Entity reference - which side of the relationship is it best to put the field in?

Question: I an adding entity references to an existing site with a lot of data, and I want to make sure I get it right first time. My question is - is it best practice to put an entity reference in the container content type, or in the contained content type? In other words, is it best practice for the entity reference to be in the album content type, or the track content type (also applies to team/team member, book/chapter or whatever)?
In an ideal world these relationships would be in both content types, but that doesn't seem to be built-in and the relevant module (Corresponding Entity Reference) seems to be in Alpha.  So what is best-practice?
Answer: Where you definitely have a 'container' vs 'contained' relationship, I would say the best way to go is to put the reference field on the contained field.  If you put the reference field on the container then every time you make a new item to be contained you have to edit the container as well.
Frequently I find that 'containers' end up with many more child objects than were originally intended, putting the reference field on the child object helps keep it manageable.
Also, when you are rendering the content or using it in views, you can use the reverse relationship.  So if you have books with many pages and each page references the book it belongs to, you could have a view that is based on books but also contains information about the pages.  And yes, that is using CER, so far for me it works quite well.
Comment: Yes, putting it on the contained rather than the container I think is probably the way to go. The only problem is when you have a new container which has lots of pre-existing contained items to contain, all the contained items need to be updated. But either way you're going to hit that kind of problem I guess.
Comment: Use Views Bulk Operations to edit the contained items in bulk.


Can median be expressed using linear combinations and max?

