Criar um foreach com uma condição especifica no PHP

Question: Tenho essa condição:
if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d'))
E tenho também um array. Para cada entrada do array preciso verificar a condição e mostrar na tela os dados da posição, e se não, preciso mostrar algo com o mesmo espaço só que com os itens vazios... Como eu poderia fazer um foreach com um condicional como esse?
o que tenho até agora é isso:
while ($arrayBancas = mysql_fetch_array($oBanca->retorno())){
   if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) {
      echo 'Nome:'. $arrayBancas['nome'];
   }
}
   if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) != $data->format('Y-m-d')) {
      echo 'Nome:----------VAZIO--------------';
   }
}

Desse jeito funciona perfeitamente para uma única entrada da condicional verdadeira do primeiro if, mas se duas ou mais entradas executarem ele, o outro não executa pela segunda ou mais vezes, e eu preciso que isso aconteça...
Comment: @Alceu E onde está o _array_ que você disse que tem? Pelo código da pergunta estou vendo que vc tem linhas de uma base de dados. Você quer um monte de campos vazios quando for dia diferente, e um monte de campos preenchidos quando for a data corrente?
Comment: O primeiro `if` é quando tem dados da banca, e o segundo quando não tem, certo? Todos os registros devem estar em um estado ou outro? Não entendi porque agora está falando em `foreach`.
Comment: E alterei a outra pergunta, talvez seja o que você quer. Esta pergunta fala de coisas que não estão presentes no código, tá difícil entender. Se é outra coisa, precisa explicar melhor.
Comment: Isso! Preciso de vários campos vazios quando o dia for diferente. Para cada registro eu preciso de vários outros vazios...
Answer: Existe uma função nativa do PHP chamada Array_map, ela aplica uma função definida (no caso a sua validação) para cada elemento do array, veja o manual dela aqui.
Você pode criar algo do tipo:
function checkCondition($pos)
{
  if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d'))
  {
    return $pos;
  }
  else
  {
   return '';
  }
}

E então você usa o array mapa mais ou menos assim:
$novo_array = array_map("checkCondition",$seuArrayAtual);

Se você der um print_r na variável $novo_array você verá que as posições para as quais a verificação é verdadeira estão preenchidas, caso contrário elas são nulas.
Comment: Você conseguiu entender a pergunta? Explica pra mim :)
Comment: Pelo que eu entendi, ele precisa fazer uma verificação a cada posição que ele ler no array, caso a verificação seja verdadeira então o array retorna o valor do próprio array, caso contrário ela seria nula.
Comment: É que ele diz: "E tenho também um array. Para cada entrada do array preciso verificar a condição e mostrar na tela os dados da posição, e se não, preciso mostrar algo com o mesmo espaço só que com os itens vazios". Ele precisa fazer a verificação para cada item do array.
Comment: Eu entendi outra coisa completamente diferente ao ponto de achar que esta resposta não chega nem perto do que ele quer.
Comment: Exatamente isso! É isso que eu preciso, enquanto percorro as posições do $arrayBancas eu preciso testar o que tem dentro e fazer uma coisa outra para todas as vezes que o percorrimento acontecer.... Vou tentar dar uma simplificada ali no código... A propósito, tô tentando aplicar esse array_map aqui e não tô conseguindo... Eu teria que adicionar os dois if dentro da função? Não está dando certo...
Comment: No caso, o while está percorrendo o $arrayBancas, que traz vários campos e várias entradas do MySQL e, para cada uma dessas entradas, preciso de campos vazios para onde o dia for diferente
Comment: Você pode substituir o else pelo outro if. Lembre-se que a função fica separada, ela não tem nada a ver com a linha do array_map


How to calculate ± deviation for precision and recall?

Question: I found a precision and recall report table like as below

Precision           Recall
.470±.009         .934±.013
.239±.010          .610±.013

I need the guidelines for ±.009 and ±.013 etc. What ± means and how to calculate it? Guide me for my situation. Thanks in advance.
Comment: probably obtained with bootstrapping, can you share where you saw it?
Comment: Please go through the link : https://www.researchgate.net/figure/Mean-Standard-Deviation-of-Precision-and-Recall-of-compared-methods-on-Spectralis-OCT_tbl2_320372468
Comment: Guide me for my situation.. Thanks..
Answer: In the paper, Page 4, it says:

...The detected cysts were then classified with texture descriptors based on Gray Level Co-occurrence Matrix (GLCM) and Gabor filters and by using classifiers such as Naive-Bayes (NB), Support Vector Machine (SVM) or Random Forest (RF) with 10-fold cross validation. The comparative evaluation in [21] indicates that GLCM + SVM and Gabor + SVM have segmentation accuracies of 0.8293 and 0.8244, respectively...

They do not specifically talk about it anywhere else in the paper, but the precision/recall mean/std values in the table you've shown were most probably calculated via these validation folds, i.e. an array of 10 precision values, and mean/std of them for example.
Comment: Thank you very much for your valuable reply. I will check with sample data and let you know. Thanks


Integral of $\frac{1}{x^2+x+1}$ and$\frac{1}{x^2-x+1}$

Question: How to integrate two very similar integrals. I am looking for the simplest approach to that, it cannot be sophisticated too much as level of the textbook this was taken from is not very high. $$\int \frac{1}{x^2+x+1} dx$$ and$$\int \frac{1}{x^2-x+1} dx$$
Comment: Partial Fraction Decomposition, Trigonometric Substitution, or completing the square should work.  Which is easiest for you?
Comment: I am fine with all of them, up to you.
Comment: Recall that there is a standard technique in algebra for reducing a problem involving a quadratic polynomial with a first-degree term to a quadratic polynomial with no first degree term. (See my answer below for details.) ${}\qquad{}$
Answer: For the first one:
$$
\int { \frac { 1 }{ 1+{ x }^{ 2 }+x }  } dx\quad =\quad \quad \int { \frac { 1 }{ { x }^{ 2 }+x+\frac { 1 }{ 4 } +\frac { 3 }{ 4 }  } dx } \\ \qquad \qquad \qquad \qquad =\quad \int { \frac { 1 }{ { \left( x+\frac { 1 }{ 2 }  \right)  }^{ 2 }+\frac { 3 }{ 4 }  } dx } \\ \qquad \qquad \qquad \qquad \quad =\quad \frac { 4 }{ 3 } \int { \frac { 1 }{ 1+{ \left( \sqrt { \frac { 4 }{ 3 }  } \left( x+\frac { 1 }{ 2 }  \right)  \right)  }^{ 2 } }  } dx\\ \qquad \qquad \qquad \qquad \quad =\quad  \frac { 2 }{ \sqrt{3} }   \arctan { \left( \frac { 2 }{ \sqrt{3} }   \left( x+\frac { 1 }{ 2 }  \right)  \right)  }  +C
$$
The second one will be the same just a minus instead of a plus:
$$
 \frac { 2 }{ \sqrt{3} }   \arctan { \left( \frac { 2 }{ \sqrt{3} }   \left( x-\frac { 1 }{ 2 }  \right)  \right)  }  +C
$$
Here's a general formula for $\int \frac{1}{ax^2+bx+c}dx$, when $b^2-4ac<0$:
$$
\int { \frac { 1 }{ a{ x }^{ 2 }+bx+c }  } dx\quad =\frac { 1 }{ a } \quad \int { \frac { 1 }{ { x }^{ 2 }+\frac { b }{ a } x+\frac { c }{ a }  }  } dx\\ \qquad \qquad \qquad \qquad \quad =\quad \frac { 1 }{ a } \int { \frac { 1 }{ { x }^{ 2 }+\frac { b }{ a } x+\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } } +\frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  } dx } \\ \qquad \qquad \qquad \qquad \quad =\quad \frac { 1 }{ a } \int { \frac { 1 }{ { \left( x+\frac { b }{ 2a }  \right)  }^{ 2 }+\frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  }  } dx\\ \qquad \qquad \qquad \qquad \quad =\quad \frac { 1 }{ a\left( \frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  \right)  } \int { \frac { 1 }{ 1+{ \left( \frac { x+\frac { b }{ 2a }  }{ \sqrt { \frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  }  }  \right)  }^{ 2 } } dx } \\ \qquad \qquad \qquad \quad =\quad \frac { \sqrt { \frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  }  }{ c-\frac { { b }^{ 2 } }{ 4a }  } \arctan { \left( \frac { x+\frac { b }{ 2a }  }{ \sqrt { \frac { c }{ a } -\frac { { b }^{ 2 } }{ 4{ a }^{ 2 } }  }  }  \right)  } +C
$$
Comment: Why not simplify $\frac43 \times \sqrt{\frac34}$?
Comment: OK. No worry.  ;-)
Comment: @Dr.MV it's good now ^^
Comment: And the square root of $4$ ... can you simplify that?
Comment: Yes if you want, leaving like that bothers you right? ^^
Comment: It doesn't bother me, but it seems simpler to write $2$.
Comment: @Dr.MV I understand I was just kidding ^^
Answer: In both cases, complete the square,  substitute, and use
$$\int\frac 1{u^2+1}\,du=\tan^{-1}u$$
Completing the square gives you
$$\int\frac 1{x^2+x+1}\,dx=\int\frac 1{\left(x+\frac 12\right)^2+\frac 34}\,dx$$
The second is similar,
$$\int\frac 1{x^2-x+1}\,dx=\int\frac 1{\left(x-\frac 12\right)^2+\frac 34}\,dx$$
Answer: HINT:
Write $x^2\pm x+1=\left(x\pm\frac12\right)^2+\frac34$.  Then, make use
$$\int \frac{1}{t^2+a^2}dt=\frac1a \arctan(t/a)+C$$
for $a>0$
SPOILER ALERT: SCROLL OVER SHADED AREA TO SEE THE ANSWER

$$\int \frac{1}{x^2\pm x+1}\,dx=\int \frac{1}{\left(x\pm\frac12\right)^2+\frac34}\,dx=\frac{2\sqrt{3}}{3}\arctan\left(\frac{2\sqrt{3}}{3}\left(x\pm \frac12\right)\right)+C$$
Comment: Please let me know how I can improve my answer.  I really just want to give you the best answer I can>
Answer: For the first one write $x^2 + x + 1 = (x + 1/2)^2 + 3/4$ and the second one $x^2 - x + 1 = (x - 1/2)^2 + 3/4$ these both are arctan
Answer: First recall that if $a,b,c$ are real numbers then $ax^2+bx+c$ can be factored using real numbers if and only if $b^2-4ac\ge 0$.  For your first polynomial above you have $a=b=c=1$ so $b^2-4ac=-3$, so you would need complex numbers to factor it.
Then recall that there is a standard technique in algebra for reducing a problem involving a quadratic polynomial with a first-degree term to a quadratic polynomial with no first degree term, namely completing the square.  You get
$$
x^2+x+1 = \left( x^2 + x + \frac 1 4 \right) + \frac 3 4 = \left( x + \frac 1 2 \right)^2 + \frac 3 4.
$$
Then you would like $\displaystyle \int \frac 1 {(\text{square})+1} \, dx$ so that you get an arctangent.  So write
$$
\left( x + \frac 1 2 \right)^2 + \frac 3 4 = \frac 3 4 \left( \left( \frac{2x+1}{\sqrt 3} \right)^2 + 1 \right) = \frac 3 4 (u^2 + 1) \quad\text{and}\quad dx = \frac{\sqrt 3} 2\, du.
$$
Answer: $$\int { \frac { dx }{ { x }^{ 2 }+x+1 } =\int { \frac { dx }{ { \left( x+\frac { 1 }{ 2 }  \right)  }^{ 2 }+\frac { 3 }{ 4 }  }  }  } =\int { \frac { d\left( x+\frac { 1 }{ 2 }  \right)  }{ { \left( x+\frac { 1 }{ 2 }  \right)  }^{ 2 }+\frac { 3 }{ 4 }  }  } =\frac { 2 }{ \sqrt { 3 }  } \arctan { \left( \frac { 2 }{ \sqrt { 3 }  } \left( x+\frac { 1 }{ 2 }  \right)  \right) \quad +C }  $$
Comment: That answer is not correct.  Remove the square root inside the arctangent and add the correct scale factor therein.
Comment: i edited thanks sir