Question: The median of two numbers is their mean, $(a+b)/2$, the median of three numbers is their sum less their maximum and minimum, i.e.
$$Median(a,b,c) =  a + b + c - \max(a,\max(b,c)) - \min(a,\min(b,c)) $$
$$ = a + b + c - \max(a,\max(b,c)) + \max(-a,\max(-b,-c)) $$
and the median of 4 numbers proceeds similarly (since it's the mean of the center two,
$$Median(a,b,c,d) =  \frac{a + b + c + d - \max(\max(a,b),\max(c,d)) - \min(\min(a,b),\min(c,d))}{2} $$
$$ = \frac{a + b + c + d - \max(\max(a,b),\max(c,d)) + \max(\max(-a,-b),\max(-c,-d))}{2} $$
But is there any similar expression for 5 elements? If there are, bonus points for proof of minimality of your expression (by whatever metric you care), or generalizations to larger sets of elements, of course!
(Background, if anyone is curious: This question was prompted by some machine learning code, where max/min are standard reduction functions, but medians are not; and when considering an ensemble of 5 models -- a pretty common number -- this would be useful. But this question seemed mathematically interesting on its own.)
Comment: The question is how to "take them away", which I don't see a straightforward way to accomplish with an expression as in the above. While you're right that for a computer algorithm this would be a fine solution, it's not a solution that would run very well (at least, not without being very clever) on a GPU.
Comment: For 5 elements why couldn't you take the Max and Min elements away and then calculate the median of the remaining 3? This idea could easily be generalized to any number of elements.
Comment: @AlexMeiburg I am no expert on GPU programming, but this seems like an ideal use case for a small sorting network approach, where you run a fixed number of $(x, y) \leftarrow (min(x, y), max(x, y))$ steps on various pairs of array indices which is guaranteed to sort the array, then take the middle element.
Comment: @Joppy that's also a good solution. It seems that for $n=5$ this can be done with a sorting network with 6 comparisons, or equivalently 11 applications of max/min (2 for each comparison, but only needing one result from the latter). This is probably close to optimal for a GPU! I am separately curious about expressions though, as the sorting network would lead to a very large expression tree (due to expression reuse).
Answer: Here's a silly way of extracting the $k$th-largest element from $n$ numbers using only max and min. Let $[n]$ denote the set $\{1, \ldots, n\}$, then the $k$-th largest element of $\{a_1, \ldots, a_n\}$ is
$$ \min_{\substack{I \subseteq [n] \\ |I| = n - k + 1}} \max_{i \in I} a_i$$
In the example with $5$ elements, to find the largest element, the formula gives
$$\min(\max(a, b, c, d, e)) = \max(a, b, c, d, e)$$
while to find the second largest element, the formula gives
$$\min(\max(b, c, d, e), \max(a, c, d, e), \max(a, b, d, e), \max(a, b, c, e), \max(a, b, c, d))$$
The reason this works is that one of the five must be the maximum, and will appear in all but one $\max(\cdots)$ expression: the $\min$ operation finds this expression. You can then plug this into similar expressions that you had above.
I make no claims as to the minimality of this formula, and it would be pretty outrageous to use this for large sets. But for $n=5$ it might hit the spot.
Comment: This is a good answer! A couple things though. When selecting an element below the median, it might be easier to flip max/min: choosing the second smallest element would be a min-of-10-maxes-of-2 as you wrote it, but by symmetry of course could be max-of-5-mins-of-4. For $n=5$, I can see selecting the median directly with your formula -- a min of 10 maxes, with each max of 3 things. But I can also use the form above to to select the least, second-to-least, greatest, and second-greatest elements, and subtract that from the sum. That's of course more complicated here, but not by much..! Thanks!
Comment: @Joppy This is the *most* elegant way I have ever seen to represent $k$-th largest number of a set. But I am not sure how you came with this formulation (even though you call it "silly"), could you provide more information about this?
Answer: The median-of-5 can be calculated from two chained median-of-3s:
med(a, b, c, d, e) = med(med(max(a, e), min(b, d), c), min(a, e), max(b, d))
"Proof": Try to get a large result with any two large inputs and three small inputs. Not possible.


Azure Web App, how to convert image/x-emf to png? [ C# ]

Question: How can I convert emf (image/x-emf) files to png without using "MetaFile class" which seems to not work in Azure Web Apps. It works on self hosted sites.
I don't seem to find any alternative.
Source Code:
https://github.com/KeesCBakker/KeesTalksTech-Utility-Pack/tree/master/KeesTalksTech-Utility-Pack/KeesTalksTech.Utilities/Graphics
Here is someone who seems to have similar error:
Calling Chart.SaveImage() in Azure WebApp results in GDI+ Exception for ChartImageFormat.EMF only
Answer: Azure Web App runs in sandbox, some GDI+ components do not have permission. Please refer to this article for more information about Azure Web App sandbox. For this scenario, please try to use cloud service or azure VM.
Comment: Sadly I already know that. So is there a alternative way to convert emf to png?


Clarification on the definition of a closed communicating class

Question: If I have a transition matrix defined as $p_{ij}=1$ for $j=i+1$ and $p_{ij}=0$ otherwise, where the state-space is countably infinite, what would this be? It doesn't look like a communicating class because no 2 states communicate but then the "communication" relation partitions the state-space, hence the entire state-space must be one big communicating class here? Then the whole thing is closed? But that shouldn't be right...
Answer: Correct me if you use the wrong definition of the communication, I base on the book 'Markov Chains and Stochastic Stability'. There $i,j$ communicate iff either $i=j$ or $p^m_{ij}>0$ and $p^n_{ji}>0$ for some $0<m,n<\infty$. In your case any state communicates only with itseld, so you have countably many communicating classes. I.e. in terms of relations, $[i] = i$ for all $i=1,2,3,...$
To be precise, in your question the statement

no 2 states communicate

is incorrect since any state communicate with itself by definition.
Comment: Can we say that an irreducible Markov chain is a closed class?


jQuery how to keep the style value when going back

Question: I've got an issue with the keeping style value when coming back to a page from another.
I've got a code in jQuery that is showing my menu.
$( "#burger" ).click(function() {
    if ($("#burger").hasClass("closed")) {
      $( "#menu" ).animate({
        marginLeft: "-400px"
      }, 600, function() {
        $("#burger").removeClass("closed");
        $("#burger").addClass("open");
      });
    } else {
        $( "#menu" ).animate({
        marginLeft: 0
      }, 600, function() {
        $("#burger").removeClass("open");
        $("#burger").addClass("closed");
      });
    }
});

And now when i enter other link: for example "gallery.html" and then go back to the "index.html" the menu is no longer there.
How can i keep the margin-left:-400px; in the memory, so when i go back the menu will still be there?
Also i don't wanna to menu will be open everytime i go back, cause in some cases it will be closed and it should remain - so in that case the value should be remembered as "margin-left:0px;"
Thanks for answers!
Comment: You need to store the information if the menu should be open or closed somewhere, a cookie perhaps ?
Answer: Here's a fiddle to round out this answer JS Fiddle
You can add an item with HTML5 Storage API using sessionStorage or localStorage.
sessionStorage.setItem("leftset", "yes");
localStorage.setItem("leftset", "yes");

the difference is that localStorage will save it indefinitely on the users computer. Session storage will remove it when the browser window is closed.
You can use
sessionStorage.getItem("leftset");
localStorage.getItem("leftset");

To pull from the storage object on page load or dom ready and then execute whether or not "leftset"(in this example, but you can set it up as whatever) has a value.
if you would like to remove an item from storage you can use the following:
sessionStorage.removeItem("leftset");
localStorage.removeItem("leftset");

learn more at w3Schools or check out the demo HTML5 Storage Demo
Answer: What's going on is that JQuery or any JS based language works on the client, so when you reload the page or your app cause a Postback every change the JQuery had done will be erased. As posted by zfrisch the best method is to "save" that the user has already clicked on the item and base it's position on whether or not has been changed.
//if you are interested on keeping it this way until browser is erased manually
localStorage.itemClicked = true;
//if the configuration is going to be reset on everytime the user opens his browser
sessionStorage.itemClicked = true;

and in the .ready function you change its position
$(function(){
    if(localStorage.itemClicked){
        $('#burger').addClass("open");
        $('#burger').css({margin-left:"-400px"});
    }
});

and your click event should look like this
$( "#burger" ).click(function() {
    if ($("#burger").hasClass("closed")) {

      $( "#menu" ).animate({
        marginLeft: "-400px"
      }, 600, function() {
        $("#burger").removeClass("closed");
        $("#burger").addClass("open");

        //save that was clicked
        localStorage.itemClicked = true;
      });
    } else {

        $( "#menu" ).animate({
        marginLeft: 0
      }, 600, function() {
        $("#burger").removeClass("open");
        $("#burger").addClass("closed");

        //remove the key so it is not wasting memory
        localStorage.removeItem("itemClicked");
      });
    }
});

Hope it helped
Comment: I've tryed this solution... but in this case menu is always open when i'm coming back or refreshing the window, no matter if i opened it in the first place
Comment: that means it is evaluating localStorage.itemClicked as true every time could you please post the result of console.log(localStorage.itemClicked) or a print of the Storage section of the inspector so I can provide a little help
Comment: i've make it working by putting localStorage.itemClicked = true; after animation completed - don't know how, but it works, please fix that in your post, so i can mark is as a good answer.
Comment: changed it now, it should work either way I'm looking why right now


Organize node file attachments into groups

Question: I have a content type with multiple file attachments to download. Is there a module to give authors the ability to divide all the attachments into groups, writing a title for every group, just like they can reorder and name them in edit mode?
The final node display should be something like this:
<code>Group Title 1
. File n.1
Group Title 2
. File n.2
. File n.3
</code>
I've been searching for a while and found FileTree, but it's too complicated. Files shouldn't be managed physically, just displayed in groups.
Thanx in advance.
Answer: You can use Field group module. Create multi-value field group, with single-value Group title sub-field and multi-value File field inside. That's pretty much all.
Comment: I'm trying, but surely I do something wrong. I installed Field group and Field group multiple, created a Multiple fields container with a single text field and a multiple file field in it, but it doesn't work. All the files aren't shown on node page. Is there a documentation or a tutorial to read and understand where I go wrong?


Javascript não puxa os resultados

Question: Boa tarde pessoal,
estou tentando fazer com que calcule novamente utilizando outros tipos de campo, como checkbox e de lista com algumas condições, em alguns tutoriais tentei entender como funciona, porem não consegui fazer gerar o resultado, se poderem dar uma olhada e orientada agradeço.

<form name="mensalidade" method="post" action="">
    Tributação

        <select id="tributacao" name="tributacao" class="form-control input">
            <option value="0">Escolha</option>
            <option value="49.90">MEI</option>
            <option value="219">Simples Nacional</option>
            <option value="319">Lucro Presumido</option>
            <option value="2650">Lucro Real</option>
        </select>

    Quantidade de Funcionarios

    <input type="text" name="qt_func" id="qt_func">

    Faturamento mes

    <input type="text" name="fat_mes" id="fat_mes">

    Selecione os Tipos

    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="30">Serviços
    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="150">Industrial
    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="80">Comercial

    <input type="text" name="res" id="res">

    <input type="button" value="Calcular" onClick="calcular(document.mensalidade.fat_mes.value)"/>
</form>

Comment: Todos os `else` estão errados, deveria ser `else if`. O último poderia ser encurtado para `} else {` (omitindo a condição de comparação, se isso for justificável)
Comment: Não entendi, o que deveria acontecer? Explica melhor por favor
Comment: ele deveria multiplicar a qt_func por 20 e somar o restante dos campos e passar pela variavel, somar o valor que esta dentro, porem ele não esta mostrando no campo res...
Comment: Tá bem mal explicado, com o perdão da palavra, suponho que o "res" que você se refere é o elemento ``. Do jeito que você escreve as pessoas tem que se esforçar mais pra entender o que você escreveu e o que quer do que entender aonde o seu código falha, ou seja as pessoas perdem muito tempo tentando lhe enteder ao invés de gastarem o tempo tentando encontrar o problema do seu código. Por favor entenda como uma critica construtiva.
Comment: @LuisHenrique bem notado, eu ainda nem havia olhado o código por causa que a pergunta em si estava dificil de entender, boa sacada +1
Comment: @LuisHenrique na verdade o ultimo `else` esta errado também. Todos estão errados.
Comment: De fato a pergunta está bem confusa, não entendi ela também, mas só de bater o olho no código deu pra perceber o erro (não que seja apenas isto). Corrigi a observação do último `else`.
Comment: pessoal desculpa, mais sou novo em javascript e to tentando explicar a maneira que vejo, sei que é algo simples, mais ja estou me matando a uns 4 dias, caçando e tentando fazer o codigo.
Comment: @ViniciusNakamura ninguem tá reclamando do teu código ou teu entendimento de js, estou criticando a maneira que você escreveu mesmo, mas agora esta um pouco mais claro a pergunta depois de conversar, no entanto é um erro de digitação (off-topic), vou até responder, espero que ajude.
Comment: so estou me desculpando, relaxa ;) , pois estou tentando aprender javascript e ta sendo uma luta. rs
Answer: você até começou com o pé direito, isolou o método para calcular em uma função.
Porém aconselho não declarar os eventos inline no proprio HTML, utilize de preferencia no HtmlElement.addEventListener(name, callback).
por fim, apesar de não haver problemas no uso do HTMLCollection para acessar os elementos DOM da pagina no seu exemplo, você pode encontrar algum problema de compatibilidade no futuro, então aconselho utilizar o document.getElementById.

//estou assumindo que você definiu estas variaveis em outro ponto do codigo.
var prestacao = 0;
var industrial = 0;
var comercial = 0;

var mensalidade = {};
mensalidade.form = document.querySelector("[name='mensalidade']");
mensalidade.tributacao = mensalidade.form.querySelector("[name='tributacao']");
mensalidade.qt_func = mensalidade.form.querySelector("[name='qt_func']");
mensalidade.fat_mes = mensalidade.form.querySelector("[name='fat_mes']");
mensalidade.tipo_emp = mensalidade.form.querySelectorAll("[name='tipo_emp']");
mensalidade.calcular = mensalidade.form.querySelector("[name='calcular']");
mensalidade.res = mensalidade.form.querySelector("[name='res']");
Object.defineProperty(mensalidade, "tipo_emp_sum", {
  get: function () {
    return [].reduce.call(mensalidade.tipo_emp, function (valor, tipo_emp, indice) {
      if (tipo_emp.checked)
        valor += parseInt(tipo_emp.value);
      return valor;
    }, 0);
  }
});

function calcular(event){
  var tributacao = parseFloat(mensalidade.tributacao.value) || 0;
  var qt_func = parseInt(mensalidade.qt_func.value) || 0;
  var fat_mes = parseInt(mensalidade.fat_mes.value) || 0;
  var tipo_emp = mensalidade.tipo_emp_sum;
  var qt_func2 = qt_func * 20;

  var soma = qt_func2 + tributacao + tipo_emp + parseInt(prestacao) + parseInt(industrial) + parseInt(comercial) ;
  var res = soma;
  switch(true) {
    case (fat_mes <= 25000): break;
    case (fat_mes <= 30000): res += 115; break;
    case (fat_mes <= 40000): res += 150; break;
    case (fat_mes <= 50000): res += 190; break;
    case (fat_mes <= 60000): res += 230; break;
    case (fat_mes <= 70000): res += 270; break;
    case (fat_mes <= 80000): res += 310; break;
    case (fat_mes <= 90000): res += 350; break;
    case (fat_mes <= 100000): res += 390; break;
    case (fat_mes <= 110000): res += 430; break;
    case (fat_mes <= 120000): res += 470; break;
    default: res = (res * 0.40) / 100; break;
  }
  mensalidade.res.value = res;
}

//adicionando os eventos aos inputs.
mensalidade.calcular.addEventListener("click", calcular);
mensalidade.tributacao.addEventListener("change", calcular);
mensalidade.qt_func.addEventListener("input", calcular);
mensalidade.fat_mes.addEventListener("input", calcular);
[].forEach.call(mensalidade.tipo_emp, function (tipo_emp, indice) {
  tipo_emp.addEventListener("change", calcular);
})
<form name="mensalidade" method="post" action="">
    Tributação

        <select id="tributacao" name="tributacao" class="form-control input">
            <option value="0">Escolha</option>
            <option value="49.90">MEI</option>
            <option value="219">Simples Nacional</option>
            <option value="319">Lucro Presumido</option>
            <option value="2650">Lucro Real</option>
        </select>

    Quantidade de Funcionarios

    <input type="text" name="qt_func" id="qt_func">

    Faturamento mes

    <input type="text" name="fat_mes" id="fat_mes">

    Selecione os Tipos

    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="30">Serviços
    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="150">Industrial
    <input type="checkbox" name="tipo_emp" id="tipo_emp" value="80">Comercial

    <input type="text" name="res" id="res">

    <input type="button" value="Calcular" name="calcular" "/>
</form>
Comment: legal, ainda estou tentando entender o codigo que vc fez, so tenho que alterar agora o selecione os tipos para checkbox, pois ele podera escolher mais de 1 serviço no caso. seria o mesmo esquema do radio?
Comment: @ViniciusNakamura, não vai quebrar o código, mas não acho que vai gerar o resultado esperado, acredito que você terá que fazer uma pequena adaptação, como substituir o filter (pega o primeiro selecionado) por um reduce (somar todos os valores selecionados). porém não estou vendo você utilizando o valor de `tipo_emp` no seu script.
Comment: No caso o tipo_emp vai dizer ql o segmento da empresa, ai necessitaria somar eles tbms, caso fossem selecionados, fiz esta alteração aqui, porem não adicionou a diferença no valor final.
Comment: @ViniciusNakamura, realizei uma alteração para somar todos os valores de `tipo_emp` e acresentar os mesmos à `soma`.
Comment: Realizei alguns teste e percebi que na linha default: res = (res * 0.40) / 100; break; não teria que ser fat_mes, pois notei que ele faz um valor totalemente diferente, que no caso seria 1000, aparece 0.12 adicionando o valor de 250000
Comment: Eu também não entendi esta linha, estava completamente fora de sintonia com o resto do codigo, em todo caso apenas transcrevi a sua logica.
Comment: eu fiz uns testes, e alterei uma linha que irei mudar no codigo, que funcionou legal, ou melhor adicionei a soma que ficou assim "default: res = (fat_mes * 0.40) / 100 + soma ; break;"
Answer: Okay, vamos ver se eu consigo te ajudar. Os if's estão errados, eles têm que ficar assim como neste exemplo abaixo e inicie a variável res antes de entrar nos if's para não precisar ficar iniciando ela a toda hora.
var res =0;
if (fat_mes <= 25000){
     res = parseInt(0) + parseFloat(soma);
} else if (fat_mes > 25000 && fat_mes <= 30000){
     res = parseFloat(soma) + 115;
} else if (fat_mes > 30000 && fat_mes <= 40000){
     res = parseFloat(soma) + 150;
} else if (fat_mes > 40000 && fat_mes <= 50000){
     res = parseFloat(soma) + 190;
} else if (fat_mes > 50000 && fat_mes <= 60000){
     res = parseFloat(soma) + 230;
} else if (fat_mes > 60000 && fat_mes <= 70000){
     res = parseFloat(soma) + 270;
} else if (fat_mes > 70000 && fat_mes <= 80000){
     res = parseFloat(soma) + 310;
} else if (fat_mes > 80000 && fat_mes <= 90000){
     res = parseFloat(soma) + 350;
} else if (fat_mes > 90000 && fat_mes <= 100000){
     res = parseFloat(soma) + 390;
} else if (fat_mes > 100000 && fat_mes <= 110000){
     res = parseFloat(soma) + 430;
} else if (fat_mes > 110000 && fat_mes <= 120000){
     res = parseFloat(soma) + 470;
} else if (fat_mes > 120000){
     res = (parseFloat(soma) * 0.40) / 100
}

fazendo assim, o erro vai sumir, mas ainda tem a variável prestacao que não está definida em lugar algum.
Comment: no final do arquivo defini um alert com a variavel res e mais acima uma outra com a variavel soma, em ambos não aparecem o valor.

Javascript não puxa os resultados


Getting current Date by CultureInfo

Question: I'd like to get localized date in my Xamarin Forms app. I have tried two ways that work just fine in ASP.NET MVC, but I wonder why neither of them works in Xamarin.
var currentDate DateTime.Now.ToString("yyyy/mm/dd", new CultureInfo("fa-IR"))

And by using culture info's calendar:
var month = new CultureInfo("fa-IR").Calendar.GetMonth(DateTime.Now);

Both of these methods gave me the current date in en-US.
Apparently, PersianCalendar is supposed to be there. I can't understand what I'm missing?
I even tried NodaTime by, SystemClock.Instance.Now.InZone(DateTimeZoneProviders.Tzdb["Asia/Tehran"]).Date.ToString() and the date is still in default culture!
UPDATE
Finally, Persian Calendar Plus did the job! But it would be very useful if someone could get the bottom of it!
Comment: If you run into limitations using DateTime, it may be helpful to know that there are other date/time libraries out there for .Net. Grandmaster Skeet's NodaTime is one but there are others.
Comment: @bubbleking, I'm using it [this way](http://stackoverflow.com/a/27853841/3967440) and I still get `en-US` date by `SystemClock.Instance.Now.InZone(DateTimeZoneProviders.Tzdb["Asia/Tehran"]).Date.ToString()`.
Answer: .Net framework doesn't support Persian calendar for the culture. This culture doesn't accept the calendar; therefore display of DateTime in this culture is impossible.
You need to create a custom helper or some extension as mentioned here.
Using the above extension you can set like this,
// create an instance of culture
CultureInfo info = new CultureInfo("fa-Ir");
//set Persian calendar to it without get exception
info.DateTimeFormat.Calendar = new PersianCalendar();

Comment: `.Net` does support `fa-IR` culture and I'm using it in `MVC` apps, am I missing something?
Comment: @Akbari did you try as above?
Comment: it seems that `.Net core` doesn't have [Persian Calendar](https://msdn.microsoft.com/en-us/library/system.globalization.persiancalendar(v=vs.110).aspx) anymore!
Comment: @Akbari Thats what i have mentioned
Comment: That's awful, but thanks for your help. Would you please note in your answer that this is related to `.Net Core` to make it more complete,

Getting current Date by CultureInfo


Django InlineModelAdmin: Show partially an inline model and link to the complete model

Question: I defined several models: Journals, volumes, volume_scanInfo etc.
A journal can have more volumes and a volume can have more scanInfo.
What I want to do is:

in the admin page of journals I want to have the list of the volumes inline (done)
connect each volume of the previous list to its admin page where I can show the form to edit the volume and the list of its "scan info" inline.

so I want to have something like:
Journal #1 admin page
[name]
[publisher]
[url]
.....
list of volumes inline
    [volume 10] [..(other fields)..]   Full record
    [volume 20] [..(other fields)..]   Full record

Then
Volume #20 admin page
[volume number]
[..(other fields)...]
......
list of the scan info inline
    [scan info 33] [..(other fields)..]   Full record
    [scan info 44] [..(other fields)..]   Full record

What I tried to do is defining a model method that create the code and trying to use it inside the class that defines "volume inline" in the admin, but it doesn't work.
In other words
the model "Volume" has inside something like:
def selflink(self):
    return 'Full record' % self.vid
selflink.allow_tags = True

and
class VolumeInline(admin.TabularInline):
    fields = ['volumenumber', 'selflink']
    model = Volume
    extra = 1

But this gives the following error:
Exception Value: 'VolumeInline.fields' refers to field 'selflink' that is missing from the form.

Any idea?
Thanks,
Giovanni
Comment: Very good question. This kind of functionality should be built in.
Comment: iI is built in. Its answered here (show_change_link) since django 1.8: http://stackoverflow.com/a/28170958/493272
Comment: I know, but the question is 6 years old :-)
I will update the answer so it is clear that there is this new functionality.
Answer: UPDATE:
Since Django 1.8, this is built in.
See this answer and the official documentation.
OLD ANSWER:
At the end I found a simple solution.
I create a new template called linked.html that is a copy of tabular.html and I added this code to create the link.
{% if inline_admin_form.original.pk %}

              Full record

{% endif %}

then I created a new model LinkedInline inheriting InlineModelAdmin
#override of the InlineModelAdmin to support the link in the tabular inline
class LinkedInline(admin.options.InlineModelAdmin):
    template = "admin/linked.html"
    admin_model_path = None

    def __init__(self, *args):
        super(LinkedInline, self).__init__(*args)
        if self.admin_model_path is None:
            self.admin_model_path = self.model.__name__.lower()

Then when I define a new inline, I have only to use my LinkedInline instead of the normal InlineModelAdmin.
I hope it can be useful for other people.
Giovanni
Comment: No, if you are inside the complete volume admin page, after saving you stay there.

But since the volume has as foreign key the journal, I extended the foreign key form to print a link back to the journal, so you can go back with just one click.
Comment: When you save a child model page does it go back to the parent one ?
Comment: If you are editing a complete volume model linked to a journal, when you save, does it automatically return to the journal edition page ?
Comment: How does the LinkedInline find the template file?  Did you put the template file into an existing template directory, instead of in a 'module' with the LinkedInline.py file?
Comment: Ignore my last comment... turns out the real issue is that apparently my remote object doesn't have a primary key (which is BS, because I defined one...)
Answer: Update:
As of Django 1.8, this is now built-in.
Answer for Django <= 1.7:
Keep your code in models.py with conditional case:
def selflink(self):
    if self.id:
        return "Edit" % str(self.id)
    else:
        return "Not present"

selflink.allow_tags = True

In admin.py, add selflink as readonly field:
class VolumeInline(admin.TabularInline):
    readonly_fields = ['selflink',]
    model = Volume

That worked for me.
Comment: In case you are using `fields` option, you need to put it after `readonly_fields`
Comment: @uszywieloryba: untrue in Django-1.4.x. Anyway, `selflink` must be in `fields` or `fieldsets`.
Comment: I like much better to code in models.py than in temaplates! thanks
Answer: Here's a reusable mixin based on some of the other answers. This is handy because it works with both Tabular and Stacked inlines, and doesn't cruft up your model or admin code.
# put this somewhere like admin_helpers.py
from django.core.urlresolvers import reverse

class InlineEditLinkMixin(object):
    readonly_fields = ['edit_details']
    edit_label = "Edit"
    def edit_details(self, obj):
        if obj.id:
            opts = self.model._meta
            return "%s" % (reverse(
                'admin:%s_%s_change' % (opts.app_label, opts.object_name.lower()),
                args=[obj.id]
            ), self.edit_label)
        else:
            return "(save to edit details)"
    edit_details.allow_tags = True

# admin.py

class VolumeInline(InlineEditLinkMixin, admin.TabularInline):
    fields = ['foo', 'bar', 'edit_details']

class JournalAdmin(admin.ModelAdmin):
    inlines = [VolumeInline]

class ScanInfoInline(InlineEditLinkMixin, admin.StackedInline):
    fields = ['foo', 'bar', 'edit_details']

class JournalAdmin(admin.ModelAdmin):
    inlines = [ScanInfoInline]

Comment: very helpful and neat. I need to add this on top of your code `from django.core.urlresolvers import reverse`
Comment: I wonder if this could be made to work with many2many fieldsets automatically, where you have `model = ModelA.modelbs.through`?
It would need to detect this (maybe via `_meta.auto_created`?) and create the edit link accordingly.
Answer: In Django 1.8+ this is now much easier. Just add show_change_link = True to your TabularInline or StackedInline subclass, like this:
class VolumeInline(admin.TabularInline):
    fields = ['volumenumber']
    model = Volume
    extra = 1
    show_change_link = True

And Django will automatically add a link to the full change form for each inline item, if the model has its own registered ModelAdmin.
Answer: Did you try the Reversing admin URL system ?
That could give something like that (in the journal page):

{% for volume in original.volume_set.all %}

    Edit {{ volume }}

{% endfor %}

Answer: After some fiddling, I was able to make this work in an InlineAdmin and a TabularInline, using reverse(). At least with TabularInline, the field you want to link must be listed in 'readonly_fields'
# create a read-only inline with the first field linked
from django.core import urlresolvers
class YOUR_MODEL_Inline(LinkedTabularInline):
    max_num = 0 # remove the "Add another ..." link
    model = YOUR_MODEL_NAME
    fk_name = "YOUR_FOREIGN_KEY_NAME"
    fields = [ 'link_name', ] # , 'field1', 'field2', 'etc' ]
    readonly_fields = fields
    can_delete = False
    def link_name(self, obj):
        if obj.pk:
            url = urlresolvers.reverse('admin:%s_%s_change'
                % (obj._meta.app_label, obj._meta.module_name), args=[obj.id])
            # obj.MODEL_FIELD can be a text string or whatever you want
            return '{1}'.format(url, obj.MODEL_FIELD)
    link_name.allow_tags = True
    link_name.short_description = "MODEL_FIELD"

If you want to link to the change list instead of the change view, you can modify the reverse() call. changelist does not require an object id.
    url = urlresolvers.reverse('admin:%s_%s_changelist'
        % (obj._meta.app_label, obj._meta.module_name))
    return '{1}'.format(url, obj.name)

And if you want to link to a subset of objects, you can add parameters to the URL:
    return '{2}'.format(url, obj.id, obj.name)


Swap out blocks based on domain name extension

Question: We have a European site that is the same exact site for three different domain names. So www.mysite.eu, www.mysite.ie and www.mysite.ch all go to the same site. However, we would like to make very small subtle changes based on which domain extension they come from. Really, I just need to swap out a couple blocks based on the domain.
I know there is the Domain Access module, which we actually use on another site, but I really didn't want to have the huge overhead and configuration and headache of everything that comes with the Domain Access module, just to swap out a couple blocks and that's it. The rest of the site in it's entirety will be exactly the same for all three domains.
I have put a hack in place using JavaScript right now, but it's not the most elegant solution. I was wondering if there is something else I could try besides Domain Access.
Answer: If you're still using D7 (there's no D8 port at the time of writing this), you could use Context Domain in conjunction with the Context module, or port the D7 version to D8. There's also option of creating a hook_block_access invocation to control display on a view operation.


Which version of notating dynamics for woodwinds is more clear?