How to manipulate the product flavours of build.gradle through java code

Question: I want to modify the token and API urls from my java code so that I can create a development or release build depending on mode selected from my custom screen.
Below is the code used in build.gradle
 productFlavors {
    dev {
        buildConfigField "String", "TOKEN_URL", '"https://example.com"'
        buildConfigField "String", "API_URL", '"https://api.ex"'
        versionCode getDevVersionCode()
    }
    prod {
        buildConfigField "String", "TOKEN_URL", '"https://release.example2.com"'
        buildConfigField "String", "API_URL", '"https://api.release.ex"'
        versionCode getReleaseVersionCode()
    }
}

Answer: first in app/build.gradle, add the productFlavor under android
productFlavors {
    qa {
        buildConfigField "boolean", "LOG_HTTP", "true"
    }
    staging {
        buildConfigField "boolean", "LOG_HTTP", "true"
    }
    live {
        buildConfigField "boolean", "LOG_HTTP", "false"
    }
}

then you need to create specific directories in app/src directory

finally, you just create a same name File in these different directories, like the following picture

in each ServerConstants(the name can be arbitrate), you should reference specific variables of "TOKEN_URL" and "API_URL"
Comment: Thanks for the reply but my requirement is i have to switch between production and development when a user chooses a radio button.Using above structure it will automatically create builds as per variables mentioned in ServerConstants.java. Suppose I have created a live build but the user wants the api url to be set of development, this is the scenario required.
Comment: if so, it has nothing to do with build.gradle. you can just decalre two static constant variable. then refer it based on user's behavior
Comment: Seems to be the only solution . Thanks for the help


Trying to get form to submit to database. Errors: Undefined index and Unedified Variable

Question: Notice: Undefined index: confirmed in
Notice: Undefined variable: fromplot1 in
 mysql_connect("$host", "$username", "$password")or die("cannot connect");

 mysql_select_db("$db_name")or die("cannot select DB");

if(isset($_POST['submit']));
{
  $confirmed=$_POST['confirmed'];

  $fromPlot1=$_POST['fromplot1'];

  $toPlot1=$_POST['toplot1'];

 $fromPlot2=$_POST['fromPlot2'];

 $toPlot2=$_POST['toplot2'];

 $trench=$_POST['trench'];

 $installDate=$_POST['installdate'];

 $pipe=$_POST['pipe'];

 $sql ="INSERT INTO $tbl_name (confirmed, fromplot1, toplot1, fromplot2, toplot2,
 trench, installdate, pipe )
 VALUES ('$confirmed','$fromplot1','$toplot1','$fromplot2','$toplot2','$trench','$installDate','$pipe)";
}
  ?>

Would be very grateful for someone to find the problem with this. New to php coding!!
Here is the form! Hope this can help. Thanks for the replies also!
<input type="checkbox" name="confirmed:" value="Confirmed"> CSEP/Mains Work Confirmed As

    Onsite Mains (Public highway)  -

From Plot:
 <input type="text"  name="fromplot1" />

 To Plot:
 <input type="text" name="toplot1" />

Offsite Mains  -

 From Plot:
 <input type="text"  name="fromplot2"  />

 To Plot:
    <input type="text"  name="toplot2" />

Is the water in the same trench? <select> <option value="Yes">Yes</option> <option value="No">No</option> </select>

                    If so, when was the water main installed?    <input type="date" name="installdate">

                    Is there sufficient pipe on site to complete the job? *<input class=mainForm type=radio name="pipe"  value="Yes" />Yes<input class=mainForm type=radio name=pipe value="No" />No

Comment: There seems no issue with the snippet you provided,let us show your form
Comment:  CSEP/Mains Work Confirmed As

Onsite Mains (Public highway)  -
From Plot:

To Plot:
Comment: I can see the text field named "fromplot1", but the html seems to be incorrect, would you please copy the entire form please?
Answer: use this
<?php

    mysql_connect("$host", "$username", "$password")or die("cannot connect");//   mysql_connect('localhost', 'user', '')or die("cannot connect");

    mysql_select_db("$db_name")or die("cannot select DB");

    if(isset($_POST['submit']))
    {
        $confirmed=$_POST['confirmed'];
        $fromPlot1=$_POST['fromplot1'];
        $toPlot1=$_POST['toplot1'];
        $fromPlot2=$_POST['fromPlot2'];
        $toPlot2=$_POST['toplot2'];
        $trench=$_POST['trench'];
        $installDate=$_POST['installdate'];
        $pipe=$_POST['pipe'];

        $sql ="INSERT INTO $tbl_name (confirmed, fromplot1, toplot1, fromplot2, toplot2,
 trench, installdate, pipe ) VALUES ('$confirmed','$fromplot1','$toplot1','$fromplot2','$toplot2','$trench','$installDate','$pipe')";

        mysql_query($sql);
    }
?>

And <input type="checkbox" name="confirmed:" value="Confirmed"> should be <input type="checkbox" name="confirmed" value="Confirmed">

Note Make sure $host, $username, $password, $tbl_name and $db_name is define.

And check form method <form method="post"..
Comment: Thank you for your help! Getting no errors now, however when I fill in the form.. It shows nothing on the database
Comment: check your `$tbl_name ` value in INSERT
Comment: can you show data inside `"$host"`, `"$username"`, `"$password"`
Comment: My answer works fine. Problem is with your connection. You are not providing resources to solve this out, So i cant help you after this. **Note there is nothing i can do with your variables**   :D. OK
Comment: Thank you so much for helping me out!


Make_shared - own implementation

Question: I am trying to make my own implementation of shared_ptr. I have problems with make_shared. The main feature of std::make_shared that it allocates counter block and object in continuous block of memory. How I can do the same?
I tried do something like that:
template<class T>
class shared_ptr
{
private:
    class _ref_cntr
    {
    private:
        long counter;

    public:
        _ref_cntr() :
            counter(1)
        {
        }

        void inc()
        {
            ++counter;
        }

        void dec()
        {
            if (counter == 0)
            {
                throw std::logic_error("already zero");
            }

            --counter;
        }

        long use_count() const
        {
            return counter;
        }
    };

    template<class _T>
    struct _object_and_block
    {
        _T object;
        _ref_cntr cntr_block;

        template<class ... Args>
        _object_and_block(Args && ...args) :
            object(args...)
        {
        }
    };

    T* _obj_ptr;
    _ref_cntr* _ref_counter;

    void _check_delete_ptr()
    {
        if (_obj_ptr == nullptr)
        {
            return;
        }

        _ref_counter->dec();

        if (_ref_counter->use_count() == 0)
        {
            _delete_ptr();
        }

        _obj_ptr = nullptr;
        _ref_counter = nullptr;
    }

    void _delete_ptr()
    {
        delete _ref_counter;
        delete _obj_ptr;
    }

    template<class _T, class ... Args>
    friend shared_ptr<_T> make_shared(Args && ... args);

public:
    shared_ptr() :
        _obj_ptr(nullptr),
        _ref_counter(nullptr)
    {
    }

    template<class _T>
    explicit shared_ptr(_T* ptr)
    {
        _ref_counter = new counter_block();
        _obj_ptr = ptr;
    }

    template<class _T>
    shared_ptr(const shared_ptr<_T> & other)
    {
        *this = other;
    }

    template<class _T>
    shared_ptr<T> & operator=(const shared_ptr<_T> & other)
    {
        _obj_ptr = other._obj_ptr;
        _ref_counter = other._ref_counter;

        _ref_counter->inc();

        return *this;
    }

    ~shared_ptr()
    {
        _check_delete_ptr();
    }

};

template<class T, class ... Args>
shared_ptr<T> make_shared(Args && ... args)
{
    shared_ptr<T> ptr;
    auto tmp_object = new shared_ptr<T>::_object_and_block<T>(args...);
    ptr._obj_ptr = &tmp_object->object;
    ptr._ref_counter = &tmp_object->cntr_block;

    return ptr;
}

But when I delete object and counter block, the invalid heap block exception occurs.
Comment: Two mandatory pieces of code that surround shared pointer management are (a) the reference counting algorithm, and (b) the actual *delete*, both of which you've chosen *not* to include in this post. We're not mind readers. Post a [**complete MCVE**](http://stackoverflow.com/help/mcve) that exhibits the actual problem. The statement "when I delete object and counter block..." suggests you're deleting *two* things that were never *directly* allocated (in fact the only direct allocation, `tmp_object`, is never retained at all).
Comment: Your implementation is missing some key features. If you add them, the solution might simply appear out of the existing code. What's missing: type-erasure for the deleter, storing a pointer unrelated to the managed object (and maybe more, like thread-safe ref counting, weak ref counting, ..) `shared_ptr` is complicated, and it took long to develop the current form.
Answer: N.B. _T is a reserved name and you must not use it for names of your own types/variables/parameters etc.
The problem is here:
void _delete_ptr()
{
    delete _ref_counter;
    delete _obj_ptr;
}

This is wrong for the make_shared case because you didn't allocate two separate objects.
The approach taken for make_shared in Boost's and GCC's shared_ptr is to use a new derived type of control block, which includes the reference counts in the base class and adds storage space for the managed object in the derived type. If you make _ref_cntr responsible for deleting the object via a virtual function then the derived type can override that virtual function to do something different (e.g. just use an explicit destructor call to destroy the object without freeing the storage).
If you give _ref_cntr a virtual destructor then delete _ref_counter will correctly destroy the derived type, so it should become something like:
void _delete_ptr()
{
    _ref_counter->dispose();
    delete _ref_counter;
}

Although if you don't plan to add weak_ptr support then there is no need to separate the destruction of the managed object and the control block, you can just have the control block's destructor do both:
void _delete_ptr()
{
    delete _ref_counter;
}

Your current design fails to support an important property of shared_ptr, which is that the  template<class Y> explicit shared_ptr(Y* ptr) constructor must remember the original type of ptr and call delete on that, not on _obj_ptr (which has been converted to T*). See the note in the docs for the corresponding constructor of boost::shared_ptr.  To make that work the _ref_cntr needs to use type-erasure to store the original pointer, separate from the _obj_ptr in the shared_ptr object, so that _ref_cntr::dispose() can delete the correct value. That change in the design is also needed to support the aliasing constructor.
class _ref_cntr
{
private:
    long counter;

public:
    _ref_cntr() :
        counter(1)
    {
    }

    virtual ~_ref_cntr() { dispose(); }

    void inc()
    {
        ++counter;
    }

    void dec()
    {
        if (counter == 0)
        {
            throw std::logic_error("already zero");
        }

        --counter;
    }

    long use_count() const
    {
        return counter;
    }

    virtual void dispose() = 0;
};

template<class Y>
struct _ptr_and_block : _ref_cntr
{
    Y* _ptr;
    explicit _ptr_and_block(Y* p) : _ptr(p) { }
    virtual void dispose() { delete _ptr; }
};

template<class Y>
struct _object_and_block : _ref_cntr
{
    Y object;

    template<class ... Args>
    _object_and_block(Args && ...args) :
        object(args...)
    {
    }

    virtual void dispose() { /* no-op */ }
};

With this design, make_shared becomes:
template<class T, class ... Args>
shared_ptr<T> make_shared(Args && ... args)
{
    shared_ptr<T> ptr;
    auto tmp_object = new shared_ptr<T>::_object_and_block<T>(args...);
    ptr._obj_ptr = &tmp_object->object;
    ptr._ref_counter = tmp_object;

    return ptr;
}

So _ref_counter points to the allocated control block and when you do delete _ref_counter that means you you have a correctly-matched new/delete pair that allocates and deallocates the same object, instead of creating one object with new then trying to delete two different objects.
To add weak_ptr support you need to add a second count to the control block, and move the call to dispose() out of the destructor, so it is called when the first count goes to zero (e.g. in dec()) and only call the destructor when the second count goes to zero. Then to do all that in a thread-safe way adds a lot of subtle complexity that would take much longer to explain than this answer.
Also, this part of your implementation is wrong and leaks memory:
void _check_delete_ptr()
{
    if (_obj_ptr == nullptr)
    {
        return;
    }

It's possible to constructor a shared_ptr with a null pointer, e.g. shared_ptr<int>((int*)nullptr), in which case the constructor will allocate a control block, but because _obj_ptr is null you will never delete the control block.
Comment: Wow! It's amazing. But I have a question about weak_ptr support. When there are no `shared_ptr`s I should delete _obj_ptr. But when there are still some `weak_ptr`s, I still should maintain `_ref_cntr` object, right? But when this `_ref_cntr` is  `_object_and_block`, I can't delete _obj_ptr without deleting _ref_cntr.
Comment: Yes, that's right. In GCC's implementation my equivalent of `_object_and_block` doesn't have a member of type `Y`, instead it has a buffer of raw memory of type `std::aligned_storage::type`, and it then creates the `Y` in that buffer using placement new, and  `dispose()` does `reinterpret_cast(&buffer)->~Y()` to destroy it. This allows the lifetime of the `Y` object to end sooner than the lifetime of the `_object_and_block` that contains it.
Comment: `_object_and_block` is only used when `make_shared` gets called, and that doesn't support a custom deleter. For custom deleters you need another derived type, like `_ptr_and_deleter_and_block` which stores `Y*` and `D` (and similar for custom allocators).
Comment: So, even in GCC, memory for object releases only when the last `weak_ptr` dies?
Comment: Yes, that's true for all `make_shared` implementations I know of.
Comment: I've got another issue about custom deleter. What should I do if `_ref_cntr` is `_object_and_block` and custom deleter passed? Deleter gets pointer to object as argument, but when it's a field in `_object_and_block` it can cause problems.
Comment: As usual, Jonathan, this answer absolutely rocks. I wish I could uptick it a few more times. Really nice work.
Comment: @WhozCraig, thanks :) Implementing `shared_ptr` is subtle and complicated, but doesn't require any actual magic, so I'm happy to be able to share how it works

Make_shared - own implementation


Adding pager to queried content in a custom module Drupal 8

Question: I've created a custom module to get X items using entityQuery, and then display them as a list. I need to limit these and add a pager to click through to the next page, but I cannot find how best to do this. Examples I've found either use external search sources, or are depreciated functions of older versions of Drupal.
I've added the pager option in the query, initialized the pager, and added the #type = pager to the content block, but it's not showing up. I know I am missing something but I cant figure out what it is.
class MyPageController extends ControllerBase {

public function myPage1() {

    $query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'page')
    ->range(0, 10)
    ->pager(3)
    ->sort('created', 'DESC');

    $nids = $query->execute();
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

    pager_default_initialize($query->total, '7');

    $list = array();

    foreach ($nodes AS $node){
        $list[] = $node->get('title')->value;
    }

    $content = [
        '#theme' => 'item_list',
        '#list_type' => 'ul',
        '#title' => 'Page list',
        '#items' => $list,
        '#attributes' => ['class' => 'my_page1_list'],
        '#wrapper_attributes' => ['class' => 'container'],
        '#type' => ['pager'],
    ];

    return $content;
}
}