Question: As in title - which is better (if any)? Specifically for flutes and oboes.
Comment: It's quite hard for a woodwind instrument to change dynamic abruptly (while remaining in-tune) without re-articulating, are your sure you don't want a hairpin between the tied notes?
Comment: You say "flutes and woodwinds" - if you have several players you could get the effect you're after by having everyone playing at the start of the bar, and then have most of them stop after the first minim, leaving one or two players.
Comment: Dynamic notation is completely instrument-independent.   And, @ElementsinSpace that's simply not true for even mid-level skilled players.
Comment: The tie might be confusing.  Could you just mark it *legato*?
Comment: @Pam - not quite the same - sf is suddenly loud, whereas f is just loud, loder than the previous note/s, but not sf. And sf/p is usually a short sf, longer p, from experience.
Comment: @aparente001 From the version in line 1, the OP _wants_ the notes tied. So now, the question is how to notate that without giving the impression of merely wanting it legato....
Comment: @JamesMartin - I guess they could write something like "fully connected."  Or maybe there's a way of notating for woodwinds *not articulalted*?
Comment: @CarlWitthoft - agreed on piano, guitar and some others, but flute and oboe?
Comment: Just checking, you don't mean a [sforzando piano](https://dictionary.onmusic.org/terms/3112-sforzando_piano), do you? (often played in concert bands by the band en masse, and often followed immediately by a crescendo on the same note).
Comment: Are you expecting a diminuendo, or a rearticulation after two beats? That would give you your answer. I would argue the first notation with a clear diminuendo notation would be the most unambiguous, for the former. For the latter, the lower notation is more clear, but definitely not unambiguous.
Comment: @Tim yes agreed, it's unlikely to be quite the same thing, and yes the sfp usually has the shortest possible loud part with an almost immediate change to piano. But since it's a change in dynamic over a single (note?) pitch, I thought I'd ask anyway.
Answer: No.2 if you want the 'p' to start exactly on the third beat.
Comment: Agree. Version 1 is just plain confusing.
Comment: For any instrument. I would take v 1 to mean literally "change from F to P anywhere within the measure that seems good to you." Or rather would come to that conclusion after scratching my head a long time about whether it was a *fp* with strange spacing, or whether a note was missing, or it was a mistake.
Comment: Yep,  Version 1 is (or should be) illegal.  If you wanted a decrescendo then you'd  annotate  " F [hairpin] P"  .     But in any case it doesn't hurt to write , in version 2,  "F subito P" so that people aren't tempted to perform a decrescendo.
Comment: @VictorEijkhout version 2 is equally confusing.  Is it a tie or a slur?  The performer is likely to conclude that it can't be a tie, because if no articulation is intended it should be a whole note.
Comment: @phoog - wasn't aware that a slur could ever be used between two of the same notes, particularly in the same bar. Therefore it must be a tie, making the dynamics appropriate,
Comment: @Tim Yes absolutely, people write slurs over passages involving repeated notes, to indicate a legato approach or general phrasing. You can even see someone above who has misunderstood v2 in exactly that way, assuming that the OP didn't want a tie and commenting "Could you just mark it legato?". (Not to disagree with you about v2 being better than v1 - but it still could easily be misunderstood.)
Comment: @Tim slurs with notes of the same pitch are common in string writing.  They also occur occasionally in wind parts.  The traditional rules for tying notes call for a whole note/semibreve here.  It's ambiguous, therefore, whether the two half notes/minims were chosen to indicate a subtle rearticulation or the timing of the dynamic shift.  Unless that is clear from the context, I would recommend some additional notation to make it clear.
Answer: Both versions are problematic.  The first version, as you noticed, is imprecise as to the timing of the piano mark.  The second version could be interpreted as asking for a rearticulation on the second note.
That problem aside, following forte with piano is ambiguous by itself as it says nothing about the rate of reduction of the volume.  Some interpreters will infer a decrescendo, while others will change suddenly from loud to soft.
It's better, therefore, to be explicit: use a decrescendo wedge or write sub p, where sub is short for subito, which means "suddenly."  (Even this, however, leaves room for interpretation; the underlying problem is that dynamic markings are inherently imprecise, which is one reason why we use the term "interpretation."  One part of learning to be a composer is learning to cede control of your creations to others.)
Traditionally, the timing of dynamic variation within a single long note is given by precise alignment.  If you find that insufficient, you could invent some new notation.  In option 1, you could place little half notes next to the f and p, or in option two you could add the text "tied" or "without articulation" above the second half note.
Another option might be what copy editors call "recasting": rethink your orchestration.  Revoice the chord in the second half of the measure, having each instrument drop an octave or perhaps just to the next lower pitch, or, as Brian THOMAS suggested in a comment, have some of the instruments drop out in the middle of the measure.
Comment: @Tim and a "hairpin" (which I called a "decrescendo wedge" in the answer) is one way of notating a decrescendo explicitly -- and a more precise way than simply using the word, of course. I'm coming at this with memories of long debates in leaderless rehearsals about the specific meaning of notation. Surely you've had similar experiences? You know, 10 people in the room, 9 of whom are convinced that it's definitely _subito,_ the other thinking that there's an implicit decrescendo, and 4 of the 9 thinking that even though it's obviously intended to be _subito,_ composers' dynamics are optional.
Comment: The *rate* of reduction isn't in question - it comes as soon as the second note is due - looking at the 'p' placement. I feel it's pretty categoric, with little wriggle room for readers. The 'sub' idea is a ood one, re-inforcing what's already being told what to do. A decrescendo it is not - tha would be easily written with a hairpin.
Comment: Are you certain that the composer does not desire a gradual change from _f_ to _p_?  Even if you are, and even if you are correct, not everyone reading this notation would share that certainty.  I mentioned the possibility of an explicit decrescendo in case that was in fact the composer's intention.
Comment: if a gradual change was required, surely a hairpin would suffice - f at the start, p at the end, if absolutely neccessary. It's really up to the composer to be as accurate and clear (or not) as to what he expects readers to play.
Comment: Too many times! That's why it's either me or some other sucker who's the leader - and his word goes, like/lump it. But there's more than a subtle difference between no. 2 and a decrescendo, so there shouldn't even be a discussion - 1st note f, 2nd p., which isn't anywhere near a decrescendo.


Can an Excel VSTO 2010 add-in be run in Office 2007?

Question: We've created an VSTO 2010 project, containing a ribbon bar for Excel, which runs nicely, however it now turns out some of our customers will be running Office 2007.
We've attempted to install it on 2007, with no luck (the ribbon is listed as a running add-in, however it doesn't appear among the ribbon tabs in Excel). I've tried following the steps mentioned in this SO question (replacing the 2010 references dlls with 2007 reference dlls), with no success.
Any suggestions that avoid having to create a new 2007 project (which as I understand would involve uninstalling Office 2010 on our development machines, and installing 2007 instead) would be very much appreciated.
Thanks!
Answer: Gah. It turned out to be a problem with the schema on the ribbon XML, which we spotted when we'd stripped the ribbon XML down to a single label, to see if it was any of the controls etc in the XML causing the incompatibility.
We were using (quite possibly copied from an example)
xmlns="http://schemas.microsoft.com/office/2009/07/customui"

but once we changed it to:
xmlns="http://schemas.microsoft.com/office/2006/01/customui"

the ribbon appeared immediately, which fitted in with the symptoms of the ribbon appearing as a running add-in, but not being visible in Excel itself. As mentioned previously (see this SO post for the details), it was necessary to use the v12 office and interop dlls.
Answer: You can install 2007 and 2010 side by side, and avoid any issues switching between the two by running the following in command line, or placing this in a batch file, either works:
reg add HKCUSoftwareMicrosoftOffice14.0WordOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice14.0ExcelOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice14.0PowerPointOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice14.0AccessOptions /f /v NoRepairNeeded /t REG_DWORD /d 1

reg add HKCUSoftwareMicrosoftOffice12.0WordOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice12.0ExcelOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice12.0PowerPointOptions /f /v NoReReg /t REG_DWORD /d 1
reg add HKCUSoftwareMicrosoftOffice12.0AccessOptions /f /v NoRepairNeeded /t REG_DWORD /d 1

As for your code, I find that the Excel Interop code for 12 and 14 is more or less interchangable. Are you using anything in Excel Interop 14 that isn't in 12?
Two projects may not seem ideal, but you may need to go this route. The upside is that you will be able to more or less copy and paste everything, espicially if you write everything for the 2007 project, and copy/paste across to the 2010 project, as opposed to the other way around.
Hope this helps
Comment: Thanks for taking the time to reply JMK, and for the confirmation that v12 and v14 should be compatible (There was only one cell.DisplayFormat() call that I had to change when switching back to 12 from 14). Once we fixed the ribbon XML schema, it was all fine, so i'll save trying to run office 2007 & 2010 alongside each other for a rainy day!
Comment: No problem, I know how painful Excel Interop can be at times, good luck!


Como remover altitude de ponto em um poligono?

Question: Abaixo segue uma representação de um Polygon em um KML. Veja:
<coordinates>
   -112.2550785337791,36.07954952145647,20
   -112.2549277039738,36.08117083492122,20
   -112.2552505069063,36.08260761307279,20
   -112.2564540158376,36.08395660588506,20
   -112.2580238976449,36.08511401044813,20
   -112.2595218489022,36.08584355239394,20
   -112.2608216347552,36.08612634548589,20
   -112.262073428656,36.08626019085147,20
   -112.2633204928495,36.08621519860091,20
   -112.2644963846444,36.08627897945274,20
   -112.2656969554589,36.08649599090644,20
</coordinates>

O ultimo valor da coordenada, ou seja o 20, representa a altitude, de acordo com a documentação, no qual não necessito. Então a princípio fiz um foreach desta forma abaixo:
foreach($names as $coordinate) {
    $coordinates[] = explode( ',20', $coordinate );
 }

Porém caso a altitude mude em alguma situação, essa regra no explode não funcionará. Qual seria uma forma viável de resolver esse problema e pegar somente as condenadas ignorando a altitude? Uma expressão regular pode resolver isso?
Answer: Se o ponto poligono é sempre no final da linha e o numero 20 pode ser variante, você pode usar regex antes de salvar no vetor:
<?php

$kml = '
   -112.2550785337791,36.07954952145647,20
   -112.2549277039738,36.08117083492122,20
   -112.2552505069063,36.08260761307279,20
   -112.2564540158376,36.08395660588506,20
   -112.2580238976449,36.08511401044813,20
   -112.2595218489022,36.08584355239394,20
   -112.2608216347552,36.08612634548589,20
   -112.262073428656,36.08626019085147,20
   -112.2633204928495,36.08621519860091,20
   -112.2644963846444,36.08627897945274,20
   -112.2656969554589,36.08649599090644,20';

$kml = preg_replace('#,\d+(\s|$)#', '$1', $kml);

echo $kml;

Explicando a regex:
 ,\d+(\s|$)
   ^  ^
   |  |------ Pega qualquer espaçamento, como quebra de linha
   |          e espaços, se não tiver então será o `$` que considera
   |          como o final da string
   |
   |---- Pega qualquer numero após a virgula


JSF Add Input to the Form

Question: I need to provide the user with a button (CommandButton) on the form which by clicking it can add TextInputs to the form. But it is not needed to be DHTML or AJAX
Comment: Related: http://stackoverflow.com/questions/2278353/how-to-dynamically-add-a-row-in-a-table-in-jsf
Answer: I was writing this code..hoping to solve your problem,
JSF page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<h:head>
    <title>Dynamic Input</title>
</h:head>
<h:body>
    <h:form>
 <h:dataTable id="textlist"  var="tbox" value="#{Bean.inputList}">
  <h:column>
      <h:inputText value="#{tbox}"/>
  </h:column>
</h:dataTable>
        <h:commandButton action="#{Bean.addInput}" value="Add Textbox"/>
    </h:form>
</h:body>

Bean:
import java.util.ArrayList;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean(name="Bean")
@ViewScoped
public class Bean implements java.io.Serializable {
private ArrayList inputList;
/** Creates a new instance of Bean */
public Bean() {
   inputList=new ArrayList();
    inputList.add(inputList.size());
}

public void addInput(){
     inputList.add(inputList.size());
}

public ArrayList getInputList() {
    return inputList;
}

public void setInputList(ArrayList inputList) {
    this.inputList = inputList;
}

}
This works...as a start. You can see if you can modify the code to suite your purposes. :)
I dont know if any other approach exist to add dynamic controls in JSF 2.0

JSF Add Input to the Form


Compiling python-mcrypt in win32?

Question: Um, I'm stumped and really stuck (+_+) here after googling many sites. I'm using mingw32-gcc.exe from Dev-c++ compiler and currently following instructions from this site.
Every time I try here's the result:
<code>C:\Python26>python c:\python26\python-mcrypt-1.1\setup.py install
running install
running build
running build_ext
error: don't know how to compile C/C++ code on platform 'nt' with 'mingw32-gcc.exe' compiler
</code>
I've edited the distuils.cfg file in my c:\python26\lib\distuils\distuils.cfg with this parameter
<code>[build]
compiler = mingw32-gcc.exe
</code>
Any ideas would be appreciated!
Comment: Is it in your PATH? Also try using Cygwin.
Comment: Yes, downloading Cygwin is suck, if I do that mostly times, my Pc will be  infected with virus (ex. bot or worms..) from the internet. I've tried using Cygwin and mingw32 with installer directly from online repository..
Comment: Cygwin is 200% virus free. Also, how did you install the two? Did you install them from the GUI package manager?
Comment: Has this been resolved? I'm hitting a similar road block.
Answer: You installed python outside of a compilation environment valids one include cygwin or mingw32 (wich is used by Dev-C++).
To use the command-line mode, you need to find the your compiler installation and find bat script which launch the shell with the proper parameters (This is needed for bith cygwin and mingw).
The alternative is to use Microsft solution for that problem.

Compiling python-mcrypt in win32?


AngularJS ng-hide not working with html binding to a div

Question: I'm trying to render html content from a controller , but the angular directive ng-hide doesn't work , I've tried the following code, does it have a problem with binding as html this way?

      var htmlContent = "

";

$scope.PageContent = $sce.trustAsHtml(htmlContent);

Answer: try this one,
 var htmlContent = "<Div class='vzone'  ng-.....

$scope.PageContent = $sce.trustAsHtml($compile(htmlContent));

don't forget to add $compile dependency in your controller.
$compile service will bind your dynamic directives with the controller
Comment: I tried it but gives the following exception  "Attempted to trust a non-string value in a content requiring a string: Context: htmlContent"


How to preset elements of dynamic mat-select as selected in Angular Material

Question: I'm building an edit form which contains multiple, multiple-choice select fields being built dynamically.
Updated code:
<mat-select multiple [(ngModel)]="dispoArray[clase.nombre]" name="clase.nombre" (selectionChange)="withoutDispositivo()"
    [ngModelOptions]="{standalone: true}">
    <mat-option *ngFor="let dispo of clase.dispositivos" [(value)]="dispo.id">
        {{ dispo.descripcion }}
    </mat-option>
</mat-select>

This is the function in charge of building these fields,
Updated code:
prepareClaseDispositivo() {
    this.dispositivos.forEach(dispo => {
        if (!this.labelDispositivos.includes(dispo.clase_dispositivo.nombre)) {
            this.labelDispositivos.push(dispo.clase_dispositivo.nombre);
        }
    });
    this.labelDispositivos.forEach(clase => {
        let arrayByClase = new Array();
        this.dispositivos.forEach(dispo => {
            if (clase === dispo.clase_dispositivo.nombre) {
                if (this.passedData.dispositivos) {
                    for (const d of this.passedData.dispositivos) {
                        if (d.descripcion == dispo.descripcion) {
                            this.dispoArrayValue.push({ id: d.id, descripcion: d.descripcion });
                        }
                    }
                }
                arrayByClase.push({ id: dispo.id, descripcion: dispo.descripcion });
            }
        });
        let json = { nombre: clase, dispositivos: arrayByClase };
        this.dispoByClase.push(json);
    });
}

My question is, how can I pre-set the options that are found in the array coming from the database as selected when the form is being built?
Comment: The app is pretty complex and is working alongside laravel and postgresql to fetch data needed for comparison. Unsure if I can share all of it on stackblitz.
Answer: To pre-populate a mat-select when using ngModel, set the model value to your selections. For example:
HTML
<mat-select multiple [(ngModel)]="selected">
  <mat-option value="option1">Option 1</mat-option>
  <mat-option value="option2">Option 2</mat-option>
  <mat-option value="option3">Option 3</mat-option>
</mat-select>

TS
selected = ['option1', 'option3'];

Comment: When you load your data, set the values in the model.
Comment: How can I add these model values dynamically as I find coincidences within the data in DB and the form fields being built?
Comment: My bad, I was thinking about it the wrong way. Still, I'm not able to make it work, could you maybe take a look at the updated code in the OP and see if I'm doing something wrong?
Comment: The values you push need to be the same as the `mat-option` `value` setting: `this.dispoArrayValue.push(d.id);` because ``.


How many arrangements of a bookshelf exist where certain books must be to the left/right of other books?

Question: The question at length is exactly this:

There are five distinct computer science books, three distinct
  mathematics books, and two distinct art books. In how many ways can
  these books be arranged on a shelf if one of the mathematics books is
  on the left of all computer science book, and another mathematics book
  is on the right of all the computer science books?

I have searched a ton online for a question that's even similar to this but have yet to find one. Most examples have set groupings of books to create an 'object' but none have the kind of modular specifications of this question.
I realize that there is ambiguity about if the math books are directly flush with the computer science books, or if they can be 'anywhere to the left/right' of the computer science books. I've attempted this question under the more challenging assumption and have gotten an answer as follows:
There are 4 different placements of two math books that will allow for the computer science books to be completely between the two.
1) 8 spaces between the two math books M__________M (1 way)
2) 7 spaces between the two math books: M_______M_ and _M_______M (2 ways)
3) 6 spaces: M______M__, _M______M_, __M______M (3 ways)
4) 5 spaces: M_____M___, _M_____M__, __M_____M_, ___M_____M. (4 ways)
Then I wanted to find the permutations of each of the ways above by the Rule of Product, and add them together by the Rule of Sum to get my final answer.
(1) 8 spaces: P(3, 2) * P(8, 8)
[Delimiting math books]  * [permutations in between]
(2) 7 spaces: P (3, 2) * P(3, 1) * P(7, 7) * 2
[Delimiting math books] * [Options for book outside of delimitation] * [Permutations in-between] * [number of ways to achieve 7 spaces]
(3) 6 spaces: P (3, 2) * P(3, 2) * P(6, 5) * 3
[Delimiting math books] * [options for 2 books outside delimitation] * [permutation in-between] * [number of ways to achieve 6 spaces]
(4) 5 Spaces: P (3, 2) * P(3,3) * P(5, 5) * 4
[Delimiting math books] * [options for 3 books outside delimitation] * [permutation in-between] * [number of ways to achieve 5 spaces]
Then my final answer would be (1) + (2) + (3) + (4). My worry is that I'm missing some duplicates somehow.
Also conveniently, I believe the total for 5 spaces would satisfy the simpler question if it is actually referring to permutations with the chunk MCCCCCM.
Thanks in advance! I'd love to see specifically what I'm doing wrong (if I am indeed wrong).
Comment: To the left would be less ambiguous. By the way, is MMCCCCCM allowed? Then there are two math to the left of the cpsc.
Comment: Yes that is allowed. I think I have accounted for that in the [options for books outside the delimitation] cases, by setting it to the 2 art books + 1 remaining math book: P(3, 1/2/3) depending on the case
Answer: Here is an approach that avoids using cases.
Set aside the art books for the moment.  We will place them later.
We have to arrange the five distinct computer science books and three distinct mathematics books so that there is at least one mathematics book to the left of all the computer science books and at least one mathematics book to the right of all the computer science books.  We have three choices for which mathematics book will be placed on the left end of the row and two choices for which mathematics book will be placed on the right end of the row.  We now have six books (five computer science books and the remaining mathematics book) to arrange between the mathematics books we have placed at the ends of the row.  We can arrange these six books in $6!$ ways.  Hence, there are $3 \cdot 2 \cdot 6!$ ways of arranging the mathematics and computer science books.
We now have nine spaces (seven spaces between the eight books we have already placed and the two ends of the row) in which to place the first art book.  Once it is placed, we have ten spaces (eight spaces between the nine books we have already placed and the two ends of the row) in which to place the second art book.  Hence, we can arrange five distinct computer science books, three distinct mathematics books, and two distinct art books so that at least one mathematics book is to the left of all the computer science books and at least one mathematics book is to the right of all the computer science books in
$$3 \cdot 2 \cdot 6! \cdot 9 \cdot 10$$
ways.
Comment: N. F .Taussig i dont think there are $6!$ ways it implies the 3rd book can also be between any two CS books.can you explain further
Comment: @ArchisWelankar  Since the only restrictions are that there must be at least one mathematics book to the left of all the computer science books and and at least one mathematics book to the right of all the computer science book, we can place the third mathematics book anywhere in the row as long as the previously mentioned conditions are met.
Answer: There are $10$ places to put a book. Place the art books in one of $10\cdot 9$ ways.
Now we order the remaining books, which then go onto the $8$ places left empty so far: We can order the five CS books among themselves in $5!$ ways and the three math books among themselves in $3!$ ways. Put $M_1$ to the left of the CS books and $M_3$ to the right of the CS books. Choose one of the $6$ slots so created for $M_2$.
In all there are
$$10\cdot9\cdot 5!\cdot 3!\cdot 6=388\,800$$
possibilities.
Comment: This answer is equivalent to the one I marked correct. Thank you for the time in answering the question, I really appreciate it.
Answer: (10!/8!)*(5!3!)*6_____ must be the answer.
First consider selecting 2 out of 10 positions on the shelf. This can be done in 10C2 ways.
Now keep the two art books on these two positions. These art books can be shuffled in 2! ways in these two positons.
We can keep the maths books on the remaining 8 positions on the shelf in 6 ways___ the first and the last positions in serial order with respect to the shelf must always be assigned to two maths books, and the third maths book can be kept on any of the remaining six positions out of the eight positions.
This is because if we consider these eight positions in serial order, the five computer books must always be in between two maths books, which means that there must be a math book on both the extreme positions.
Once we have assigned the positions to books of different subjects, we can shuffle them in 3! * 5! ways, This is because the maths books can be shuffled in 3! ways and the computer books can be shuffled in 5! ways.
Thus total number of ways are ( 10 C 2 ) * 2! * 6 * 3! * 5! = (10!/8!)*(5!3!)*6
However, if the maths books which are to be kept on the extreme positions are already decided, then there would be 6! ways to arrange the remaining six books. In that case answer would be
10!/8! * 6! = 10*9*6!
Comment: I have just a bit of confusion about this line:

" the first and the last positions in serial order with respect to the shelf must always be assigned to two maths books"

Why must they be on the extremes? couldn't there be an art book between the math book and the computer science books? I may be misunderstanding
Comment: No I'm saying the extremes of the eight positions on the shelf out of the 10 positions must be assigned to the two maths books, not the extreme positions on the shelf.
Answer: Converted to "just before/after" approach