Answer: The format of the render array is wrong, you have to place the pager in its own render element (see this question, which was almost at the same time Pager with EntityQuery) or if you want to have it in the theme in a variable, but then a name other than #type.


Erro ao rodar aplicação Web em flask - Python

Question: Olá, estou tentando rodar essa aplicação em Flask e quando tento visualizar a página no navegador aparece erro de servidor, quando eu apago a linha do código que cria uma lista de itens em que cada item é um link para outra página o erro some, então tenho certeza que o erro está nessa parte do código:

 {% for i in range | atividades %}

{{{{atividades[i]}}}}

 {% endfor %}

Estou chamando o template dessa forma no arquivo python:
@app.route("/")
def index():
    atividades = ["Estudar","Programar", "Praticar Karate", "Trabalhar", "Hobbies"]
    link_atividades = ["estudar.html","programar.html" ,"praticar_karate.html" ,"trabalhar.html" ,"hobbies.html"]
    return render_template("index.html", atividades=atividades, link_atividades=link_atividades)

Alguém consegue me ajudar ?
Comment: Coloque ali na pergunta como você está chamando esta view também,
Comment: Obrigado pela dica, ja adicionei.
Answer: Tente usar algo como:
Em sua rota:
atividades = [
    {
        'atividade':"Estudar",
        'url':"estudar.html"
    },
    {
        'atividade':"Programar",
        'url':"programar.html"
    },
    {
        'atividade':"Particar Karate",
        'url':"praticar_karate.html"
    },
    {
        'atividade':"Trabalhar",
        'url':'trabalhar.html'
    },
    {
        'atividade':"Hobbies",
        'url':'hobbies.html'
    }
]

Em em seu template:
<select>
{% for atividade in atividades %}

{{{{atividade.atividade}}}}

{% endfor %}
</select>


Quasi-isomorphisms are stable under homotopy base change in $\operatorname{Ch}(\mathcal{A})$

Question: Edit: People are commenting that what I'm trying to do follows from "general theory of model categories" or "general theory of categories of fibrant objects". I have no idea at all of any of these theories and reading the definition from nLab does not tell me much. I only know a little of category theory and some theory of abelian categories. Here I give an elementary proof that only relies on abelian category theory. Any detailed explanation of how any of this exactly follows from more general abstract nonsense is very welcome, specially if it explains what is the model structure / fibrant objects structure on $\operatorname{Ch}(\mathcal{A})$ from necessary to make it work.
Before stating my question, I will explain the theoretical background. Let $\mathcal{A}$ be an additive category. In the category $\operatorname{CoCh}(\mathcal{A})$ of cochain complexes we can define an homotopy pullback in the following way: given morphisms $f:A\to C$ and $g:B\to C$ in $\operatorname{CoCh}(\mathcal{A})$, we define $A\times^h_CB$ as the cochain complex $(A\times^h_CB)^i=A^i\oplus B^i\oplus C^{i-1}$ with differential $d^i:(a,b,c)\mapsto(d^i_A(a),d^i_B(b),f^i(a)-g^i(b)-d^{i-1}_C(c))$. We have canonical projections
\begin{align*}
p&:A\times_C^hB\to A\\
q&:A\times_C^hB\to B
\end{align*}
such that the canonical projection $h^i:(A\times_C^hB)^{i}=A^{i}\oplus B^{i}\oplus C^{i-1}\to C^{i-1}$ defines the components of a cochain homotopy $h:fp\cong gq$. The object $A\times^h_CB$ is characterized by a universal property. Given a cochain complex $D$, define the set of triples
$$
\operatorname{Hom}(D,(f,g))
=\{(\tilde{f},\tilde{g},\tilde{h})\mid \tilde{f}:D\to A,\;\tilde{g}:D\to B
\text{ and } \tilde{h} \text{ is a cochain homotopy from } f\tilde{f}\text{ to }g\tilde{g}\}.
$$
Then $\operatorname{Hom}(-,(f,g))$ is a functor $\operatorname{CoCh}(\mathcal{A})^\mathrm{op}\to\mathsf{Set}$. This way, $A\times_C^hB$ is the cochain complex representing $\operatorname{Hom}(-,(f,g))$. That is, the map
\begin{align*}
\operatorname{Hom}_{\operatorname{CoCh}(\mathcal{A})}(D,A\times_C^hB)
&\to\operatorname{Hom}(D,(f,g))\\
\alpha&\mapsto(p\alpha,q\alpha,h\alpha)
\end{align*}
defines the components of a natural isomorphism of functors $\operatorname{CoCh}(\mathcal{A})^\mathrm{op}\to\mathsf{Set}$. Where $(h\alpha)^i=h^i\alpha^i:D^i\to C^{i-1}$.
I was trying to show the result "quasi-isomorphisms are stable under homotopy base change". That is, if in the diagram
$\require{AMScd}$
\begin{CD}
A\times^h_C B @>{p}>> A\\
@V{q}VV @VV{f}V\\
B @>>{g}> C
\end{CD}
(which commutes up to homotopy) we have that $g$ is a quasi-isomorphism (induces isomorphisms on all homology objects), then $p$ is a quasi-isomorphism. The following is the proof I was trying to construct:
We have a short exact sequence of chain complexes
$$
\tag{1}\label{1}
0\to C[-1]\to A\times_C^hB\xrightarrow{p\times q} A\oplus B\to 0,
$$ where the left map is the inclusion and the second one is the projection on the two first components. If we apply the result "short exact sequence of chain complexes induces long exact sequence on homology" to \eqref{1}, we obtain a LES
$$
\tag{2}\label{2}
\cdots \longrightarrow H^{i-1}(C) \longrightarrow H^{i}\left(A \times_{C}^{h} B\right) \xrightarrow{H^i(p)\times H^i(q)} H^{i}(A) \oplus H^{i}(B) \longrightarrow H^{i}(C) \longrightarrow \cdots
$$
Although I haven't worked out the details for an arbitrary additive category $\mathcal{A}$, for the category $\mathcal{A}=\mathsf{Ab}$ of abelian groups the boundary map $H^{i}(A) \oplus H^{i}(B) \to H^{i}(C) $ equals $H^i(f)-H^i(g)$. This is because in the commutative diagram of abelian groups with exact rows
$\require{AMScd}$
$$
\begin{CD}
@. C^{i-1}@>>> A^i\oplus B^i\oplus C^{i-1}@>>> A^i\oplus B^i@>>>0\\
@. @V{d^{i-1}_C}VV @V{d^i_{A\times_C^hB}}VV @V{d^i_A\oplus d^i_B}VV\\
0@>>> C^i@>>> A^{i+1}\oplus B^{i+1}\oplus C^{i}@>>> A^{i+1}\oplus B^{i+1}
\end{CD}
$$
we can do the chase