Take out $2$ math books as well as both the arts books in $\binom32 = 3$ ways.
Permute the remaining $6$ in 6! ways
Insert $2$ math books just before/after computer science books in $2$ ways.
Insert the arts books successively in gaps (including ends) in $9\cdot10 = 90$ ways

$\qquad 3\cdot6!\cdot2\cdot 90 = 388,800$


Android toolbar ocupando todo espaço do layout

Question: Estou tentando realizar a implementação de um Toolbar em minha aplicação Android, mas por algum motivo ele ocupa todo espaço da tela.
Gostaria de saber por que, já que estou usando a propriedade below no layout depois do toolbar.
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Main">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"></include>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tool_bar">

        <LinearLayout
            android:id="@+id/llLogotipo"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imgLogotipo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:src="@drawable/dmufscar" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/frmbotoes"
            android:layout_width="fill_parent"
            android:layout_height="100dp"
            android:layout_below="@+id/llLogotipo"
            android:orientation="horizontal">

            <Button
                android:id="@+id/btnIniciarRFID"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="RFID" />

            <Button
                android:id="@+id/btnPatrimonio"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_weight="1"
                android:text="@string/btnPatrimonio" />
        </LinearLayout>
    </RelativeLayout>

</RelativeLayout>

tool_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    android:elevation="4dp">

</android.support.v7.widget.Toolbar>

Answer: Em seu arquivo toolbar.xml , faça as seguintes alterações:

Troque a linha android:layout_height="match_parent" por
android:layout_height="wrap_content"

Adicione a seguinte linha:
android:minHeight="?attr/actionBarSize"

Comment: Joia amigo! Deu certinho


How can I keep a record of user email addresses when users update their email address?

Question: I have a site where a minority of users are causing trouble by registering with one email address and then changing to another email address. Email Change Confirmation helps with this, but I would also like to keep a record of changed email addresses per-user, preferably in the Drupal UI.
I am thinking about making an email address field and using rules to automatically add an old email address when the user changes his or her email, but if there is a more robust solution I would love to know about it.
Comment: if you want to eliminate changes, you could grey out the email field in the user edit form, preventing users from changing their email - and then add new fields as 'alternative' emails, maintaining the integrity of the registration email
Comment: @Geoff I definitely don't want to eliminate changes, just keep track of them.  There are lots of legitimate reasons a user may want to change his or her email address.
Answer: The first thing that came to mind is Drupal's revision feature. Out of the box, Drupal let's you keep records of what changes are made to nodes over time. Users are a different entity, but the User Revision module aims to provide the same functionality. This Lullabot article explains it pretty well. You could give it a shot.


Galeria de Imagem SWIFT e Storage do Firebase

Question: Boa tarde,
Estou finalizando um APP desenvolvido em Swift 4, com Xcode 9 e Firebase.
Eu já consigo me logar com Firebase, e enviar e-mail pelo meu App, o que eu preciso fazer, que não estou conseguindo de jeito nenhum é como montar uma galeria de imagem, com as imagens que eu gravo no Storage do Firebase, mas isso de forma automática, eu já consigo enviar as imagens para o Storage do Firebase.
Segue o que eu quero fazer, estou a 3 semanas tentando e lendo vários tutoriais mais não consigo.
Considerando que as imagens já estão no Storage do Firebase:

Listar em uma galeria de imagem, todas as fotos salvas pelo usuário no Storage do Firebase;
Essa lista tem que ser miniaturas das imagens, e ao clicar elas ficam no tamanho normal que estão gravadas.

Obs.: Tem essa biblioteca que monta a galeria de imagem, do jeito que eu quero, mas eu não sei utilizar e nem como eu faria para carregar as imagens automaticamente do Fisebase ( biblioteca:https://github.com/mwaterfall/MWPhotoBrowser)
Poderiam me ajudar por favor.
Obrigado
Comment: O Firebase Storage não tem uma forma de mostrar todas as imagens que estão lá armazenadas. O que você terá de fazer é guardar a lista de imagens na sua Database. Assim fica mais fácil de listar elas
Answer: Opa, blza!?
O que fiz foi o seguinte: toda vez que fazia o upload de uma imagem, eu gravava no perfil do usuário o caminho que a foto foi salva:
    func uploadImage() -> Void {
    let storage = Storage.storage()
    let nomeImagem = self.nome + ".jpg"
    let storageRef = storage.reference().child("App/Usuarios").child(userID).child("ImagemPerfil").child(nomeImagem)
    let metadata = StorageMetadata()
    metadata.contentType = "image/jpeg"

    if let uploadData = UIImageJPEGRepresentation(self.imagemPerfil.image!, 0.2){
        storageRef.putData(uploadData, metadata: metadata, completion: { (metadata, error) in
            if error == nil{
                storageRef.downloadURL { url, error in
                    if error != nil {
                        // Handle any errors
                    } else {
                        self.mEleitorModel.urlFotoPerfil = url?.absoluteString
                        self.gravaUsuario()
                    }
                }
            }
        })
    }
}

gravava o usuário com o caminho da imagem, no seu caso vc pode criar uma lista com as imagens atreladas ao usuario:
para carregar a imagem, ligue da view no seu código e faça o seguinte(esse cod ai deixa ela redonda, caso nao queira remova):
    func carregaImagem() -> Void {
    let url = URL(string: mCandidato.urlFotoPerfil!)
    let data = try? Data(contentsOf: url!)
    imagemPerfil.image = UIImage(data: data!)
    imagemPerfil.layer.borderWidth = 1.0
    imagemPerfil.layer.masksToBounds = false
    imagemPerfil.layer.borderColor = UIColor.white.cgColor
    imagemPerfil.layer.cornerRadius = imagemPerfil.frame.size.width / 2
    imagemPerfil.clipsToBounds = true
}

Para adicionar uma lista de imagens, crie um dicionário de url, e já manda o dicionário pro firebase.
Caso seja uma lista de imagens, basta colocar um for antes de carregar elas.


prove that if $ T^2=T $ then T is diagonalizable operator ( over finite dimension vector space)

Question: I know its a very basic question in linear algebra, and I actually solved it myself. But something's tells me there's a lot more ways to prove it, and I'd like to see some other informative ways that I can learn from.
So, let V be a vector space with finite dimension n. and let $ T^2=T $ be a linear operator $ T: V\to V $ (I think its called projection).
We need to prove that T is diagonalizable operator.
What I've done:
Since $ T^2=T $ we can prove that $ V=Im\left(T\right)\oplus Ker\left(T\right) $.
Assume $ \dim Ker\left(T\right)=n_{1} $
and
$ \dim Im\left(T\right)=n_{2} $
So, $n_1+n_2=n $  . and notice : $ \ker\left(T\right)=W_{0} $
$ Im\left(T\right)=W_{1} $
meaning $KerT $ is the eigenspace of the eigenvalue $ 0 $ and $ImT $ is the eigensapce of the eigenvalue $ 1 $
The fact that $ KerT $ is the eigenvalue of $ 0 $ is trivial i guess.
And $ImT$ is the eigenspace of $ 1 $ because:
for any $ v\in V $ $ v\in Im(T) \iff T(v)=v $
proof:
$ \Longleftarrow $
Thats trivial.
$ \Longrightarrow $
since $ v\in Im(T) $ There's $ u\in V $ such that  $ T(u)=v $ so
$ T\left(v\right)=T\left(T\left(u\right)\right)=T^{2}\left(u\right)=T\left(u\right)=v $
Thus, $ ImT $ is the eigenspace of $ 1 $.
since $n_1+n_2=n$ the algebric multiplicity  and geometric multiplicity  of both eigenvalues equal, therefore T is diagonalizable (now at this point im counting on an argument I havent proved myself, but rather accepted as a fact. If anyone can show me the proof, It will be helpful.
Besides, I'd like to see some more ways, if exists, of proving this statement.
Answer: Note that $T$ satisfies $f(x) = x^{2} -x = x(x-1)$.
The minimal polynomial of $T$, $m_{T}(x) = \{x, x-1, f(x) \}$.
It is a fact that if the minimal polynomial splits into distinct linear factors, then $T$ is diagonalizable.
One can even be more explicit:
$m_{T}(x) = x \implies$ T is similar to the zero matrix.
$m_{T}(x) = x - 1 \implies $ $T$ is similar to the $n \times n$ identity matrix.
$m_{T}(x) = x(x-1) \implies T$ is similar to the matrix gotten from the set of $k$ elements invariant factors: $\{f(x), \cdots, f(x) \}$, where $2k = n$, where $n$ is the dimension of the vector space or the degree of the characteristic polynomial.
Comment: Thats wonderful solution, Thanks. a few questions if I may: If I remember correctly, we prove back it the lecture that for every $ f\in F[X] $ that satisfies  $ f\left(T\right)=0 $ its true that: $ f|\left(m_{t}\right)^{n} $. So can we coclude that $ f $ and $ m_T $ has the same Irreducible products, and therefore $ m_T $ has to be $ x(x-1) $ ? also, why mT(x)=x⟹  T is similar to the zero matrix ? I'd understand if it were the characteristic polynomial, but it dosent sounds trivial for the minimal polynomial.
Comment: If $f(T) =0$, then all that you can claim is that the minimal polynomial is a divisor of $f$. Unfortunately, the characteristic polynomial won't be of much help (f of course, is not the characteristic polynomial). if $m_{T}(x) = x$, then $0_{n \times n} = m_{T}(T) = T$.
Answer: Let $p(x) = x^2 - x$. Then $p(T) = T^2 - T = T-T = 0$, so $T$ is a root of $p(x)$. It follows that the minimal polynomial $m_T(x)$ for $T$ divides $p(x)$. If $T$ is a root of $x$, then $T$ is the zero operator, which is diagonalisable. If $T$ is a root of $x-1$, then $T$ is the identity operator, which is diagonalisable. Otherwise, $m_T(x) = p(x) = x^2 - x$. Hence, $T$ is diagonalisable since the minimal polynomial has no repeated roots.


How to use integer literals and arithmetic within Haskell data kinds

Question: I have recently started messing around with DataKinds in order to have compile-time scientific units for arithmetic. I have more or less figured out a way to do what I want but I feel like it could be a lot cleaner.
I needed integers that could potentially be negative (m^-1) so I decided to use integers rather than naturals. But as it turns out when you do :k 5 it gives you GHC.Types.Nat which does not fit my needs. I ended up instead making my own custom algebraic integer type. As well as defining addition and subtraction type families to use with it.
But this all seems very indirect, it seems like there is no good reason why I can't just directly use all the existing functions for manipulating data at compile time within type families.
Basically I want the following to essentially be generated automatically:
type family (a :: Int) + (b :: Int) :: Int where
    -- Should be automatically derivable from (+) applied to Int

Is that possible, if not then why not?
Also is there an easy way to obtain a runtime value back from a type? Specifically when writing a Show instance for all these types I basically just want to pull in the phantom type representing the unit combination and convert it to a string. All the ways I can think of doing that right now seem really verbose.
Comment: "there is no good reason why I can't just directly use all the existing functions" - the reason is that Haskell is not a dependently-typed language. There's a separation between values and types, which means that you have to duplicate code between the two levels and use tedious hacks like singleton values. [The Haskell designers are hard at work on lifting that restriction](http://cs.brynmawr.edu/~rae/papers/2016/thesis/eisenberg-thesis-draft.pdf); in the mean time, you could consider using a real dependently-typed language like Agda or Idris.
Comment: I don't think this can be done in current Haskell. In a type family definition, we are not allowed to use value expressions (which have a type), only type expressions (which have a kind). Hence, I believe we currently have no way to refer to the value-level definition of `(+)`.
Comment: Are you familiar with [Dimensional](https://github.com/bjornbm/dimensional)?
Comment: It seems like you are really just looking for dependant types (which as @BenjaminHodgson stated, Haskell does not yet have). "Also is there an easy way to obtain a runtime value back from a type?" In a dependantly typed language, both 'type' and 'values' are simply terms, i.e. there is no distinction. But the tradeoff for more expressiveness is more proof obligation - you will have to convince the compiler of many things you simply consider axiomatic.
Comment: @chi But the following works: `type family Foo a where { Foo False = Nothing; Foo True = Just () }`. So we can clearly use a subset of value expressions, I am just wondering why we can only use certain value expressions.
Comment: @BenjaminHodgson But I really want to keep all the things I love about Haskell, plus this was mostly a learning exercise to improve my knowledge of GHC extensions.
Comment: @user2407038 I don't see why you would need more proof obligation, maybe for certain aspects of dependent types but I really cannot tell why you would need to prove anything more for doing what my original question asked, all I am asking to do here is remove boilerplate.
Comment: @semicolon That is because we can lift value constructors to the type level via `DataKinds`. We do not have (yet) a way to lift other value expressions, though. I.e. if we let `n = Nothing` we can't use `Foo False = n` later on. We need `type N = Nothing` instead. Many things can be lifted manually at the type level, but the automagic lifting is far from being universal (albeit it is still very useful, and quite amazing!).
Comment: @BenjaminHodgson Full fledged dependent types don't seem to be needed here.  This functionality is implementable in C++ which is hardly a dependently typed language.
Comment: @n.m. What do you mean by that specifically? Because the program itself I got working just fine, I just wanted things to be more concise. In C++ can you really do unrestricted compile time data manipulation within phantom types? I would be pretty surprised if that were true.
Comment: @semicolon not unrestricted, but compile time integer arithmetic is built in
Answer: It looks like the answer to this question is simply that you cannot currently do either of those things automatically. Hopefully it won't take too long before this kind of thing becomes possible.
Comment: It's likely to happen soonish, I'd say. Maybe 8.4 or 8.6, unless they decide it justifies a major-major version bump and call whatever release it is 9.0.


Verificando Diretório (WINDOWS)

Question: Como faço para verificar se um diretório existe usando C++ e Windows API?
Answer: Existe a função GetFileAttributesA que recupera os atributos do sistema
para um diretótio ou arquivo especificado.
Maiores informações  ->  MSDN
Aqui uma função simples que faz exatamente o que você quer:
bool HYPNOS_DIR_VALIDATE(const std::string& hypnos_dirNAME)
{
  DWORD hypnos_ftyp = GetFileAttributesA(hypnos_dirNAME.c_str());
  if (hypnos_ftyp == INVALID_FILE_ATTRIBUTES)
    return false;  // algo de errado com o path

  if (hypnos_ftyp & FILE_ATTRIBUTE_DIRECTORY)
    return true;   // É um diretório!

  return false;    // Não é um diretório.
}

Comment: O que é o "hypnos"?
Comment: Ok! Boa sorte para o teu projecto. Diverte-te!
Comment: Cara... kkkkk
é só um projeto meu.. :)
Comment: Hahaha, Obrigado!

Verificando Diretório (WINDOWS)


Why does every 7-manifold bound an 8-manifold?

Question: I'm glancing over Milnor's paper on exotic 7-spheres, and one of the first few lines says, `every closed 7-manifold $M^7$ is the boundary of an 8-manifold $B^8$.
Here's what I don't understand: The unoriented cobordism ring is isomorphic to a polynomial ring over $\mathbb{Z}_2$ with a generator in every degree except $2^m -1$ for any $m$. In particular, there are generators $x_2$ and $x_5$ in degrees $2$ and $5$, respectively. So: why does their product not represent a nontrivial element of the group of cobordism classes of 7-manifolds?
Apologies if this is a silly question... I'm new to all of this.
Comment: Since the question has been resurrected, I'll add a small tidbit (4 years late!)  Practically, Milnor only considers $S^3$ bundles over $S^4$ with structure group $SO(4)$.  The linear action of $SO(4)$ on $S^3$ extends to a disc, and so each of his manifolds is the boundary of the associated disc bundle $D^4$ over $S^4$.  In particular, you don't need Thom's computation of the oriented bordism ring for Milnor's paper to work
Comment: If you don't get a good answer within a couple of days, feel free to post this to MathOverflow.This is an appropriate level of question for that forum.
Comment: @Rasmus: No I don't think that it is always the case that the product of nontrivial classes is nontrivial. But in this case we're in a polynomial ring, which is a free algebra... so the product of two `indterminates' shouldn't be zero, right? Otherwise we would be imposing some extraneous relation...
Comment: Is your point that you think that a product of two non-trivial classes *must* be non-trivial? That's not true, as your reasoning shows.
Comment: Apologies for my earlier ignorant response.  I didn't appreciate the intricate nature of the question.  I would also like to second Jim's suggestion: it might be profitable to post this at MathOverflow.
Answer: Milnor is referring to oriented bordism there, not un-oriented bordism.  Not every 7-manifold bounds an 8-manifold as you've observed from Thom's computation of the unoriented bordism ring, being a polynomial ring and having generators in dimension 2 and 5 (and many other dimensions).
But I believe it goes back to Rene Thom, that the bordism group of oriented 7-manifolds is trivial.
Answer: EDIT: The first paragraph is nonsense... but I'm keeping this here since the comments might be helpful to people looking at this question.
Looks like I figured out the answer to my own question! In the shower just now, I came up with a 7-manifold not bounded by an 8-manifold: $\mathbb{RP}^2 \times S\mathbb{RP}^4$ (Edit: this doesn't quite work yet; don't trust things you find out about in the shower. I just need a 5-manifold with odd Euler characteristic... any ideas?). Indeed, notice that its Euler characteristic is the product of the Euler characteristics of the factors, which are both odd. Boundaries of manifolds have even Euler characteristic, therefore this one is not a boundary, and it is clearly 7-dimensional.
So my confusion stemmed from the fact that the claim `every 7-manifold is a boundary' is false! After a more careful skimming of Milnor's paper, it looks like, even though he uses the unqualified phrase "every 7-manifold is a boundary" he really only uses that "every orientable 7-manifold is a boundary of an orientable 8-manifold."
I'm not entirely sure why this is true, but some evidence comes from the fact that if we invert $2$ in the oriented cobordism ring, then it becomes isomorphic to a polynomial algebra over $\mathbb{Z}[1/2]$ with generators in every 4th dimension... so at least we know that there's nothing appearing in dimension 7 except possibly some 2-torsion. Anyone know why there's no 2-torsion there?
Comment: And so every compact 5-manifold has Euler characteristic zero, since non-orientable manifolds are finitely covered by orientable ones.  This applies to all odd-dimensional manifolds.
Comment: You probably know this, but just to be sure: a compact orientable manifold of odd dimension has vanishing Euler characteristic, by Poincare duality.
Comment: Take the Cartesian product of representatives of the generators $x_2$ and $x_5$ in the unoriented cobordism ring!  We know $x_2=[\mathbb{R}P^2]$, but this only works for $x_{2i}$.  Apparently Dold gives representatives for $x_{2i+1}$ (for $2i+1\not= 2^j-1$, of course!) in "Erzeugende der Thomschen Algebra $N$", 1956.
Comment: This answer needs a slight tweaking and then it will be correct... I'll think about finding manifolds with odd Euler characteristic, and then check back here later today.
Comment: Ah, whoops. Well then can you think of an explicit example of a non-orientable 7-manifold that is not a boundary?
Comment: Well, duh :P I was asking for explicit descriptions of what those manifolds look like! :)
Comment: Just for the record, the Wu manifold $SU(3)/SO(3)$ is an example of a closed 5-dimensional manifold which is not nullcobordant, in fact $[SU(3)/SO(3)]$ is the only non-zero element of $\Omega^O_5 \cong \mathbb{Z}_2$. So $\mathbb{RP}^2\times(SU(3)/SO(3))$ is a closed 7-manifold which doesn't bound.
Answer: Because all its Stiefel-Whitney numbers are all zero.
Comment: This is false in general, as other answers show.


How can I select my agent in microsoft azure CI pipelines using azure-pipelines.yml

Question: I have this script:
trigger:
- master

pool:
  name: Mobile-Pool
  agent: 'MacMini3-AMS'
  vmImage: 'MacMini3-AMS'

steps:
- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'clean assembleDebug testDebugUnitTest'

# Bash
# Run a Bash script on macOS, Linux, or Windows
- task: Bash@3
  inputs:
    targetType: 'filePath'
    filePath: 'run-tests-on-emulator.sh'

- task: Gradle@2
  inputs:
    workingDirectory: ''
    gradleWrapperFile: 'gradlew'
    gradleOptions: '-Xmx4096m'
    publishJUnitResults: false
    testResultsFiles: '**/TEST-*.xml'
    tasks: 'connectedDebugAndroidTest'

I am running my own on-premise hardware. I have a MacMini3 and a MacMini2. The MacMini2 doesn't compile properly, and I want to run on the MacMini3. How can I change the yaml script to do so?
Answer: You should use Demands to make sure that the capabilities your pipeline needs are present on the agents that run it.
pool:
  name: MyPool
  demands:
  - myCustomCapability   # check for existence of capability
  - agent.os -equals Darwin  # check for specific string in capability

In your scenario, you can use Agent.Name or Agent.ComputerName demand.
Comment: It now runs on Agent: MacMini3. So this question is answered. But the problem turns out to not be the machine...


Automate multiple registrations of 'sender' accounts for Android C2DM?

Question: I'm wondering if it is possible to develop a script to submit multiple apps - ALL AT ONE GO OR ONE BYE ONE - to Android Cloud to Device Messaging  (https://developers.google.com/android/c2dm/signup).
We have multiple apps to register on a regular basis and it is too time-consuming to do this manually everytime.
We understand that it is technically possible, but does Google policy allow this?
Note:
I am aware that there is no API.
I have tested with script to post to that form and it worked.
I don't mind comments coming.
Answer: We had to use GSM and there is no way to do via script now!
We have to register manually!


Robolectric ContentProvider testing

Question: I have noticed that every now and then there is a question about using Robolectric for testing custom ContentProviders. However, there has never been a concrete and unambiguous answer on how to do it properly. I have stumbled upon 2 different approaches:

one saying you can simply instantiate an in-memory ContentProvider, which you can use to insert and query data (https://gist.github.com/anonymous/6139359)
the other saying to use the ShadowContentResolver to set mock cursor data (https://groups.google.com/d/msg/robolectric/r35mMirIkTs/xJJBNXl_RgwJ)

However, I'm getting a java.lang.InstantiationException with both approaches. There have been some SO posts saying that this is due to SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java) not being overriden in Robolectric (Android + Robolectric - RuntimeException / InstantiationException in queryBuilder.query() in ContentProvider).
I guess my question is - are there any preffered workarounds that make testing ContentProviders possible. Or are there any other approaches that are better then those 2 mentioned above.
Comment: I suggest not to use first link at all - code there is completely dumb and won't even compile.
Answer: This is the Robolectric (v2.4) test that worked fine for me:
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

import org.joda.time.LocalDate;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.Robolectric;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import org.robolectric.shadows.ShadowContentResolver;

import co.tomup.app.db.DbSchema;
import co.tomup.app.db.TomupContentProvider;
import co.tomup.app.db.model.CalendarDay;
import co.tomup.app.db.tables.CalendarDayTable;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class CalendarDayProviderTest {

    private ContentResolver mContentResolver;
    private ShadowContentResolver mShadowContentResolver;
    private TomupContentProvider mProvider;

    @Before
    public void setup() {
        mProvider = new TomupContentProvider();
        mContentResolver = Robolectric.application.getContentResolver();
        mShadowContentResolver = Robolectric.shadowOf(mContentResolver);
        mProvider.onCreate();
        ShadowContentResolver.registerProvider(DbSchema.AUTHORITY, mProvider);
    }

    @Test
    public void testInsertAndDelete() {
        // insert
        CalendarDay calendarDay = new CalendarDay();
        calendarDay.setId(1L);
        calendarDay.setDay(new LocalDate());
        calendarDay.setMoonPhase("new");
        calendarDay.setSunrise(1);
        calendarDay.setSunset(100);
        Uri insertionId = mContentResolver.insert(CalendarDayTable.CONTENT_URI,
                calendarDay.toSQLiteContentValues());
        Cursor cursorCheck = mShadowContentResolver.query(CalendarDayTable.CONTENT_URI,
                null, null, null, null);
        while (cursorCheck.moveToNext()) {
            CalendarDay calendarDayCheck = CalendarDay.fromSQLiteCursor(cursorCheck);
            assertEquals(calendarDay, calendarDayCheck);
        }
        assertTrue(cursorCheck.getCount() > 0);
        // delete
        mShadowContentResolver.delete(insertionId,
                null, null);
        cursorCheck = mShadowContentResolver.query(CalendarDayTable.CONTENT_URI,
                null, null, null, null);
        assertTrue(cursorCheck.getCount() == 0);
    }
}

Comment: Note this answer is for RoboElectric 2.4, if you are using 3.0 then use https://github.com/robolectric/robolectric/wiki/2.4-to-3.0-Upgrade-Guide to find the 3.0 equivalents.
Comment: Thanks for your answer. I am relying more on learning Android using robolectric. I get tired of going back and forth with the emulator. And this answer is helping me to user and test contentprovider. :)
Comment: @Benjamin do you know if there's an example using 3.0?  Are the only changes you have to make are to the class & annotation names?  Here's are the changes I've interpreted from the document --> change the test runner to RoboelectricGradleTestRunner, and maybe change getApplication to getShadowApplication.  Is that correct?
Answer: All you have to do, is set up ShadowContentResolver before test, so it will properly associate authority of your ContentProvider with ContentProvider itself. Here is an example:
ShadowContentResolver.registerProvider(
        "com.example.provider",    //authority of your provider
        contentProvider    //instance of your ContentProvider (you can just use default constructor)
);

The easiest way is to put this stuff into some @Before annotated set-up method. However, the more correct (and therefore better in long term) way is to put this into your TestApplication#onCreate method, so this configuration will be used by all tests in your application.
Comment: @HieuRocker yes, I do. If I understood you correctly, then you got it a bit wrong - that should be expected behavior for tests to clean up after execution. Just create your database each time in some `@Before` method
Comment: I put the above code into `TestApplication#onCreate` but it couldn't use the content provider for all tests. After the first test the database will be removed: https://github.com/robolectric/robolectric/issues/1082 . Did you success to have more than 2 tests for content provider with Robolectric?
Comment: W00t, I could fix the issue based on your hint. Turned out it was because in the ContentProvider, I initialized `SQLiteOpenHelper` using singleton pattern. It causes Robolectric failed to recreate the database for each test. Thanks a lot.
Answer: Using Roboelectric 4.2, this is what worked for me:
@RunWith(RobolectricTestRunner.class)
public class MyContentProviderTest {

    private ContentResolver contentResolver;
    private MyRepository repository;

    @Before
    public void setup() {
        repository = mock(MyRepository.class);
        contentResolver = ApplicationProvider.getApplicationContext().getContentResolver();

        ProviderInfo info = new ProviderInfo();
        info.authority = "my.authority";
        info.grantUriPermissions = true;
        ContentProviderController<MediaContentProvider> controller = Robolectric
                .buildContentProvider(MyContentProvider.class)
                .create(info);

        MyContentProvider provider = controller.get();
        // Method in my ContentProvider that allows to override
        // the repository it uses
        provider.setRepository(repository);
    }

    @Test
    public void testQuery() {

        // setup expectations in mockito
        when(repository.getAll()).thenReturn(...);

        try (Cursor cursor = contentResolver.query(SOME_URI, null, null, null, null)) {
            // test cursor contents here
        }

    }
}

Answer: Thanks to Wim Deblauwe's answer, I have also done with roboelectric 4.2 in Kotlin
, Here is the full demonstration:
this is my custom provider class
    //this is my custom provider class
    public final class NameProvider : ContentProvider() {
        private var pContext: Context? = null;
        private var nameDbHelper: NameDbHelper? = null
        private var dataBase: SQLiteDatabase? = null
        private val Log_Tag = "NAME_PROVIDER"

        override fun onCreate(): Boolean {
            pContext = context
            nameDbHelper = pContext?.let { NameDbHelper(it) }
            dataBase = nameDbHelper?.writableDatabase
            if (dataBase == null) {
                Log.d(Log_Tag, "dataBase NOT created ...")
                return false
            }
            Log.d(Log_Tag, "dataBase created ...")
            return true
        }

        override fun query(p0: Uri, p1: Array<out String>?, p2: String?, p3: Array<out String>?, p4: String?): Cursor? {
            var queryBuilder : SQLiteQueryBuilder = SQLiteQueryBuilder()
            queryBuilder.tables = "TABLE_NAME"
            val cursor = queryBuilder.query(dataBase,p1,p2,p3,null,null, "COLUMN_NAME")
            cursor.setNotificationUri(pContext?.contentResolver, p0)
            return cursor
        }

        override fun insert(p0: Uri, p1: ContentValues?): Uri? {
            val rowID: Long? = dataBase?.insert("TABLE_NAME", "", p1)
            rowID?.let {
                if (it > 0) {
                    val _uri = ContentUris.withAppendedId(CONTENT_URI, it)
                    pContext?.contentResolver?.notifyChange(_uri, null)
                    return _uri
                }
            }
            throw SQLException("Failed to add a record into")
        }

        override fun getType(p0: Uri): String? {
            TODO("Not yet implemented")
        }

        override fun delete(p0: Uri, p1: String?, p2: Array<out String>?): Int {
            TODO("Not yet implemented")
        }

        override fun update(p0: Uri, p1: ContentValues?, p2: String?, p3: Array<out String>?): Int {
            TODO("Not yet implemented")
        }
    }

this is my test class with roboelectric
    @Config(maxSdk = 29)
    @RunWith(RobolectricTestRunner::class)
    class NameProviderTest {

        private var contentResolver : ContentResolver? = null
        private var shadowContentResolver : ShadowContentResolver? = null
        private var nameProvider : NameProvider? = null

        @Before
        fun setUp() {
            contentResolver = ApplicationProvider.getApplicationContext<Context>().contentResolver
            val providerInfo : ProviderInfo = ProviderInfo()
            providerInfo.authority = NameContract.AUTHORITY
            providerInfo.grantUriPermissions = true
            val controller = Robolectric.buildContentProvider(NameProvider::class.java).create(providerInfo)
            shadowContentResolver = shadowOf(contentResolver)
            nameProvider = controller.get()

        }

        @Test
        fun onCreate() {
            val res  = nameProvider?.onCreate()
            assertEquals(res, true)
            //ShadowContentResolver.registerProviderInternal(NameContract.AUTHORITY, nameProvider)
        }

        @Test
        fun query() {
            val values =  ContentValues()
            values.put(NameContract.KEY_NAME, "ABCD")
            val uri = contentResolver?.insert(NameContract.CONTENT_URI, values);
            assertNotNull(uri)
            val cursor = contentResolver?.query(NameContract.CONTENT_URI,null,null,null,null)
            assertNotNull(cursor)
            var name : String? = null
            if(cursor != null && cursor.moveToFirst()){
                name = cursor.getString(cursor.getColumnIndex(NameContract.KEY_NAME))
            }
            cursor?.close()
            assertNotNull(name)
            assertEquals(name, "ABCD")
        }

        @Test
        fun insert() {
            val values =  ContentValues()
            values.put(NameContract.KEY_NAME, "Taher")
            val uri = contentResolver?.insert(NameContract.CONTENT_URI, values);
            assertNotNull(uri)

        }

    }

Answer: I have added a pull request for robolectic which adds a replacement for ProviderTestCase2: https://github.com/robolectric/robolectric/pull/2060.

Robolectric ContentProvider testing


File upload with nodejs, express and angular using dropzone

Question: I'm having trouble getting the file recognized server side with node.
Specifically when accessing request data, (req.files or req.body)
Here are some snippets if someone has any advice.
html:
<form action="/upload" class="dropzone" drop-zone id="file-dropzone"></form>

angular controller:
'use strict';

angular.module('app')
  .controller('SampleCtrl', function ($scope, $http) {

  })

  .directive('dropZone', function() {
    return function(scope, element, attrs) {
     $(element).dropzone({
        url: "/upload",
        maxFilesize: 100,
        maxThumbnailFilesize: 5
    });
  }
});

node router:
'use strict';

var express = require('express');
var controller = require('./import.controller');

var router = express.Router();

router.post('/', controller.import);

module.exports = router;

node controller:
'use strict';

var express = require('express'),
    _ = require('lodash'),
    fs = require('fs'),
    path = require('path'),
    multer = require('multer'),
    bodyParser = require('body-parser'),
    app = express();

app.use(bodyParser.urlencoded({extended: true}));

exports.import = function(req, res) {
    console.log(req.files); // responds with 'undefined'
    console.log(req.body); // responds with {}
};

thanks in advance
Comment: You're adding the **multer** middleware to the `app` in your controller. I don't think it is doing what you expect it to as  `exports.import` has no connection to `app`.
Comment: Hi, I have the exact same issue, did you manage to make it work?
Answer: You have to actually use the file upload middleware to get express to unpack that part of the request.  From the multer docs:
var express = require('express')
var multer  = require('multer')

var app = express()
app.use(multer({ dest: './uploads/'}));

console.log(req.body)
console.log(req.files)

Comment: thanks for the reply. unfortunately adding app.use(multer({ dest: './uploads/'})); still gives me the same responses.