Now, if $H^i(g)$ is an isomorphism, in particular it is an epimorphism and thus the map $H^i(f)-H^i(g)=H^i(f)\amalg(-H^i(g))$ is also an epimorphism (follows from the identity $k(l\amalg m)=kl\amalg km)$ for the coproduct). This way, $H^{i-1}(C)\to H^i(A\times_C^hB)$ is the zero map (by exactness of \eqref{2}) and we get a SES
$$
0\to H^{i}\left(A \times_{C}^{h} B\right) \xrightarrow{H^i(p)\times H^i(q)} H^{i}(A) \oplus H^{i}(B) \xrightarrow{H^i(f)-H^i(g)} H^{i}(C)\to 0.
$$
This SES is split as $0\times (-H^i(g)^{-1})$ is a section of $H^i(f)-H^i(g)$.
And here is where I get stuck. How can I conclude that $H^i(p)$ is an isomorphism using that $H^i(g)$ is an iso? I was trying to prove it following the proof of the splitting lemma but that didn't work.
Comment: You can refer to §9.2 and §§4.1–4.2 of [my notes](http://zll22.user.srcf.net/writing/homotopical-algebra/2015-11-10-Main.pdf) for details.
Comment: I haven't read most of what you've written but if your homotopy pullback construction is a homotopy pullback in the usual sense (e.g. on the correct model category structure on $\mathbf{CoCh}$), then this is a consequence of the formal fact that weak equivalences are stable under homotopy pullbacks.
Comment: @QiZhu I don't know anything about model categories. Any source/reference/book recommendation where I could look that up?
Comment: I'm not sure about a reference for this fact. You can check out the notes on homotopy coherent algebraic structures from Bonn this semester where he proves the dual statement (for homotopy pushouts) in Corollary 3.41. He only shows it for $\mathbf{sSet}$ because he only proved the Gluing Lemma for $\mathbf{sSet}$ but this fact holds more generally as e.g. stated in this semester's Algebraic Topology 2 lecture. These notes all manage to avoid mentioning the word 'model category'.
Comment: It's probably also in the book Modern Classical Homotopy Theory by Strom but I suspect that he might also only show this for spaces.
Comment: There is no need for the machinery of model categories here (and, anyway, it is not applicable in general). It suffices to show that the category of cochain complexes has the structure of a category of fibrant objects where the weak equivalences are quasi-isomorphisms. (In principle you also need to show that every chain homotopy equivalence is also a quasi-isomorphism.) Then the general theory of categories of fibrant objects tells you that quasi-isomorphisms are preserved by homotopy pullback.
Comment: (The references I gave btw also play in fibration categories since Schwede only covered cofibration categories and not model categories in this semester's lecture.)
Answer: Here is the step missing:

Lemma. Let $\mathcal{A}$ be an abelian category, and let $f:A\to B$, $g:A\to C$, $h:B\to D$, and $k:C\to D$ be morphisms in $\mathcal{A}$. It holds:

If the sequence
$$
0\to A\xrightarrow{f\times g}B\oplus C\xrightarrow{h\amalg k}D\to 0
$$
is short exact, then $k$ being an isomorphism implies $f$ is an isomorphism.
$\operatorname{Im}(\operatorname{Im}(f\times g)\to B\oplus C\xrightarrow{p} B)=\operatorname{Im}f$, where $p$ is the canonical projection.

Proof. For proving 1 we will need 2, so we prove 2 first. Note the result is obvious for $\mathcal{A}=\mathsf{Ab}$ the category of abelian groups, but in the general case we have to work with universal properties of (co)kernels.
Denote $h$ to the composite $\operatorname{Im}(f\times g)\to B\oplus C\xrightarrow{p} B$, so we want to show that $\operatorname{Im}h=\operatorname{Im}f$. We claim that the composite $\operatorname{Im}f\to B\to\operatorname{Coker}h$ vanishes. We can verify nullity after pre-composition with $A\to\operatorname{Im}f$, as the latter is epic (here we are using abelianity of $\mathcal{A}$). By commutativity of the following diagram, the claim follows from the fact that $(\operatorname{coker}h)\cdot h=0$.

Now we show $\operatorname{Im}f$ shows the universal property of an image of $h$. Suppose $D\to B$ is a map such that the composite $D\to B\to\operatorname{Coker} h$ vanishes. It suffices to show that there exists a dotted arrow $\operatorname{Coker}h\dashrightarrow\operatorname{Coker}f$ that makes the following diagram commutative

because on that case, the morphism $D\to B$ will factor through $\operatorname{Im}f$ since it is the kernel of $B\to\operatorname{Coker}f$. Uniqueness of the factorization will come from the fact that $\operatorname{Im}f\to B$ is monic (since it is a kernel). To construct the dotted arrow, we use the universal property of $\operatorname{Coker}h$. To verify that $(\operatorname{coker} f)pi$ vanishes, we can verify it after pre-composition with $k$ (again, by abelianity of $\mathcal{A}$, $k$ is a surjection), and we have $(\operatorname{coker} f)pik=(\operatorname{coker} f)p(f\times g)=(\operatorname{coker} f)f=0$.
We now prove 1. It suffices to prove the claim for $C=D$ and $k=-1_C$, as we have an isomorphism of short exact sequences
$\require{AMScd}$
$$
\begin{CD}
0@>>> A@>{f\times g}>> B\oplus C@>{h\amalg k}>>D@>>>0\\
@.@|@|@VV{-k^{-1}}V\\
0@>>> A@>>{f\times g}> B\oplus C@>>{(-hk^{-1})\amalg(-1_C)}>C@>>> 0
\end{CD}
$$
We show then that if
$$
\tag{3}\label{3}
0\to A\xrightarrow{f\times g}B\oplus C\xrightarrow{h\amalg(-1_C)}C\to 0
$$
is short exact, then $f$ is an isomorphism. With the purpose of understand why the result is true, we show it first for $\mathcal{A}=\mathsf{Ab}$ the category of abelian groups. Really the general proof is just the categorification of this particular case. If \eqref{3} is exact, we have that
$$
\tag{4}\label{4}
\{(f(a),g(a))\mid a\in A\}
=\operatorname{Im}(f\times g)
=\operatorname{Ker}(h\amalg(-1_C))
=\{(b,h(b))\mid b\in B\}.
$$
From the equality of the leftmost side with the rightmost one, it follows at once that $f$ is surjective. But from this equality it also follows that $g(a)=h(f(a))$ for all $a\in A$, so $g=hf$. From here we deduce that $f$ is injective, since $f\times g$ is injective: $f(a)=f(a')$ implies
$$
(f\times g)(a)=(f(a),g(a))=(f(a),h(f(a)))=(f(a'),h(f(a')))=(f\times g)(a')
$$
which in turn implies $a=a'$. Hence $f$ is bijective.
Now we give the proof for a general abelian category $\mathcal{A}$. We cannot consider elements anymore, but we can still work with universal properties. As we did before, we will show first that $f$ is onto and then that it is injective. From the fact that $\mathcal{A}$ is balanced (abelian categories are), it will follow that $f$ is an isomorphism.
We need an abelian-category-theoretic way of expressing the RHS of \eqref{4}. This RHS corresponds to $\operatorname{Im}(1_B\times h)$, so we will show that
$$
\tag{5}\label{5}
\operatorname{Ker}(h\amalg(-1_C))=\operatorname{Im}(1_B\times h).
$$
We show that $\operatorname{Im}(1_B\times h)$ is a kernel of $h\amalg(-1_C)$. For that, we first have to show that the composite $\operatorname{Im}(1_B\times h)\to B\oplus C\xrightarrow{h\amalg(-1_C)}C$ vanishes. But this is easy, using the image factorization of $1_B\times h$ and the fact that $B\to\operatorname{Im}(1_B\times h)$ is surjective as $\mathcal{A}$ is abelian, as $(h\amalg(-1_C))\cdot(1_B\times h)=h-h=0$.

We prove that the RHS of \eqref{5} satisfies the UP of the LHS. Suppose $k\times\ell:D\to B\oplus C$ is a morphism such that $0=(h\amalg(-1_C))\cdot(k\times\ell)=hk-\ell$. Thus $\ell=hk$.
We get a solid commutative diagram

By commutativity of the right upper triangle, the vertical composite $D\xrightarrow{k\times\ell}B\oplus C\to \operatorname{Coker}(1_B\times h)$ vanishes, so $k\times\ell$ factors through $\operatorname{Im}(1_B\times h)$ via the dotted arrow of the last diagram. Uniqueness of the factorization comes from the fact that $\operatorname{Im}(1_B\times h)\to B\oplus C$ is monic.
This shows \eqref{5}. Using this equation and exactness of \eqref{3}, we deduce that
$$
\operatorname{Im}(f\times g)=\operatorname{Im}(1_B\times h).
$$
From this last equality plus point 1 of the lemma, it follows that $f$ and $1_B$ have same image, i.e., $\operatorname{Im}f=B$ and $f$ is surjective (this is the substitute of the inference we did in the case of abelian groups to conclude surjectiveness then). It is left to see that $f$ is injective. As it was the case before, we claim that $hf=g$ holds now as well. To see this, note that $1_B\times h$ is injective (in abelian categories, the product of a monomorphism with any other map is a monomorphism), so $\operatorname{im}(1_B\times h)=1_B\times h$, as in a preabelian category the image of a monomorphism is the map itself. Hence, we can use the image factorization of $f\times g$ to get a factorization

That is, $f\times g=(1_B\times h) f'=f'\times hf'$. Therefore $f=f'$ and $g=hf$.
Lastly, since $f\times g=f\times hf=(1_B\times h)f$ is injective, we deduce that $f$ is also injective. $\square$
Comment: This (elementary) proof does not use the fact that the SES $$0\to A\xrightarrow{f\times g}B\oplus C\xrightarrow{h\amalg(-1_C)}C\to 0$$ is split. Perhaps a shorter proof could be carried out exploiting this fact? As I said on the question, I could not figure this out by myself.
Answer: Okay, I've found an easier proof of the same lemma from my last answer, which I here restate

Lemma. Let $\mathcal{A}$ be an abelian category, and let $f:A\to B$, $g:A\to C$, $h:B\to D$, and $k:C\to D$ be morphisms in $\mathcal{A}$, and suppose the sequence
$$
0\to A\xrightarrow{f\times g}B\oplus C\xrightarrow{h\amalg k}D\to 0
$$
is short exact. Then $k$ being an isomorphism implies $f$ is an isomorphism.

Proof. As we argued in the other answer, without loss of generality we may assume $k=1_C$, since we have an isomorphism of short exact sequences
we have an isomorphism of sequences
$\require{AMScd}$
$$
\begin{CD}
0@>>> A@>{f\times g}>> B\oplus C@>{h\amalg k}>>D@>>>0\\
@.@|@|@VV{k^{-1}}V\\
0@>>> A@>>{f\times g}> B\oplus C@>>{(hk^{-1})\amalg(1_C)}>C@>>> 0
\end{CD}
$$
But we also have an isomorphism of complexes
$\require{AMScd}$
$$
\tag{$\star$}\label{diag}
\begin{CD}
0@>>> A@>{\begin{pmatrix} f\\ g\end{pmatrix}}>> B\oplus C@>{(h,1_C)}>>C@>>>0\\
@.@|@VV{\begin{pmatrix} 1_B&0\\ h&1_C\end{pmatrix}}V@|\\
0@>>> A@>>{\begin{pmatrix} f\\ 0\end{pmatrix}}> B\oplus C@>>{(0,1_C)}>C@>>> 0
\end{CD}
$$
Here we are using matrix calculus. The matrix in the middle is invertible for its inverse is $\begin{pmatrix} 1_B&0\\ -h&1_C\end{pmatrix}$.
In \eqref{diag} the three vertical morphisms indeed define a chain map, since the right square clearly commutes and the left square commutes as $0=hf+g$, for the top sequence is a complex.
Therefore, in \eqref{diag}, if the top complex is short exact so is the bottom one. On this case, the kernel of $(0,1_C)$, i.e., $\begin{pmatrix} 1_B\\ 0\end{pmatrix}:B\to B\oplus C$, by exactness coincides with the image of $\begin{pmatrix} f\\ 0\end{pmatrix}$. Therefore

is the factorization of $\begin{pmatrix}f\\0\end{pmatrix}$ through its image. Since $\begin{pmatrix}f\\0\end{pmatrix}$ is injective and $\mathcal{A}$ is abelian, the morphism into the image, $f$, becomes an isomorphism.


Is there a finite ring whose rank is smaller than the rank of its group and its monoid?

Question: Consider a finite ring $(R, +, \times)$ comprising a finite additive abelian group $(R, +)$, a finite multiplicative monoid $(R, \times)$, and a distributivity rule relating the two. Let the rank of the ring be the minimum size of a set that generates the ring (that is, a set $S$ of ring elements such that the closure of $S$ under both addition and multiplication is $R$). The rank of this ring is bounded above by the smaller of the rank of the additive group and the rank of the multiplicative monoid, since a generating set for either the group or the monoid is a generating set for the ring.
Is there a finite ring whose rank is strictly less than both the rank of its group and the rank of its monoid? In other words, is there a ring in which the combination of both addition and multiplication allows us to generate more elements than using either operation individually?
Answer: Yes, there is. An example is $R=\mathbb{Z}_2\times\mathbb{Z}_2\times\mathbb{Z}_2$.
Indeed, the rank of $R$ as a ring is $2$: it is generated by $(1,1,0)$ and $(0,1,1)$.  On the other hand, its rank as an abelian group is $3$.
It remains to be shown that the rank of the multiplicative monoid of $R$ is at least $3$.  Note that a generating set of this monoid has to contain $(1,1,1)$.  This element is not sufficient for generating $R$; nor is any set of the form $\{(1,1,1),(a,b,c)\}$, since this set only generates itself as a monoid.  Thus the rank of the multiplicative monoid of $R$ is at least $3$.
In fact, I think the rank of $R$ as a multiplicative monoid is $4$, with generating set $\{(1,1,1), (1,1,0), (1,0,1), (0,1,1)\}$. In any case, the above argument shows that $R$ is such that its rank as a ring is strictly smaller than   both the rank of its abelian group and that of its monoid.

Edit: As per Eric Wofsey's comment, if by the rank of a monoid $R$ one means the smallest cardinal of a subset $S$ such that $R$ is the smallest submonoid containing $S$, then the rank of the monoid in my example above is $3$, not $4$ (since $(1,1,1)$ will be automatically contained in any submonoid).
Comment: You don't need to include $(1,1,1)$ in the generators as a multiplicative monoid, since the unit is part of the structure of a monoid.
Answer: Let me generalize Pierre-Guy Plamondon's example.  Let $p$ be a prime and let $R=\mathbb{F}_p^n$.  Then the additive rank of $R$ is $n$.  If $x\in R$ has exactly one coordinate which is $0$ and $x=yz$, then at least one of $y$ and $z$ must have that same coordinate as its only coordinate which is $0$.  Thus the multiplicative rank is at least $n$, since any generating set must contain an element which has exactly one coordinate which is zero, for each possible coordinate.  (For $p=2$ the rank is exactly $n$; for $p>2$ it will be $2n$, since the group of units has rank $n$, and any set of multiplicative generators must also contain a set of generators for the units.)  But I claim the rank of $R$ as a ring is only $\lceil\log_p n\rceil$.   For each $i<\lceil\log_p n\rceil$ let $x_i\in R$ be the element whose $k$th coordinate is the $i$th base $p$ digit of $k$.  Then the set $\{x_i:0\leq i<\lceil\log_p n\rceil\}$ separates coordinates, and it follows that it generates $R$ as a ring (in general, if $K$ is a field, then (unital) $K$-subalgebras of $K^n$ are determined by the coordinates they separate).  Conversely, it is easy to see that no subset of $R$ of cardinality less than $\lceil\log_p n\rceil$ can separate coordinates, and thus no smaller set can generate the ring.
In particular, taking $p\geq n$, this gives rings which are generated by a single element as a ring but require arbitrarily large numbers of elements to generate either additively or multiplicatively.
Comment: Can you clarify what "separating coordinates" means?
Comment: A subset $S\subseteq R^n$ separates coordinates if for each $i,j\in\{1,\dots,n\}$ with $i\neq j$, there exists $s=(s_1,\dots,s_n)\in S$ such that $s_i\neq s_j$.


Why does "Competed" container result in "CrashLoopBackOff" pod?

Question: My question is highly related to Back-off restarting failed container - Error syncing pod in Minikube. I came across the same issue. My question is:
Why does "Competed" container result in "CrashLoopBackOff" pod? Per https://sysdig.com/blog/debug-kubernetes-crashloopbackoff/, "CrashLoopBackOff" means "you have a pod starting, crashing, starting again, and then crashing again." But my pod is not crashing at all because the container in it exits without any error. The "starting again" is expected because the default restart policy is Always.
Answer: A Deployment is supposed to keep on running performing something, responding to user request, etc. It's not supposed to end, until told to. If you want to run something to completion, you have to deploy a Job. You can use a Job if you want to run it once for example, or a CronJob if you want to run it on schedule.
As per the comment, you created a Pod without a controller. The API documentation clearly stipulates:

It is recommended that users create Pods only through a Controller, and not directly. See Controllers: Deployment, Job, or StatefulSet.

In essence, this isn't a standard way to deploy.
Comment: Thanks! But in my use case, I actually created a Pod instead of a Deployment. What I expect is that the pod will be `Succeeded` once the container is `Completed`. But the Pod still shows "CrashLoopBackOff", and then becomes "Running" because of the container restart policy. So the Pod status is like `Running-->CrashLoopBackOff-->Running-->CrashLoopBackOff-->...`
Answer: I guess you hit the confusion of another community contributors, as so far output of kubectl get pod command doesn't show Pod phase in the corresponded STATUS column, but it actually retrieves the state from particular container inside the Pod, you can find relevant information under containerStatuses: field from within a Pod description, I was answering the same behavior here.
Find the related Github issue addressed #76619 and relevant pull requests #13840, #12397.


XPTemplate new snippet for a new language - how?

Question: Okey, simple problem, but I'm stupid and am not seeing it.
Can somebody give me an example what needs to be done to create a new snippet (preferably if someone could give a simple example) for a new language in XPTemplate (Vim plugin).
Its syntax files are a total mess from my point of view.
Answer: Reading the documentation is always a good way to start. In doc/xpt.snippet.syn.txt you'll see details on the syntax of their template files.
<code> A snippet file looks like this : >
        XPTemplate priority=lang keyword=$  | |xpt-snippet-header|

        let s:f = XPTfuncs()            | |xpt-snippet-function|

        XPTvar $TRUE          true      | |xpt-snippet-variable|
        XPTvar $FALSE         false             |
        XPTvar $NULL          null              |
        XPTvar $UNDEFINED     undefined         |
                                                        |
        XPTvar $CL  /*                          |
        XPTvar $CM   *                          |
        XPTvar $CR   */                         |
                                                        |

        XPTinclude              | |xpt-snippet-XPTinclude|
              \ _common/common                  |
              \ _comment/doubleSign             |
              \ _condition/c.like               |

        fun! s:f.js_filename()          | |xpt-snippet-function|
            return expand( "%" )            |
        endfunction                             |

        XPTemplateDef               | |XPTemplateDef|

        XPT cmt hint=/**\ @auth...\ */      | |xpt-snippet|
        XSET author=$author                     | |xpt-snippet-XSET|
        XSET email=$email                       | |xpt-snippet-XSET|
        /**                                     |\
        * @author : `author^ | `email^          | \
        * @description                          |  +|xpt-snippet-body|
        *     `cursor^                          | /
        * @return {`Object^} `desc^             |/
        */

        XPT for hint=for\ (var..;..;++)
        ... </code>
I personally prefer NerdSnippets which has a very simple snippet template syntax.
Comment: Of course. And naturally, I wouldn't ask it were it clear from the help. Unfortunatelly, although the snippet syntax help file is in the help, the "syntax tutor" is still unwritten, and I'm having problems finding out what goes where (the general organisation). That's why I asked for an example if anyone has perhaps written some.


How to wait for all completionHandler blocks to complete before proceeding?

Question: Have been using the Google Drive iOS SDK, and trying to build a list of folder contents, which includes the folder parent-folders & sub-folders.
The Google Drive iOS SDK stuff is simple enough, but given the sample code below, how do I wait for all "queryForFilesGetWithFileId" completionHandler blocks to complete before proceeding?
The reason is that addFolderChildren adds the sub-folders & then refreshes the view, which obviously needs to be done last.
GTLQueryDrive *query = [GTLQueryDrive queryForParentsListWithFileId:folderId];
[self.driveService executeQuery:query
              completionHandler:^(GTLServiceTicket *ticket,
                                  GTLDriveParentList *parents,
                                  NSError *error)
 {
     if (error == nil)
     {
         for (GTLDriveParentReference *parent in parents)
         {
             if ([parent.isRoot intValue] == 1)
             {
                 // add folder root -> "My Drive"
             }
             else
             {
                 GTLQueryDrive *query = [GTLQueryDrive queryForFilesGetWithFileId:parent.identifier];
                 [self.driveService executeQuery:query
                               completionHandler:^(GTLServiceTicket *ticket,
                                                   GTLDriveFile *file,
                                                   NSError *error)
                  {
                      if (error == nil)
                      {
                          // add folder parent -> file.title
                      }
                      else
                      {
                          [self handleFailed:error];
                      }
                  }];
             }
         }
         // add folder children
         // how do we wait here until all above queryForFilesGetWithFileId completionhandler blocks are done?
         [self addFolderChildren:folderId];
     }
     else
     {
         [self handleFailed:error];
     }
 }];

Comment: You can keep an index for parents count and decrease 1 at completion. Then you can update your ui when you reach to 0.
Comment: Thanks @BoranA, nice workaround until I'm able to tame NSOperation/Queue, GCD etc. for an elegant solution.
Comment: Ok then, this the more elegant one. Subclass NSOperation, create a property for your completion block. Create an operation queue and set maxconcurrency to 1 and add your operations to the queue. If you want to be sure about the fifo order you should set priorities or dependencies of the queue.
Answer: you can use @protocol for this
like
@protocol MeuDelegate <NSObject>
@optional

-(void) meuEditingDone:(Meu*) meu;

@end

@interface EditMeu : MeuBasicViewController {

    id <MeuDelegate> delegate;
}

@property (retain) id delegate;

@end

and in the .m file do followings
@synthesize delegate;

call this method in your completion handler , so form there you can proceeds.


No icon for PrimeFaces checkboxed tree nodes in non-selecteable state?

Question: I am using PrimeFaces and I created a checkbox Tree.
Some nodes have no children, so I set them to not selectable:
<code>    node.setSelectable( false);
</code>
The problem is, nodes that are not selectable show no checkbox at all. They have no icon for this "disabled" state. It's just empty space and doesn't look good.
Is this expected behaviour or am I missing something?
p.s.
Screenshot here.
Answer: This is expected behaviour. Might be changed in future versions.


Save captured png as arraybuffer

Question: I'm trying to save an image to dropbox, and having trouble getting the convertion correct. I have an img (captured using this sample) and I want to store it to dropbox that accepts an ArrayBuffer (sample here)
This is the code I found that should to the two conversions, first to a base64, then into a ArrayBuffer
<code>    function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

function base64ToArrayBuffer(string_base64) {
    var binary_string = window.atob(string_base64);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    for (var i = 0; i < len; i++) {
        var ascii = binary_string.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes.buffer;
}
</code>
Saving is started like this
<code>     var img = $('#show-picture')[0];
    var data = base64ToArrayBuffer( getBase64Image(img));
    dropbox.client.writeFile(moment().format('YYYYMMDD-HH-mm-ss')+'.png', data, function (error, stat) {
        if (error) {
            return dropbax.handleError(error);
        }
        // The image has been succesfully written.
    });
</code>
Problem is that I get a corrupted file saved, and is a bit confused on what's wrong.
*EDIT *
Here's the link to the original file
https://www.dropbox.com/s/ekyhvu2t6d8ldh3/original.PNG and here to the corrupted. https://www.dropbox.com/s/f0oevj1z33brpur/20131219-22-23-14.png
I'm using this version of the dropbox.js: //cdnjs.cloudflare.com/ajax/libs/dropbox.js/0.10.2/dropbox.min.js
As you can see the corrupted is slighty bigger 23,3KB vs 32,6 KB
Thanks for any help
Larsi
Comment: What browser and what version of the Dropbox library? And what's wrong with the image that's saved? (I assume by "corrupted" you mean that it won't open in whatever tool you're using... any more hints? Is the file size reasonable?) I just did a very similar test (`toDataURL`, `atob`, and `Uint8Array`) with Chrome on OS X and https://www.dropbox.com/static/api/dropbox-datastores-1.0-latest.js, and it seems to work.
Comment: Hi @smarx ! Thanks for looking into this. I've added links to the original and corrupted file
Comment: @smarx I've just tried with the latest dropbox.js  and its working. Thanks for your update. Post an answer and I'll accept it.
Comment: I used `canvas.toDataURL('png')` and store it in a variable: `data` and then i coded `client.writeFile('image.png',data, callback)`...the file is ceated but it is corrupted i.e no contents to display. What could be the error?
Answer: Moving my comment to an answer, since it seems that this works in the latest Datastore JS SDK but perhaps not in dropbox.js 0.10.2.

What browser and what version of the Dropbox library? And what's wrong with the image that's saved? (I assume by "corrupted" you mean that it won't open in whatever tool you're using... any more hints? Is the file size reasonable?) I just did a very similar test (toDataURL, atob, and Uint8Array) with Chrome on OS X and dropbox.com/static/api/dropbox-datastores-1.0-latest.js, and it seems to work.
Comment: I used canvas.toDataURL('png') and store it in a variable: data and then i coded client.writeFile('image.png',data, callback)...the file is ceated but it is corrupted i.e no contents to display. What could be the error?
Comment: A data URL is not the same as the data you want to store in a PNG. Specifically, it's a base64-encoded version of the data with a prefixed URL scheme and MIME type. There's code right in the question above that shows how to convert a data URL to the actual underlying data and save it to Dropbox.

Save captured png as arraybuffer


How to access library version details in JavaScript

Question: I have a theme with library file looks like this:
global:
  version: 1.0.0
  js:
    js/global.js: {}

global.js has some functionality specific to version 1.0.0.
Is there anyway to get this version number? Is it available in JS?
Answer: Library definitions can be accessed via the library.discovery service (LibraryDiscovery).
$libraryDiscovery = \Drupal::get('library.discovery');
// Where mytheme is the name of your theme.
$definition = $libraryDiscovery->getLibraryByName('mytheme/global');

Then you would need to pull out $definition['version'] into a JavaScript settings or do something with it in your theme.
Comment: Thanks.I will give this option a try. Thought there might be some kinda out-of-box option available as version could be essential.
Comment: This is out of the box. It is within core API.


Fingering on sheet music?

Question: I'm trying to teach an autistic child the trumpet. He does not read music. Is there any sheet music out there with the fingerings already on it?
Answer: I am not sure how advance your student is but the picture below shows the fingerings. It also shows a diagram of a trumpet.

Fingering on sheet music?


Assignment from Incompatible Pointer Types

Question: Here's the following problem, Im getting Asisgnment from incompatible pointer types in the next code:
TO resume this to you the line 43 goes as follows:
  aux->sig=nodo;

Line 60 :
 aux2=aux2->sig;

Basically im getting every error in "aux2"
Whats is causing this? And if you could explain this to me, Im a student and Im basically new to programming.
proyecto2mod.c: In function 'agrega_nombre':
proyecto2mod.c:43: warning: assignment from incompatible pointer type
proyecto2mod.c:60: warning: assignment from incompatible pointer type
proyecto2mod.c: In function 'busca_cliente':
proyecto2mod.c:105: warning: assignment from incompatible pointer type
proyecto2mod.c: In function 'ordena':
proyecto2mod.c:118: warning: assignment from incompatible pointer type
proyecto2mod.c:119: error: request for member 'nombre' in something not a structure or  union
proyecto2mod.c:119: error: request for member 'nombre' in something not a structure or union
proyecto2mod.c:120: error: request for member 'direccion' in something not a structure or union
proyecto2mod.c:120: error: request for member 'direccion' in something not a structure or union
proyecto2mod.c:121: error: request for member 'num_cliente' in something not a structure or union
proyecto2mod.c:122: error: request for member 'ant' in something not a structure or union

...
And So on.
Heres the Codes:
MAIN CODE
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include "clientes.h"
#include "ventas.h"
extern void agrega_nombre(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2);
extern void busca_cliente(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2,    ApLista2 inicioventas, ApLista2 auxventas, ApLista2 nodoventas, ApLista2 aux2ventas);
extern int ordena(ApLista1 inicio, ApLista1 aux,ApLista1 nodo,ApLista1 *aux2);
int main(void)
{
int menu=0;

 //LISTA1 *aux2,*nodo;
 ApLista1 inicio, aux, nodo, aux2;
 ApLista2 inicioventas, auxventas,nodoventas,aux2ventas;

inicio=NULL;
nodo=malloc(sizeof(LISTA1));
aux=malloc(sizeof(LISTA1));
inicioventas=NULL;
nodoventas=malloc(sizeof(LISTA2));
auxventas=malloc(sizeof(LISTA2));

system("clear");
while(menu!='6')
 {
    //funcion void carga_datos();
  printf("TIENDA DEPARTAMENTAL\n\n\n");
  printf("1. Agregar a un Cliente.\n2. Agregar una venta.\n3. Buscar Cliente. \n4.     Borrar Cliente. \n5. Borrar una venta. \n6. Salir.");
  printf("\n\nElige una opcion: ");
  scanf("%d", &menu);
  switch(menu)
{
case 1:
  system("clear");
  printf("opcion1\n");

  agrega_nombre(inicio, aux,nodo, aux2);
  menu=0;
  break;
case 2:
  system("clear");
  printf("opcion2\n");

  ///lo mismo que agrega_cliente pero utilizando la lista de ventas.
  menu=0;
  break;
case 3:
  system("clear");
  printf("opcion3\n");
  busca_cliente(inicio,aux,nodo,aux2,inicioventas, auxventas, nodoventas,  aux2ventas);
  menu=0;
  break;
case 4:
  system("clear");
  printf("opcion4\n");
  //borra_cliente(inicio,aux,nodo,aux2,inicioventas, auxventas, nodoventas,   aux2ventas);
  menu=0;
  break;//
case 5:
  system("clear");
  printf("opcion5\n");
  //Lo Mismo que borra cliente pero en la lista de ventas solamente.
  menu=0;
  break;
case 6:
  system("clear");
  printf("Adios!\n");
  exit(1);
  menu=0;
  break;
 }
   }
}

Functions that go in main:
 void agrega_nombre(ApLista1 *inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2)
{

 FILE *clientes;
 int pops=0, sanders=0;
 char aux_char[80];

  system("clear");
 clientes=fopen("clientes.txt", "a+");
 //fseek(clientes, 0L, SEEK_END);

if(nodo==NULL)
 {
   printf("No hay memoria\n");
   exit(1);
 }
  printf("NOMBRE:");
  scanf("%s", nodo->nombre);
  printf("DIRECCION:");
  scanf("%s",nodo->direccion);
  printf("NUMERO DE CLIENTE:");
  scanf("%d", &nodo->num_cliente);

  if(inicio==NULL)
{
  (*inicio)=nodo;
  (*inicio)->sig=NULL;
  (*inicio)->ant=NULL;
  aux=(*inicio);
}
  else
{
  aux->sig=nodo;
  nodo->ant=aux;
  aux=nodo;
  nodo->sig=NULL;
}

  pops++;

  aux2=(*inicio);

  while(aux2!=NULL)
{
  fprintf(clientes, "%s\n", aux2->nombre);
  fprintf(clientes, "%s\n", aux2->direccion);
  fprintf(clientes, "%d\n", aux2->num_cliente);
  puts(aux2->nombre);
  puts(aux2->direccion);
  aux2=aux2->sig;
}

  aux2=aux;
  do
{
  puts(aux2->nombre);
  aux2=aux2->ant;
}
  while(aux2!=NULL);
  fclose(clientes);
 }

 //Funcion Busqueda
 void busca_cliente(ApLista1 inicio, ApLista1 aux,ApLista1 nodo, ApLista1 aux2, ApLista2   inicioventas, ApLista2 auxventas, ApLista2 nodoventas, ApLista2 aux2ventas)
   {
char nombrebusqueda[80];
int numclienteprueba;
inicio=NULL;

printf("Dame el nombre del cliente a buscar\n");
scanf("%s",nombrebusqueda);
aux2=aux;
while(aux2!=NULL)
  {
    printf("Entramos al While Aux2");
    if((strcmp(nombrebusqueda,aux2->nombre))==0)
      {
    printf("Encontramos BAM");
    puts(aux2->nombre);
    ////////Buscamos la venta
    aux2ventas=auxventas;
    while(aux2ventas!=NULL)
      {
        numclienteprueba=aux2ventas->num_clienteventas;
        if(numclienteprueba==aux2ventas->num_clienteventas)
          {
        printf("Wow");
        ///Aqui ensenamos las ventas que ha tenido el cliente y la i   informacion de la estructura.
          }
        aux2ventas=aux2ventas->sigvent;
      }
    ////////////
      }
    aux2=aux2->sig;
  }
   }

 //Funcion Ordena

     int ordena(ApLista1 inicio, ApLista1 aux,ApLista1 nodo,ApLista1 *aux2)
 {
char pruebaman[80],probaman[80];//nombres
char pruebadireccion[150],probadireccion[150];//direccion
int pruebanum_cliente,probanum_cliente;//numero de cliente
aux2=aux;
strcpy(pruebaman,aux2->nombre);
strcpy(pruebadireccion,aux2->direccion);
pruebanum_cliente=aux2->num_cliente;
aux2=aux2->ant;

do
  {

    strcpy(probaman,aux2->nombre);

    if(pruebaman[0]<probaman[0])
{
  strcpy(pruebaman,aux2->nombre);
  strcpy(pruebadireccion,aux2->direccion);
  pruebanum_cliente=aux2->num_cliente;
  aux2=aux2->sig;
  strcpy(aux2->nombre,probaman);
  strcpy(aux2->direccion,probadireccion);
  probanum_cliente=aux2->num_cliente;
}
  strcpy(pruebaman,aux2->nombre);
  strcpy(pruebadireccion,aux2->direccion);
  pruebanum_cliente=aux2->num_cliente;

  aux2=aux2->ant;

  printf("Ciclo\n\n");

}
while(aux2!=NULL);
aux2=aux;
strcpy(pruebaman,aux2->nombre);
aux2=aux2->ant;
strcpy(probaman,aux2->nombre);
if(pruebaman[0]<probaman[0])
 ordena(inicio,aux,nodo,aux2);
 }

Structures:
  #include<stdio.h>
  typedef struct clientes{
  char nombre[80];
   char direccion[150];
  int num_cliente;
  struct cliente*sig;
  struct clientes *ant;
  struct ventas *vent;
  }LISTA1;
  typedef struct clientes *ApLista1;

Second Structure:
  #include<stdio.h>
  typedef struct ventas{
  int num_clienteventas;
  char nombre_producto[150];
  int precio;
  int unidades;
  char fecha[11];
  struct ventas *sigvent;
  struct ventas *antvent;
  }LISTA2;
  typedef struct ventas *ApLista2;

Answer: In int ordena(), you define aux2 as an ApLista1*, which is basically a struct clientes**. You then try to assign it into aux, which is defined as ApLista1 aux, namely a struct clientes* - note the missing star.
aux2 being a pointer to a pointer to a struct, it's clear why calls like aux2->nombre are not compiling. The solution is to either define aux2 as ApLista1, or dereference it when needed.
Oh, and as a side note - IMO, hiding *s behind typedefs is not a good practice. It doesn't help you type less, and it makes the code less readable - and as in this case, more error prone.
Comment: +1 on including `*` in the typedef.  Doing so often results in confusing code, unless the type clearly indicates it's a pointer like Microsoft's `lp` prefix, or using `ptr` or `handle` somewhere in the name.


Finding point coordinates that have been reflected.

Question: I'm just working on some summer problems so that I can be more prepared when I go into my class in the fall. I found a website full of problems of the content we will be learning but it doesn't have the answers. I need a little guidance on how to do this problem. Here is the problem:
Consider the lines $L1$ and $L2$ with equations:
$L_1 : r = (11, 8, 2) + s(4, 3, -1)$
$L_2 : r = (1, 1,-7) + t(2, 1, 11)$
The lines intersect at point $P$.
The coordinates of $P$ are (3, 2, 4).
The lines are also perpendicular.
The point $Q(7,5,3)$ lies on $L_1$. The point $R$ is the reflection of $Q$ in the line $L_2$.
Question: Find the coordinates of $R$.
So, trying to work this out, Q is on $L_1$. $L_1 : r = (11, 8, 2) + s(4, 3, -1)$. And $R$ is on $L_2$. $L_2 : r = (1, 1,-7) + t(2, 1, 11)$
I'm guessing I figure out how $Q$ is correlated to $L_1$. And then relate that to $R$. But how would that work?
Comment: If two points A,B(end points of position vectors) are mirror images of each other with regard to a line, the the line bisect the line segment AB.
Comment: This question was asked before by you https://math.stackexchange.com/questions/2877680/finding-components-of-lines-intersecting-at-a-point. You have deletec part c) and asked a new question. I asked for clarification of part c) without answer. Even you include a comment about a part c).
Comment: @mfl I gave as much information as I was given and I am trying to work out the question to get to the final answer.
Comment: I think it's reasonable to split out part (c) of the old question into a separate question, especially since you accepted an answer for parts (a) and (b) of the old question. I would also have included a link back to the previous question, since this is a follow-up question. We have that link now via a comment, so it's a moot point now; I merely suggest that in the next situation like this, you include a link in the question.
Answer: The reflection of a point $Q$ in a line $L$ can be described as follows:
Drop a perpendicular from $Q$ to the line $L.$
Suppose we say $M$ is the name of the point at the foot of the perpendicular.
That is, $M$ is on $L$ and the segment $QM$ is perpendicular to $L.$
The reflection of $Q$ in the line $L$ is the point (call it $Q'$) that is the same distance from $M$ as $Q$ is, but in the exact opposite direction.
That way, the segment $QQ'$ is perpendicular to $L,$ and $L$ cuts through $QQ'$ at $M,$ exactly midway between $Q$ and $Q'$.
One way to look at this is, if you have $M,$ you can take the vector from $M$ to $Q,$
and then reverse the direction of the vector to get a vector from $M$ to $Q'.$
Now, knowing $M$ and the vector from $M$ to $Q',$ you find $Q'.$
Now review the information in the question statement.
You have the coordinates of $Q.$ You also have the coordinates of $M$ (not called by that name, but if you look at the facts already given in the question, you should find the coordinates there).
So you can find the vector $MQ,$ reverse it, and find $Q'.$
Alternatively, instead of using vectors, use the fact that $M$ is the midpoint of $Q$ and $Q'.$ Therefore
$$ x_M = \frac{x_Q + x_{Q'}}{2}, \quad
y_M = \frac{y_Q + y_{Q'}}{2}, \quad \text{and}\quad
z_M = \frac{z_Q + z_{Q'}}{2}.$$
Put the coordinates of $Q$ and $M$ in these equations, then solve for $x_{Q'},$ $y_{Q'},$
and $z_{Q'}.$
Comment: Right, $z$ is dealt with similarly to $x$ and $y.$ I have added that detail to the answer.
Comment: Yes, I get the same.
Comment: Point $Q$ has $x, y, and z$. So wouldn't $R$ also have those 3 parts?
Comment: I got (-1,-1, 5) as my answer. Does this seem correct?


Configuring Sudo using SSSD

Question: Trying to Login to Linux systems using windows AD account. Configured successfully using SSSD.
Used LDAP as Identity & Access Providers and Kerberos as the Authentication provider.
I have done all this without joining the linux systems to the domain.
Now I'm trying to configure LDAP as sudo provider. But its not successfull. I'm not able to elevate the sudo permissions to the ad users. I've even tried using sudoers file, there i'm able to elevate permissions to the specific user, but not to the ad group.
Here's the SSSD config w.r.t sudo configuration
**sudo_provider = ldap

ldap_sudo_search_base = ou=groups,dc=ad,dc=example,dc=com
ldap_sudorule_object_class = sudoRole
ldap_sudorule_object_class = top
ldap_sudorule_command = ALL
ldap_sudorule_host = ALL
ldap_sudorule_user = %domain_group
ldap_sudorule_runasuser = ALL
ldap_sudorule_runas = ALL
ldap_sudorule_runasgroup = ALL
ldap_sudorule_option = !authenticate**

I've tried enabling logging at debug level 7, its mentioning that unable to load local rules.
Regards, Uday.
Answer: I think you misunderstood the purpose of the config file switches - they serve to map the LDAP values of the queried objects. The directives default to the values specified by the auxiliary object class (schema is in /usr/share/doc/sudo-*/schema.ActiveDirectory on CentOS).
You are supposed to import this schema in your AD, create objects representing sudo roles using this object class and have SSSD query them.
Find an exhaustive example below:
Here's a sample SSSD config querying users, groups, and sudo roles from LDAP. Replace the <> enclosed parts with values fitting your environment:
[domain/default]
id_provider = ldap
auth_provider = ldap
access_provider = ldap
chpass_provider = ldap
sudo_provider = ldap
ldap_uri = ldaps://<ldap-server-address>:636
ldap_tls_cacert = /etc/pki/tls/certs/ca-bundle.crt
ldap_tls_reqcert = demand
ldap_default_bind_dn = <proxy-user-dn>
ldap_default_authtok_type = obfuscated_password
ldap_default_authtok = <obfuscated password>
ldap_search_base = <search base for users>
ldap_schema = rfc2307bis
ldap_group_search_base = <search base for groups>
ldap_sudo_search_base = <search base for sudo rules>
cache_credentials = false
enumerate = false

[sssd]
services = nss, pam, ssh, sudo
config_file_version = 2
domains = default

[nss]

[pam]

[sudo]

[autofs]

[ssh]

In your LDAP directory, create an object below ldap_sudo_search_base looking something like this:
objectClass: Top
objectClass: sudoRole
sudoRunAsUser: ALL
sudoHost: yourhost.example.com
sudoUser: %wheel
sudoCommand: ALL
description: Allows members of wheel to become root
cn: wheel_group_sudo_role

This allows all members of the group wheel to become root on the host yourhost.example.com.
Running sudo -U testuser -ll as root on the target host should yield:
LDAP Role: wheel_group_sudo_role
    RunAsUsers: ALL
    RunAsGroups: ALL
    Commands:
        ALL

edit:
As you've figured, as SSSD provides users to a Linux box, you may treat them as regular Linux users and thus create a local sudo rule:
/etc/sudoers.d/00-local-admin-rule
%ad-admin-group ALL: (ALL) ALL

This allows members of the ad-admin-group to call sudo to become root.
When talking about *_search_base, the DN of some form of LDAP container object is meant, e.g. an organizational unit like ou=users,o=corg,dc=example,dc=org or whatever hierarchy your directory features. Create the objects of the desired types below the specified container.
Comment: Thanks for the clarification. As per your suggestion, i have to edit or create the AD objects which corresponds to sudo rule. Is there no way, without editing AD, i could attain the sudo on the AD users by setting something locally in linux servers( apart from adding it into the sudoers). Also, Whatever the sudo search base you had mentioned is CN name of the obj for which i have to elevate the permission right ?
Comment: I've updated my answer.

Configuring Sudo using SSSD


get com port on which usb modem is connected in java

Question: how to get the com ports on which usb edge modem is connected in java program. neeed quick help.
kindly tell me which library to use to get com.. except javax.comm. I tried it but failed.
I didnt find way to install it properly its showing me error conitneously. :(
package commtest;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Formatter;
import org.smslib.helper.CommPortIdentifier;
import org.smslib.helper.SerialPort;

public class CommTest
{
    private static final String _NO_DEVICE_FOUND = "  no device found";

    private final static Formatter _formatter = new Formatter(System.out);

    static CommPortIdentifier portId;

    static Enumeration<CommPortIdentifier> portList;

    static int bauds[] = { 9600, 14400, 19200, 28800, 33600, 38400, 56000, 57600, 115200 };

    /**
     * Wrapper around {@link CommPortIdentifier#getPortIdentifiers()} to be
     * avoid unchecked warnings.
     */
    private static Enumeration<CommPortIdentifier> getCleanPortIdentifiers()
    {
        return CommPortIdentifier.getPortIdentifiers();
    }

    public static void main(String[] args)
    {
        System.out.println("\nSearching for devices...");
        portList = getCleanPortIdentifiers();
        while (portList.hasMoreElements())
        {
            portId = portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
            {
                _formatter.format("%nFound port: %-5s%n", portId.getName());
                for (int i = 0; i < bauds.length; i++)
                {
                    SerialPort serialPort = null;
                    _formatter.format("       Trying at %6d...", bauds[i]);
                    try
                    {
                        InputStream inStream;
                        OutputStream outStream;
                        int c;
                        String response;
                        serialPort = portId.open("SMSLibCommTester", 1971);
                        serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_RTSCTS_IN);
                        serialPort.setSerialPortParams(bauds[i], SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
                        inStream = serialPort.getInputStream();
                        outStream = serialPort.getOutputStream();
                        serialPort.enableReceiveTimeout(1000);
                        c = inStream.read();
                        while (c != -1)
                            c = inStream.read();
                        outStream.write('A');
                        outStream.write('T');
                        outStream.write('\r');
                        Thread.sleep(1000);
                        response = "";
                        StringBuilder sb = new StringBuilder();
                        c = inStream.read();
                        while (c != -1)
                        {
                            sb.append((char) c);
                            c = inStream.read();
                        }
                        response = sb.toString();
                        if (response.indexOf("OK") >= 0)
                        {
                            try
                            {
                                System.out.print("  Getting Info...");
                                outStream.write('A');
                                outStream.write('T');
                                outStream.write('+');
                                outStream.write('C');
                                outStream.write('G');
                                outStream.write('M');
                                outStream.write('M');
                                outStream.write('\r');
                                response = "";
                                c = inStream.read();
                                while (c != -1)
                                {
                                    response += (char) c;
                                    c = inStream.read();
                                }
                                System.out.println(" Found: " + response.replaceAll("\\s+OK\\s+", "").replaceAll("\n", "").replaceAll("\r", ""));
                            }
                            catch (Exception e)
                            {
                                System.out.println(_NO_DEVICE_FOUND);
                            }
                        }
                        else
                        {
                            System.out.println(_NO_DEVICE_FOUND);
                        }
                    }
                    catch (Exception e)
                    {
                        System.out.print(_NO_DEVICE_FOUND);
                        Throwable cause = e;
                        while (cause.getCause() != null)
                        {
                            cause = cause.getCause();
                        }
                        System.out.println(" (" + cause.getMessage() + ")");
                    }
                    finally
                    {
                        if (serialPort != null)
                        {
                            serialPort.close();
                        }
                    }
                }
            }
        }
        System.out.println("\nTest complete.");
    }
}

Answer: This is not related with USB, AT Commands and so on... if you would've read carefully the error message, you would've had the answer:
win32com.dll: Can't load IA 32-bit .dll on a AMD 64-bit.

The topic was alredy address here: Javax.comm API on 64-bit Windows
Answer: This method is working for me.This code will automatically detect port with which GSM modem connected and send SMS.
public class ModamSMS {

public void sendMessage(String num, String massage) throws Exception {

    SerialModemGateway gateway = new SerialModemGateway("", "COM5", 9600, "", "");
    gateway.setInbound(true);
    gateway.setOutbound(true);
    OutboundNotification outboundNotification = new OutboundNotification();
    InboundNotification inboundNotification = new InboundNotification();
    Service service = Service.getInstance();
    service.setOutboundMessageNotification(outboundNotification);
    service.setInboundMessageNotification(inboundNotification);
    service.addGateway(gateway);
    service.startService();

    OutboundMessage msg = new OutboundMessage(num, massage);
    service.sendMessage(msg);
}

public ArrayList sendBulkMessage(ArrayList<String> numbers, String massage)
        throws IOException, InterruptedException, SMSLibException {

    ArrayList list = new ArrayList();
    String connectedport = getConnectedport(numbers.get(0), massage);
    System.out.println(connectedport + " port in bulsksmssend method");
    if (connectedport != null) {
        BasicConfigurator.configure();

        SerialModemGateway gateway = new SerialModemGateway("", connectedport, 9600, "", "");

        try {

            // gateway.setInbound(true);
            gateway.setOutbound(true);

            OutboundNotification outboundNotification = new OutboundNotification();

            // InboundNotification inboundNotification = new
            // InboundNotification();
            Service service = Service.getInstance();
            service.setOutboundMessageNotification(outboundNotification);
            // service.setInboundMessageNotification(inboundNotification);
            service.addGateway(gateway);
            service.startService();

            for (int i = 1; i < numbers.size(); i++) {

                String num = (String) numbers.get(i);
                OutboundMessage msg = new OutboundMessage(num, i + " " + massage);
                System.out.println(i + " " + massage);
                Thread.sleep(1000);

                service.sendMessage(msg);
                list.add(num + " Sms send succes");

            }
            Service.getInstance().stopService();

        } catch (SMSLibException | IOException | InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));

            writfile(sw.toString());
        }

        Service.getInstance().removeGateway(gateway);
    } else {
        JOptionPane.showMessageDialog(null, "Please make ! \n Modam is correctly inseted\nYou hava SMS package\n ");
    }
    return list;
}

public class InboundNotification implements IInboundMessageNotification {
    // @Override
    // Get triggered when a SMS is received
    public void process(AGateway gateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
        System.out.println(inboundMessage);
        try {
            gateway.deleteMessage(inboundMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public class OutboundNotification implements IOutboundMessageNotification {

    // Get triggered when a SMS is sent
    public void process(AGateway gateway, OutboundMessage outboundMessage) {
        System.out.println(outboundMessage);
    }
}

public String getConnectedport(String num, String msge)
        throws TimeoutException, GatewayException, SMSLibException, IOException, InterruptedException {

    ArrayList<String> allports = new ArrayList<>();

    Enumeration ports = CommPortIdentifier.getPortIdentifiers();
    while (ports.hasMoreElements()) {
        CommPortIdentifier port = (CommPortIdentifier) ports.nextElement();
        String type;
        switch (port.getPortType()) {
        case CommPortIdentifier.PORT_PARALLEL:
            type = "Parallel";
            break;
        case CommPortIdentifier.PORT_SERIAL:
            allports.add(port.getName());
            type = "Serial";
            break;
        default: /// Shouldn't happen
            type = "Unknown";
            break;
        }
        System.out.println(port.getName() + ": " + type);
        allports.add(port.getName());
    }
    String connectedport = null;
    for (int a = 0; a < allports.size(); a++) {
        connectedport = getport(allports.get(a), num, msge);
        if (connectedport != null) {
            a = allports.size();
            System.out.println(connectedport + " port in for loop");

        }

    }

    return connectedport;

}

private String getport(String port, String num, String msge)
        throws TimeoutException, GatewayException, SMSLibException, IOException, InterruptedException {
    String returnport = null;

    SerialModemGateway gateway = new SerialModemGateway("", port, 9600, "", "");
    gateway.setInbound(true);
    gateway.setOutbound(true);
    OutboundNotification outboundNotification = new OutboundNotification();
    InboundNotification inboundNotification = new InboundNotification();
    Service service = Service.getInstance();
    service.setOutboundMessageNotification(outboundNotification);
    service.setInboundMessageNotification(inboundNotification);
    try {
        service.addGateway(gateway);
        service.startService();

        OutboundMessage msg = new OutboundMessage(num, msge);
        service.sendMessage(msg);
        returnport = port;
        System.out.println(returnport + " port in port finding method");

    } catch (GatewayException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SMSLibException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    Service.getInstance().stopService();
    Service.getInstance().removeGateway(gateway);
    return returnport;

}

public static void main(String args[]) {

    BasicConfigurator.configure();

    ModamSMS app = new ModamSMS();
    ArrayList<String> numbers = new ArrayList<>();
    numbers.add("+923075142199");
    numbers.add("+923075142199");

    try {
        // app.sendMessage("+923075142199","plz Allah it shoud work");
        app.sendBulkMessage(numbers,
                "hy this is me Abdulrehman javed .Who are you and how are you.This is testing sms so do not worry");

    } catch (Exception e) {
        e.printStackTrace();
        e.printStackTrace();
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));

        writfile(sw.toString());
    }
}

public static void writfile(String content) {

    BufferedWriter bw = null;
    FileWriter fw = null;

    try {

        fw = new FileWriter("Error.txt");
        bw = new BufferedWriter(fw);
        bw.write(content);

        System.out.println("Done");

    } catch (IOException e) {

        e.printStackTrace();

    } finally {

        try {

            if (bw != null)
                bw.close();

            if (fw != null)
                fw.close();

        } catch (IOException ex) {

            ex.printStackTrace();

        }

    }
}
}


Quebrar linha depois de uma IMG com CSS

Question: Estou fazendo a versão mobile de um site, porem eu não consigo forçar uma quebra de linha depois de uma imagem que fica dentro de um modal.
Esse é o trecho que importa no modal:

        <button type="button" class="close" data-dismiss="modal">×
        </button>

Açougue

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur justo tellus, rutrum lobortis nibh placerat ut. Etiam magna lorem, imperdiet sit amet felis nec, dictum eleifend felis. Donec vel molestie dui. Maecenas nulla eros, porta id nulla eu, imperdiet ullamcorper purus. Pellentesque commodo, massa vitae bibendum eleifend, libero turpis dapibus elit, eu auctor nisl dui rhoncus nibh. Nam vulputate sem nisi, non eleifend justo fringilla sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur tincidunt lectus nisl, quis semper sem fermentum sed. Nulla a mi vehicula, sagittis nulla ac, venenatis erat. Maecenas tristique nibh eget dignissim malesuada.

Basicamente eu preciso que após a tag  o css quebre a linha, mas não posso utilizar o
 porque no desktop a linha não vai quebrar, somente quando a media query for @media(max-width: 1080px)
Answer: Fiz usando flex e mudando a ordem de row para column, assim fica um item por coluna. Depois usei o align-self para centralizar a imagem.
Veja o resultado. (vc precisa testar em uma tela menor que o Snippet aqui do StackOverflow ok)

    <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />

            <button type="button" class="close" data-dismiss="modal">×
            </button>

Açougue

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur justo tellus, rutrum lobortis nibh placerat ut. Etiam magna lorem, imperdiet sit amet felis nec, dictum eleifend felis. Donec vel molestie dui. Maecenas nulla eros, porta id nulla eu, imperdiet ullamcorper purus. Pellentesque commodo, massa vitae bibendum eleifend, libero turpis dapibus elit, eu auctor nisl dui rhoncus nibh. Nam vulputate sem nisi, non eleifend justo fringilla sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur tincidunt lectus nisl, quis semper sem fermentum sed. Nulla a mi vehicula, sagittis nulla ac, venenatis erat. Maecenas tristique nibh eget dignissim malesuada.

OBS: Se vc estiver como o Bootstrap 4 é ainda melhor pq ele já tem o Grid em Flex e todas as classes do Flex nativas.
Comment: @OtavioSouzaRocha valeu jovem. Só mais uma coisa, vc também pode testar fazer essa quebra usando o Grid do próprio Bootstrap, Ai vc tem que separar a imagem e o P, cada um em uma div, tipo `` para a imagem e `` para o texto. Boa sorte com o projeto. Tmj
Comment: Eu geralmente utilizo o Bootstrap, mas nesse caso eu o site vai sem consideravelmente diferente no mobile, ai decidi fazer com media query
Comment: Simples e funcional! Muito obrigado
Answer: Ele não quebra pois tem o align="left". Minha sugestão é: remove align="left", adiciona a imagem dentro de uma div com uma classe com float:left e quando for menor que "tal", apenas remove o float left:

@media screen and (min-width:765px){
  .float-left-lg{
    float:left;
  }
}
<link rel="stylesheet" src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

        <button type="button" class="close" data-dismiss="modal">×
        </button>

Açougue

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur justo tellus, rutrum lobortis nibh placerat ut. Etiam magna lorem, imperdiet sit amet felis nec, dictum eleifend felis. Donec vel molestie dui. Maecenas nulla eros, porta id nulla eu, imperdiet ullamcorper purus. Pellentesque commodo, massa vitae bibendum eleifend, libero turpis dapibus elit, eu auctor nisl dui rhoncus nibh. Nam vulputate sem nisi, non eleifend justo fringilla sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur tincidunt lectus nisl, quis semper sem fermentum sed. Nulla a mi vehicula, sagittis nulla ac, venenatis erat. Maecenas tristique nibh eget dignissim malesuada.

Answer: Uma alternativa é colocar o texto dentro de outra tag
:

            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer efficitur justo tellus, rutrum lobortis nibh placerat ut. Etiam magna lorem, imperdiet sit amet felis nec, dictum eleifend felis. Donec vel molestie dui. Maecenas nulla eros, porta id nulla eu, imperdiet ullamcorper purus. Pellentesque commodo, massa vitae bibendum eleifend, libero turpis dapibus elit, eu auctor nisl dui rhoncus nibh. Nam vulputate sem nisi, non eleifend justo fringilla sed. Interdum et malesuada fames ac ante ipsum primis in faucibus. Curabitur tincidunt lectus nisl, quis semper sem fermentum sed. Nulla a mi vehicula, sagittis nulla ac, venenatis erat. Maecenas tristique nibh eget dignissim malesuada.

Comment: Sim, porém nesse caso, quando o site for aberto pelo desktop a imagem vai estar com a linha quebrada também, preciso que quebre só no mobile

Quebrar linha depois de uma IMG com CSS


Erro a não conseguir aceder à coleção de imagens C#

Question: Estou utilizado o Magick.NET para poder escolher a compresão JPEG para os meus ficheiros TIFF. Assim, guardo cada um com essa compressão numa coleção de imagens. Por fim quero juntar todos os TIFF da coleção num só ficheiro.
Mas quando faço "images.Combine();" recebo o erro:

Também tentei fazer a mesma ação sem a linha de código mencionada acima mas recebo o mesmo erro. No entanto, não vejo onde o objeto foi Disposed pois está tudo dentro de um bloco using.
Código:
public void JoinTiffJPEG(string[] imageFiles, string outFile)
{
    using (MagickImageCollection images = new MagickImageCollection())
    {
        try
        {
            MagickReadSettings settings = new MagickReadSettings();
            settings.Compression = CompressionMethod.JPEG;
            for (int i = 0; i <= (imageFiles.Length - 1); i++)
            {
                using (var image = new MagickImage(File.ReadAllBytes(imageFiles[i]), settings))
                {
                    image.Settings.Compression = CompressionMethod.JPEG;
                    // Add the image
                    images.Add(image);
                }
            }
            images.Combine();
            Stream output = new FileStream(outFile, FileMode.Create);
            images.Write(output, MagickFormat.Tif);

            //images.Dispose();
            return;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
        }
    }
}

Comment: Deita fora o `using`, na linha `using (var image = ...)`.
Comment: @MarceloShinitiUchimura  Era isso, obrigada! No entanto, o ficheiro afinal só tem a primeira página e não todas... Consegue me ajuda nisso ou devo postar uma nova questão?
Comment: Nova questão, por favor.
Comment: Certo. Obrigada.
Comment: @MarceloShinitiUchimura Coloque isso na resposta, por favor. E Sofia, quando houver a resposta, marque como resolvido por favor. :) Isso pode ajudar os próximos a terem a mesma dúvida.
Comment: Certo, eu fá-lo-ei.
Answer: Com ajuda do comentário de @MarceloShinitiUchimura , a resposta é retirar o bloco using na linha
using (var image = new MagickImage(File.ReadAllBytes(imageFiles[i]), settings))

Sendo assim, o código final ficará:
    public void JoinTiffJPEG(string[] imageFiles, string outFile)
    {
        using (MagickImageCollection images = new MagickImageCollection())
        {

            try
            {
                MagickReadSettings settings = new MagickReadSettings();
                settings.Compression = CompressionMethod.JPEG;

                for (int i = 0; i <= (imageFiles.Length - 1); i++)
                {
                    MagickImage image = new MagickImage(File.ReadAllBytes(imageFiles[i]), settings);
                    image.Settings.Compression = CompressionMethod.JPEG;
                    // Add the image
                    images.Add(image);

                }
                images.Combine();
                Stream output = new FileStream(outFile, FileMode.Create);
                images.Write(output, MagickFormat.Tif);

                //images.Dispose();
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
            }
        }
    }