In .Net 4.0 is the Data Access Application Blocks still the way to implement data connections?

Question: I have been stuck in 2.0 for some time now due to what my job requires and I am trying to now keep up with the latest .net framework.  I am begining to build a Mvc application and I am wondering if the Data Access Application Blocks (SqlHelper) is still an acceptable method of writing a data tier.
I know there is a lot of debate over the EF, with it's speed performance, lazy loading and the issue of keeping the database separate from the application.  So I hesitate to go there right now.
But I am seeing a lot of code that just uses ADO.Net and the DataAdapter and wondering if there was a shift back to ADO.net without a helping framework.  If this is correct then my question would be why?  It seems like a step backwards to not use some type of helper class/framework to do data access.
Comment: Most of the Pattern and Practices practices have fallen out of practice.
Comment: I put the 4.0 tag in there because the question is specific to the 4.0 framework
Comment: Actually, it isn't. This is a generic issue that Java programmers will face too (use an additional framework or the built in Java packages), for example.
Answer: The use of ORMs is seen as best practice these days, and the Data Access Application Block has fallen out of favor as other, easier to work with libraries have come to existence and prominence in the .NET world.
These would include nHibernate, LINQ to SQL, Entity Framework to mention the big, fully featured libraries (some more fully featured than others).
People who do use ADO.Net directly are those who want more control over their SQL than afforded by these (always possible with ORMs, but they tend to be rather cumbersome when it comes to accessing the database not through their idioms).
An example lightweight ORM is Dapper, which is a very thin layer over ADO.Net.


How can vertically center a chunk of line-wrapping text next to an image?

Question: I have some legacy table code here. I'd like to rewrite that in a way that uses good ol' CSS, but am having trouble.
Also, using a background-image instead of the img is not an option, as there will be many different images.
Here's my attempt, but I can't get the darn thing to stay inline with the image and remain vertically centered.
How would I do this?
Answer: Oh wait, solved it:
http://www.jsfiddle.net/Eric/fRaU7/14/


In minor, can the neapolitan sixth chord resolve to the diminished seventh chord on the leading-tone (of the same key)?

Question: What would that look like voice-leading-wise? I'm assuming more or less traditional common-practice harmony rules. Examples from the literature would be much appreciated.
Answer: My hunch is that, if a ♭II6 did resolve to vii°7, it would tend to resolve to one in second inversion (that is, vii°43). This way, the bass scale-degree 4 stays constant. This is one reason why ♭II6 resolving to V42 is so common.
I know of two examples in the literature where ♭II resolves to vii°7. First, and I think most in line with what you're looking for, is from the opening measures of Saint-Saëns' "Organ" Symphony. Here, the ♭II6 resolves to vii°65:

Another example to consider is from Weber's Overture to Der Freischütz.

There are a few things to notice here:

The Neapolitan (mm. 4–5) is in second inversion (!).
It resolves to a vii°7 chord in third inversion (m. 6).
But most importantly, that vii°42 really just delays the appearance of V7 on the downbeat of the last measure. In other words, I view the A♭ in the next-to-last measure as a suspension from the ♭II64. As such, I hesitate to call that measure a vii°42; in my opinion, the final two measures are V7, we just have a long suspension in the bass.

More common, as you probably already know, is for the Neapolitan to resolve to an applied diminished-seventh chord of the dominant. As one example of many, consider this quick example from the last movement of Mahler 2:

The Neapolitan is on the third beat of the first measure, and it moves through vii°7/V on beat 4.
Comment: @KimFierens The database of a theory professor's brain :-)
Comment: @KimFierens Oh, I see! I make these examples in a program called LilyPond, which I think is much faster (once you learn it) than Finale or Sibelius.
Comment: @KimFierens Full disclosure: LilyPond has a pretty steep learning curve. I strongly recommend the video tutorials at https://www.youtube.com/playlist?list=PLHi8BvxILUV6x9FqEmZiYrEj6VMGmTKjt, which I used when I first learned.
Comment: Thanks for this excellent and well-documented answer!
Comment: Where do you get your music examples from, if I may ask? Some sort of database?
Comment: Yes, I sort of guessed that you knew the music itself from memory. But what I was wondering was how you got the notation so ready at hand. Or are you just a rapid typist in Finale/Sibelius/whatever?
Comment: Thanks. I will definitely look into this LllyPond program, because in Finale it takes "forever" to create even rather simple and brief examples.


Get Authenticated user on many=True serializer Viewset

Question: I'm writing a rest api using Django Rest Framework, I have an endpoint to create objects on POST method and this method is overridden in order to allow bulk adding. However, the object is an "intermediate table" between Pacient and Symptoms and in order to create it I need to provide the pacient object or id and the same for the symptom. I get the Symptom id in the request, so that's not an issue, however the pacient is the authenticated user (who's making the request). Now, how do I edit the create method in the serializer in order to do that?
Here's my view:
class PacienteSintomaViewSet(viewsets.ModelViewSet):
    serializer_class = SintomaPacienteSerializer
    queryset = SintomaPaciente.objects.all()
    permission_classes = (IsAuthenticated, )
    http_method_names = ['post', 'get']

    def create(self, request, *args, **kwargs):
        many = True if isinstance(request.data, list) else False
        serializer = SintomaPacienteSerializer(data=request.data, many=many)
        if serializer.is_valid():
            sintomas_paciente_lista = [SintomaPaciente(**data) for data in serializer.validated_data]
            print(serializer.validated_data)
            SintomaPaciente.objects.bulk_create(sintomas_paciente_lista)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)

And this is my serializer:
class SintomaPacienteSerializer(serializers.ModelSerializer):
    def create(self, validated_data):
        sintoma_paciente = SintomaPaciente.objects.create(
            sintoma_id=self.validated_data['sintoma_id'],
            paciente_id=THIS NEEDS TO BE FILLED,
            data=self.validated_data['data'],
            intensidade=self.validated_data['intensidade'],
        )
        return sintoma_paciente

    class Meta:
        model = SintomaPaciente
        fields = ('id', 'sintoma_id', 'paciente_id', 'intensidade', 'data',
                  'primeiro_dia', 'ativo')

Answer: There is two way.
First one, you can pass your user to serializer inside context, and use it in serializer:
in your view:
def create(self, request, *args, **kwargs):
    many = True if isinstance(request.data, list) else False
    serializer = SintomaPacienteSerializer(data=request.data, many=many,context={'user':request.user})

in your serializer you can access this user with self.context['user']
Second way, you don't need to pass user to serializer again. Also If you already override the create method in your View, you don't need to override create method in serializer. I think it is wrong logically. Anyway, you can use your user when create object in view:
def create(self, request, *args, **kwargs):
    many = True if isinstance(request.data, list) else False
    serializer = SintomaPacienteSerializer(data=request.data, many=many)
    if serializer.is_valid():
        sintomas_paciente_lista = [SintomaPaciente(**data,paciente_id=request.user.id) for data in serializer.validated_data]
        print(serializer.validated_data)
        ....


InvalidCastException when passing a mocked dependency into a function

Question: I am using Rhino Mocks along with nUnit to attempt to test my function IsApprovable() on an object. The function I am testing relies on another object "UserManager" that needs to be passed in. I am attempting to mock an instance of UserManager so I can specify the result of another function GetApproverDependantsList()
My issue is that when I mock the object and pass it into the function I am testing I get the following InvalidCastException:
Unable to cast object of type 'Castle.Proxies.IUserManagerProxye15b431a53ca4190b7ffbdf5e241e2bb' to type 'MyNamespace.Users.UserManager'.
I am new to this so I am not really sure if I am doing things correctly... Here is the sample mocking code I am using:
Dim helper As New BookingManagerHelper()
Dim booking As Booking = GetDummyBooking() 'method to get a booking in suitable state
Dim parameters As Collection(Of Parameter) = GetDummyParameters() 'factory method, as above
Dim mockedUserManager = MockRepository.GenerateMock(Of Users.IUserManager)()

'I have created a dummy function called GetUserCollectionWithDependant() to create the results I need the mocked function to return...
mockedUserManager.Stub(Function(x) x.GetApproverDependantsList(-1)).[Return](GetUserCollectionWithDependant(1))

'It's the line below where I find my exception...
Assert.AreEqual(True, helper.IsApprovable(booking, mockedUserManager, parameters))

The function I am attempting to test looks like the following:
Public Function IsApprovable(ByVal Booking As Booking , ByVal UserManager As Users.UserManager, Optional ByVal Parameters As Collection(Of Parameter) = Nothing) As Boolean
'various logic checks are performed on the objects passed in
End Function

Some things to note:

UserManager implements the interface IUserManager
UserManager contains additional properties and functions that are not defined by the interface
UserManager also inherits from a base class (do I need to override base properties?)

I can post more code if needed. Thanks in advance.
Answer: I am no expert in VB.NET but IsApprovable expects a UserManager instance. The mock is of type IUserManager. Maybe you want to adjust IsApprovable to use a IUserManager instance.


Local Rings, How to prove Z/(P^l)Z is a local ring

Question: please do me a great favor to answer my following question:
Is the ring Z/(P^l)Z a local ring? If it 's the case what is its maximal principal ideal ?
Comment: I m studying p-adic gauss sums and when reading a paper about them I found that those kind of sums are defining in local rings and give the example of Z/(P^l)Z .I looked for the definition of such rings i.e local rings and I found that are rings which posses one maximal ideal ring that is why  I m asking what is the unique maximal ring of Z/(P^l)Z
Comment: You might want to do some reviewing of basic ring theory before looking further into $p$-adic Gauss sums. This particular case is fairly straightforward and a basic exercise.
Comment: Please to gain a time can you indicate me some practical references
Comment: The thing is, that local rings are usually only introduced fairly late in most cases, since most interesting results about them require a bit extra background. So once one gets to the definition, I would usually expect an exercise like this to be fairly trivial, and I am not aware of some text that covers the basics and introduces local rings so early. But to review the basics, take pretty much any textbook on abstract algebra.
Answer: HINT: Maximal ideals of $\mathbb{Z}/p^i\mathbb{Z}$ are in bijection with maximal ideals of $\mathbb{Z}$ containing $p^i\mathbb{Z}$.
But now, a maximal ideal of $\mathbb{Z}$ is generated by a prime, and this contains $p^i\mathbb{Z}$ if and only if...
Comment: Thank you very much Crostul
Comment: Can I deduce that we the Z/(P^l)Z posses just one maximal ideal throug this bijection and that there is no a cocrete expression of it?
Comment: @moksih Oh, come on! The only maximal ideal is obviously $pZ/p^iZ$
Comment: Thank you very much. Excuse me for being too so slowly to deduce evident things.
Comment: Just a last favor, can you indicate me any references where appears the above bijection
Comment: @moksih http://en.wikipedia.org/wiki/Isomorphism_theorem#Second_isomorphism_theorem_2
Comment: Thank you very very ...much.


Limit as $\lim_{x\to 0}\frac{x\cos(1/x)}{x-\sqrt{x}}$

Question: I've been trying to get this limit for hours. Can someone help me, please?
The solution manual says it's 0 but I can't get there. I tried to use $\lim_{h\to0} {h-\cos(h)\over h} = 0$.
$$\lim_{x\to 0}\frac{x\cos(1/x)}{x-\sqrt{x}}.$$
Thank you.
Comment: Just in general, if you have a discontinuity inside of a trig function, check squeeze theorem.
Answer: Divide numerator and denominator by $x$.
$$\frac{x\cos(1/x)}{x-\sqrt x}=\frac{\cos(1/x)}{1-x^{-0.5}}$$
Now see that
$$-1\le\cos(1/x)\le1$$
And apply squeeze theorem.

Remark:  Notice that $\frac{x\cos(1/x)}{x-\sqrt{x}}$ is not defined for $x<0$, so the above limit only makes sense as $x\to0^+$.
Comment: And what is the result ??
Comment: @Fred The one the OP's "solution manual" states.  See that $\frac1{1-x^{-0.5}}\to0$ as $x\to0^+$.
Comment: There must be a simpler way, I never talked about that theorem. (I'm learning it now, but do you know any simpler way?) Thank you though, that's really helpful.
Comment: Oh sorry, the theorem seems simple. Thank you!
Comment: @SadSeven Well, just see that $\cos(1/x)$ is a small number and that $1-x^{-0.5}\to-\infty$.  A small number divided by an arbitrarily large number is even smaller.
Answer:
$$\lim_{x\to 0}\frac{x\cos(1/x)}{x-\sqrt{x}}.$$

Due to the $\sqrt{x}$, clearly $x>0$. Substitute $t = \frac{1}{x}$, then $t \to +\infty$ as $x \to 0^+$ and you have:
$$\lim_{x\to 0}\frac{x\cos\left(\tfrac{1}{x}\right)}{x-\sqrt{x}}
= \lim_{t\to +\infty}\frac{\tfrac{1}{t}\cos\left(t\right)}{\tfrac{1}{t}-\sqrt{\tfrac{1}{t}}}
= \lim_{t\to +\infty}\frac{\cos\left(t\right)}{1-\sqrt{t}}$$
And the limit is clearly $0$ since $-1 \le \cos t \le 1$ and the denominator is unbounded.


HTML binding Angular 4

Question: Boa tarde, Estou precisando de uma ajuda com o Angular 4
tenho o seguinte metodo:
import { Component, OnInit, Input, Output } from '@angular/core';
import { Remedy } from '../remedy/remedy.model'
import { RemedysService } from '../remedys.service'
import { ActivatedRoute } from '@angular/router'
import { Observable } from 'rxjs/Observable'

@Component({
    selector: 'gmr-remedy-details',
    templateUrl: './remedy-details.component.html'
})
export class RemedyDetailsComponent implements OnInit {

    remedy: Remedy

    constructor(private remedysService: RemedysService, private route: ActivatedRoute) { }

    ngOnInit() {
        this.remedysService.remedyByMenuId(this.route.snapshot.params['id'])
            .subscribe(remedy => this.remedy = remedy)
        console.log(`Parametro : ${this.route.snapshot.params['id']}, Remédio ${this.remedy}`)
    }
}

Para ser colocado em um template:

Categoria

{{remedy?.des_category}}

Dosagem

{{remedy?.des_dosage}}

Descrição

{{remedy?.des_description}}

Cadastrar novo remédio

serviço que busca do Web service:
remedyByMenuId(id: string): Observable<Remedy> {
    return this.http.get(`${GMR_API}/api/remedys/remedysMenu/${id}`)
        .map(response => response.json())
        .catch(ErrorHandler.handleError)
}

Obs: a URL funciona pois utilizo para outros serviços e funciona normalmente.
Porém não consigo o Bind para que os valores apareçam no HTML, e verifico no navegador pela ferramenta de debug o objeto com todos os valores do web service estão sendo retornados normalmente a algo que estou fazendo errado ?
Comment: você pode substituir `.subscribe(remedy => this.remedy = remedy)` por `.subscribe(remedy => { this.remedy = remedy; console.log(this.remedy); })` e me dizer o que é printado no console?
Comment: @mercador tem um log na função init ele volta undefined pq eu pesquisei o remedy e setado antes da execução do on init então vem undefined porém dess jeito q vc colocou ainda não testei vou testar amanhã e posto aqui valeu !
Comment: `undefined` no `ngOnInit` é esperado pois sua requisição pode demorar a retornar algo. Dentro do callback de success no `subscribe` deve vir alguma coisa.
Comment: Opa bom dia tudo bem então o retorno foi um Objeto : log subscribe: [object Object]
Comment: acredito então que para toda referência de `remedy` no seu template, se você usar `*ngIf` deve resolver.
Comment: será ? mas como eu faria no template *ngIf="remedy" ?
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/71811/discussion-between-mercador-and-felipe-sangiorge).
Answer: Como estava:
ngOnInit() {
        this.remedysService.remedyByMenuId(this.route.snapshot.params['id'])
            .subscribe(remedy => this.remedy = remedy)
        console.log(`Parametro : ${this.route.snapshot.params['id']}, Remédio ${this.remedy}`)
    }
}

Resolução :
  this.remedysService.remedyByMenuId(this.route.snapshot.params['id'])
    .subscribe(response => {
          this.remedy = {des_name : response[0].des_name}
          console.log(this.remedy)
    })

A verdade é que o retorno estava vindo como array, depois de deixar essa parte de lado aprofundar meus conhecimentos e voltar a analizar percebi que retornava em forma de array no indice [0] ou seja bastava pegar os retornos desse indice popular em um objeto e fazer o bind desse objeto.

HTML binding Angular 4


Colors in Emacs shell prompt

Question: Is it possible to use colors in the Emacs shell prompt (the prompt itself, not the rest of the shell screen) with the bash PS1 variable?  I believe I have the syntax correct (e.g., PS1='[\u@\h \[\e[0;31m\]\W\[\e[m\]]\$ ' - it works in term or ansi-term), but it seems like Emacs is applying the comint-highlight-prompt face.  I can set that to some color, and it works, but I want to be able to set individual parts of the prompt to different colors.  I prefer using shell over term or ansi-term, so I'd rather not switch.
Thanks.
Answer: Figured it out:  The comint-highlight-prompt face was set to inherit from minibuffer-prompt, which was setting the :weight, :foreground and :background.  Removing the inheritance prevented the colors set in PS1 from being overridden by the comint-highlight-prompt face.  Added this to my .emacs file.
(set-face-attribute 'comint-highlight-prompt nil
                    :inherit nil)

Also, M-x customize-group <ret> font-lock-faces was helpful in figuring this out.
Comment: That will not work in Ubuntu 16.04 that uses Emacs 24.5 due to Emacs bug https://debbugs.gnu.org/cgi/bugreport.cgi?bug=20084 that has already been fixed on git://git.sv.gnu.org/emacs.git at commit 792d44b3c31d2a682607ab8b79ae7d26b7402f41. To make your solution work, use https://www.gnu.org/software/emacs/manual/html_node/elisp/Hooks-for-Loading.html with "comint" to fix "comint-snapshot-last-prompt" and "comint-output-filter" and with "font-lock" to add "font-lock--remove-face-from-text-property".
Answer: I would recommend not to change the face globally (since there are many comint users besides shell mode) but in a buffer specific manner by setting a mode hook:
(add-hook 'shell-mode-hook
      (lambda ()
        (face-remap-set-base 'comint-highlight-prompt :inherit nil)))

Answer: I use that to change the terminal color and the information in mac, maybe can help:
Cyan="$(tput setaf 6)"
NC="$(tput sgr0)" # No Color
export PS1="$Cyan.Where-> \w\n\\$\[$NC\]"

Comment: Thanks, but it still gets set to the comint-highlight-prompt face.  I have tried doing `(set-face-foreground 'comint-highlight-prompt nil)` in my .emacs file, but the prompt still gets set to all cyan.

Colors in Emacs shell prompt


Trace of a matrix

Question: What is the trace of $e^{A}$ where A is a $4 \times4$ matrix
$$\begin{bmatrix}0 & 0 & 0 & t\\
 0 & 0 &-t & 0\\
 0 & t & 0 & 0\\
-t & 0 & 0 & 0 \end{bmatrix}$$
where $t=\dfrac{\pi}{4}$.
Comment: The definition of the exponential of a matrix is:
$$
e^A=\sum_{k=0}^\infty\frac{1}{k!}A^k.
$$
Does this assist your effort? What to the powers of $A$ look like?
Comment: please make sure I got the edits correct.
Answer: Looking at the basis $(e_1,e_4,-e_2,e_3)$, $A$ is similar to a block-diagonal matrix made of two identical blocks
$$
B=\pmatrix{0&t\\-t&0}.
$$
Note that $A^n$ is similar to the block-diagonal matrix made of two copies of $B^n$, so $\mbox{tr} \,A^n=2\,\mbox{tr}\,B^n$ for every $n\in \mathbb{N}$. Then an easy induction shows that
$$
B^{2n}=\pmatrix{(-1)^nt^{2n}&0\\ 0&(-1)^nt^{2n}}\qquad B^{2n+1}=\pmatrix{0&(-1)^nt^{2n+1}\\ (-1)^{n+1}t^{2n+1}&0}.
$$
Therefore
$$
\mbox{tr}\,e^A=\mbox{tr}\sum_{n=0}^{+\infty}
\frac{1}{n!}A^n=\sum_{n=0}^{+\infty}
\frac{1}{n!}\mbox{tr}A^n=\sum_{n=0}^{+\infty}
\frac{2}{n!}\mbox{tr}B^n=4\sum_{n=0}^{+\infty}
\frac{(-1)^nt^{2n}}{(2n)!}=4\cos t=2\sqrt{2}.$$
Comment: Very nice breakdown! +1
Comment: @Amzoti Thanks. I did not have the patience to write down $16$ coefficients.
Answer: By definition:
$$ Tr(e^A)=\sum_{k=1}^4 e^{\lambda_k},$$
where, $\lambda_k$ are eigenvalues of $A$, which solve
$$
\det(A-\lambda I)=\lambda^4+2t^2\lambda^2+t^4=(\lambda^2+t^2)^2=0.
$$
So,
$$ Tr(e^A)=2(e^{it}+e^{-it})=4\cos t|_{\pi/4}=2\sqrt{2}.$$
Btw,
$$ \det(e^A)=\prod_{k=1}^4 e^{\lambda_k}=e^{\sum_{k=1}^4\lambda_k}=e^{Tr(A)}=e^0=1.$$

Trace of a matrix


Jquery Mouse Over effect.. going "out" before it should

Question: So I created a simple menu for a small project I have.  When people mouse in and out of the menu on IE6 or IE7 the menu will drop down.. but it will go back up if you move the mouse slowly downwards.
Does anyone know how to prevent this behaviour.. it seems like it thinks its mousing out.. even though it hasnt yet..
the url: http://vasoshield.xcsit.com/index.html
the html structure:

        Request Info

Ordering

Contact Us

        News

Press Release

        Product

Overview

Uses

jquery
$(document).ready(function() {
$('#mainNav ul li').hover(
    function() {
        $(this).find('ul').slideDown(100);
    },
    function () {
        $(this).find('ul').slideUp(50);
    }
);

});
the css:
    #mainNav { padding-top: 175px;  }
#mainNav ul { border-bottom: 4px solid #369790; width: 765px; height: 33px;}
#mainNav li a { text-align: center; display: block; height: 24px; font-size: 12px; text-transform: uppercase; padding-top: 9px; line-height: 25px; text-decoration: none; color: black; font-weight: bold;}
#mainNav ul li a:hover { font-weight: bold; }
#mainNav li {  position: relative; float: right; margin-left: 15px; }

#mainNav ul ul { position: absolute; display: none; border: none; width: auto; height: auto; top: 33px; z-index: 999; border-top: 4px solid #369790;}
#mainNav ul ul li a { background: none; height: auto; padding: 0; margin: 0; line-height: 33px; color: #a0a0a0; }
#mainNav ul ul li a:hover { background-color: #939598; color: #616264; }
#mainNav li li { float: none; height: auto; margin: 0; background-color: #c9cacc; border-bottom: 2px solid #dcddde;}

#mainNav li.productLink a { width: 151px; background: url(../images/long_nav2.gif) no-repeat;}
#mainNav li.newsLink a { width: 90px; background: url(../images/short_nav2.gif) no-repeat; }
#mainNav li.requestInfoLink a { width: 151px; background: url(../images/long_nav2.gif) no-repeat; }
#mainNav li.productLink ul { width: 152px; }
#mainNav li.newsLink ul { width: 90px;  }
#mainNav li.requestInfoLink ul { width: 151px;  }
#mainNav li.newsLink ul li a { line-height: 1.6em; height: 40px; padding-top: 5px; }
#mainNav li.productLink li a { background: none;}
#mainNav li.newsLink li a { background: none;}
#mainNav li.requestInfoLink li a { background: none;}

Answer: Note that the $('#mainNav ul li') expression matches inner li elements. Try using $('#mainNav > ul > li') for the main expression.
Also, you can simulate the border in li elements by changing the background colors and padding to:
#mainNav ul ul li a { background-color: #c9cacc; height: auto; padding: 0; margin: 0; line-height: 33px; color: #a0a0a0; }
#mainNav li li { float: none; height: auto; margin: 0; background-color: #dcddde; padding-bottom: 2px; }

This should solve your problems in IE.
Comment: Ok, that's great it worked! IE has an awful box model, so borders can be a problem when using hover events.
Answer: Try mouseenter and mouseleave instead of hover.  Mouse enter and leave also cover child elements. See the example here.
You could also move the menus up 1 or 2 pixels.  I only checked quickly, but in IE7 and 6 it looks like there is an extra pixel between the two elements (a and UL) that causes un-hover to fire.
Answer: Have you tried using mouseenter and mouseleave?
$(document).ready(function() {
  $('#mainNav ul li').mouseenter(function() {
    $(this).find('ul').slideDown(100);
    }).mouseleave(function () {
      $(this).find('ul').slideUp(50);
    });
);

Answer: speculating here.
IE treats border,padding and margin as gaps. your ul > li has border-bottom:2px;
that means u have a gap betweent ur li's. when u enter the gap, it fires mouseout event.
trying remove the borders to see if it works.


how can I develop my top-line melody writing style?

Question: I'll try to use definitions from writing speech, in order to explain my question.
In order to write an essay, you need to know the alphabet, some vocabulary, grammar, syntax and combine the words in different ways.
Following the same pattern, in order to write (top-line) music you need to read the notes, phrasing, music theory and harmony.
If someone wants to move his top-line writing on further than some logical sequence of notes and phrases, what is the factor that distinguishes the writing style of one top-line writer from another?
And lastly, how could someone develop his writing style or his "voice" in music?
Comment: My guesses so far (just guesses, not solid enough for an answer): Listen **a lot** and think about what you're hearing. Practice writing **a lot** and think about what you're writing. And then relax and see what comes out of you and be open to whatever your heart speaks. Don't pick your style or genre, look for it deep inside you and allow it to come out.
Comment: "in order to write (top-line) music you need to read the notes, (some musical phrases?), music theory and harmony." No. Those things are only about *writing the music down*. First you have to *invent* something that is worth writing down, and there are no *rules* about how to do that. In fact, attempting to carefully follow a set of "rules" often leads to something that is boringly predictable, even if it is "theoretically correct". You can be the world's expert on associating modal scale patterns with harmonic progressions but still be totally incapable of actually *doing* jazz improvisation!
Comment: Problem is, you're looking for something that right now doesn't exist. You have not developed a style, so you can't recognise one! Apart from that, why should there be one style from one compser? The best is to write stuff with no pressure, and the best of it will rise above the dross. You may well then see a sort of style developing, but then maybe you'll be thinking 'this is all samey'. So then you change things. That's how it works. There are no magic formulae.
Comment: @ToddWilcox thank you so much for your asnwer. Though I am a little confused here. What should I "see" when I hear a song or practice writing. Where should I focus my thought? In note succession, In scale use...?
Comment: I'm a 100% with you on that. I also believe that we have a lot of styles as composers. But unfortunately the industry demands "specialization", in order a songwriter to be defined as an artist.
Comment: @alephzero I feel that you refer to a potential "gift" or talent, without which one cannot write (or deal with) music. I agree that you have to invent a story in order to write a novel, but what about the personal style? Is it something that we come with it by default, or is it something that can be altered or further developed...?
Comment: just write any rhythm and pitches and see if you like it. There isn't any music theory for it, even the interval theory doesn't help much.
Answer: Listen to other music. This is perhaps the most important piece of advice full stop. In order to develop your OWN style, you must listen to many different types of styles by different artists as this allows you to 'blend' other styles. This is what all successful composers and artists have done, for example the Beetles were influenced in their later years by Ravi Shankar, a sitar player in the style of classical Indian - very different from their usual.
Listen to other's music, both for enjoyment and analytically as well as composing your own as much as possible; from here on, your style will develop.
Answer: [Aside: Assuming by "top-line" you mean melody, there really is no such thing as a top-line-only writer. The melody is pretty much always in context.]
As to distinguishing the melodic style of writer from another,  there is no single factor, it's a blend.  Beyond the formal "vocabulary" elements you've mentioned, you can look at melodies through a variety of lenses:
- Genre and cultural background or inspirations  (i.e. a country love ballad or a morning raga?)
- The artist's creative process and self-imposed constraints (e.g., the "one-note guitar solo" on Neil Young's Down by the River)
- Instruments used while composing, and in performance
- Harmony and arrangement elements
- Lyrics and prosody, or the "story" inspiring the music (i.e. this is a sad song about my dead dog, or an angry political screed?)
So in addition to the excellent advice provided in previous replies, especially the "write alot" point, I'd add: clarify where you stand on the above, and then take the resulting constraints as a means of generating melodic ideas.
Now I'm going to go pick up my clarinet to write a morning raga about my pickup truck, and see where it takes me...
Comment: (My understanding: topline refers to melody and lyrics, generally composed over an already-given accompaniment to make a pop song. http://blog.sonicbids.com/whats-the-difference-between-a-songwriter-and-a-topline-writer )
Answer: This is definitely a good question.
One thing to note is the principle of prosody and how it applies here. If you're writing top line melodies, I'm assuming there's an instrumental track already laid out? If so, that's going to have a huge impact on what kind of melody you ought to write.
When a song is harmonically complex, with frequent chord changes, you'll very likely want to write a more static melody (Not moving up and down that much at all). (Lots of John Lennon songs are like this... I Am The Walrus, etc.)
Also, melodic lines should be written with language in mind if melody is coming first, just like if words are coming first you should keep the rhythm and tones of the future melody in mind. This overall cohesion and balance is prosody on multiple levels and dimensions. If you find this helpful check out my post on an expanded understanding of prosody.
So in that sense, if you feel like you're struggling with writing melodies, it may have at least something to do with the
Like any other kind of creative endeavor; you start by stumbling around, and you practice, you copy things you like, since what you like is already what's resonant with your own creativity, and your own style will emerge.

Additionally, you could also just make a conscious decision as to
what kind of melodies you want to write and sort of just take charge of your development in a purposeful way.

Lots of interesting possibilities though.


Foundation 6.2.4 modal

Question: I try to implement a modal with foundation 6.2.4, but it's not working :s
The modal is hide, but i can't display it.
The code :
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>RIA2-Projet</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
    <link rel="stylesheet" href="assets/foundation-icons/foundation-icons.css" />

Awesome. I Have It.

Your couch. It is mine.

I'm a cool paragraph that lives inside of an even cooler modal. Wins!

    <button class="close-button" data-close aria-label="Close modal" type="button">
        ×
    </button>

Click me for a modal

Edit :
If in my app.js file i put :
$(document).foundation();
$( document ).ready(function() {
    var popup = new Foundation.Reveal($('#exampleModal1'));
});

It's work, but it suppose to be working without it right?
Answer: Some of the features / plugins of Foundation require initialisation to work: https://foundation.zurb.com/sites/docs/javascript.html#initializing
Your code is fine, but the $(document).foundation(); is required to run any of the Foundation plugins that use JavaScript / jQuery.
You could also initialise just the modals with:
$('reveal').foundation();
Here is a fiddle with it working (using the minimum file includes): https://jsfiddle.net/gbyobLt5/

Foundation 6.2.4 modal


LASSO: Difference in selecting tuning parameter for variable selection and prediction purposes

Question: I'm reading Kirkland et al. "LASSO Tuning Parameter Selection" (2015) regarding methods for selecting the tuning Parameter in LASSO regressions. I'm a bit confused about the following Statements.
"This paper attempts to provide an overview of methods which are available
to select the value of the tuning parameter for either prediction or variable selection purposes"
Why the tuning parameter should differ between the two purposes ?
I mean if we can select the "true" model, this should also result in the best forecast, or is my intuition wrong ?
Comment: Your intuition is reasonable, but turns out not to be quite right. Generally you want a smaller penalty for prediction accuracy, as it is a little better to err on the side of making the model too big. This manifests in the AIC/BIC debate: AIC is optimal for a certain type of prediction error but is not even consistent for variable selection.
Comment: If you are going to select the wrong predictors, would you rather select a set which is too big (has False Positives) or too small (has False Negatives)? If your goal is prediction, having a few FPs is not too big of a deal, but a FN is a disaster. Consequently, the optimal thing to choose a penalty which will have a few FPs but no FNs; this leads to inconsistent selection. On the other hand, if you value variable selection then you can treat FPs and FNs more equally; this leads to suboptimal prediction accuracy (because when you get an FN it is really bad) but you get consistent selection.
Comment: I'm still not getting the right Intuition. May you can extend or comment or reffer to some sources, that explain the difference
Comment: You may have erred in seeking parsimony, which is more often than not the enemy of predictive discrimination.  But even worse, you did not validate the stability of the set of features selected by _lasso_.  Do a little simulation or bootstrapping to see if the lasso agrees with itself in the list of features selected.  If it doesn't you are just wasting your time and losing all interpretation ability.
Comment: Thanks guy, that helped a lot for intuition. Do you have maybe some sources or academic literature to that ? Btw: I can just vote your comment up
Answer: For prediction, we are interested in the best outcome and want to include as much information as possible in the model to explain the response, but still without over fitting (don't capture the noise) as we want our model to generalize well to new data. Generally, lower values of the LASSO tuning parameter are needed for prediction. When a group of correlated variables are present, LASSO will tend to select the best predictor in the group and discard the rest. The true set of variables are usually included in the best predictive model with high probability. Other variables will be included to maximize the predictive power of the model and will likely have small parameter estimates but won't be shrunk completely to zero. The best predictive model will have the lowest mean squared error (MSE).
Variable selection is a much harder problem than prediction. For variable selection we want to understand the relationships between variables and explain the importance of each variable. This would in fact be recovering the true model. A higher value of the tuning parameter is necessary in order to shrink more parameters to zero. LASSO only does well for variable selection under some rather strong assumptions regarding the size of the parameters and the correlations between variables (see my answer here). Without these assumptions, the bias is usually very high in the models. In that case, a two stage procedure like relaxed LASSO or adaptive LASSO are better suited.
There are models with the oracle property, i.e. they are consistent for prediction and variable selection, containing the correct subset of variables only and having lowest MSE. Think of it as fitting a least squares model where the set of true predictor variables known. Adaptive LASSO has the oracle property (see my answer here), as do some shrinkage methods with concave penalty functions like MCP and SCAD (see my answer here). Hope that clarifies the issue for you.


Cannot change status bar text color on large screen iPhone

Question: I'm working on an old Object C app using tabBarController. Because setStatusBarStyle that was used to set status bar text to white is deprecated in iOS 9 so I deleted it and changed the .plist file like:

I also changed Status Bar Style in Deployment Info to 'Light'.
It worked fine with iPhone SE and 5 (checked with iOS 9.3 and 11) but for some reason didn't work with larger devices such as iPhone 6 or 7. Status bar and its content (time, battery etc.) are both black.
I tried preferredStatusBarStyle as suggested and some other instructions but nothing worked perfectly for me.
Comment: Whats your project deployment target?
Comment: If your deployment target is > 9 then use - (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
use this in every view controller class(.m file).
Answer: Your answer is here:
This code use every UIViewController
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

Answer: Try this code:
[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

use - (void)viewDidLoad
or
- (void)viewWillAppear:(BOOL)animated
- (void)viewWillDisappear:(BOOL)animated


Determine if number of permutations is odd or even

Question: I am facing problem in this question.

Let $X$ be the total number of $n$-permutations that have exactly
$k$-inversions. An inversion is defined as a pair of entries $(i,j)$ such
that $i<j$ but $p(i) > p(j)$. Determine whether $X$ is odd or even.

Now, if $k$ is $0$, then $X$ is $1$ so it is odd. If $k$ is $1$, then $X$ will have just the opposite parity of $n$. But I don't know how to determine this for higher values of $k$. There isn't any explicit formula for the higher values either except for $k=2$ and $3$. I am stuck and don't know how to continue.
Comment: Probably exploiting the recursion. These numbers are arranged in the so called Mahonian triangle. See, for example: https://math.stackexchange.com/questions/2008758/showing-mahonian-triangle-numbers-related-to-inversion-probability/
Comment: The answer seems quite complicated to me. The OEIS doesn't give any non-recursive description (http://oeis.org/A186518). Where did this problem come from?
Comment: I have learned that this is a question from an ongoing coding competition (https://math.stackexchange.com/questions/3854289/how-to-find-mahonian-number-under-modulo-2, https://www.codechef.com/OCT20A/problems/INVSMOD2) so I'm deleting my answer until the competition is over.
Answer: This isn't a complete answer. If $\ell(\pi)$ denotes the number of inversions of a permutation $\pi$ then
$$\sum_{\pi \in S_n} q^{\ell(\pi)} = \prod_{i=1}^n \left( q^{i-1} + \dots + q + 1 \right) = \prod_{i=1}^n \frac{q^i - 1}{q - 1}.$$
(This is the $q$-factorial $[n]_q!$; it's a nice exercise to prove this.) Working $\bmod 2$ we have that if $i = 2^k o$ where $o$ is odd then $q^i - 1 \equiv (q^o - 1)^{2^k} \bmod 2$ and applying this to every factor in the product gives
$$\prod_{i=1}^n \frac{q^i - 1}{q - 1} \equiv \prod_{1 \le 2^k o \le n, o \equiv 1 \bmod 2} \frac{(q^o - 1)^{2^k}}{q - 1} \bmod 2$$
This is admittedly still quite complicated. The number of times $o = 1$ appears in the numerator of the product is $1 + 2 + 2^2 + \dots + 2^k$ where $2^k$ is the largest power of $2$ less than or equal to $n$. In particular it is at least $n$, with equality iff $n = 2^k - 1$. That means the factors of $q - 1$ in the numerator successfully absorb the factors of $q - 1$ in the denominator, giving
$$[n]_q! \equiv (q - 1)^{2^{\lfloor \log_2 n \rfloor + 1} - 1 - n} \prod_{o \equiv 1 \bmod 2, o \ge 3} (q^o - 1)^{2^{\lfloor \log_2 \frac{n}{o} \rfloor + 1} - 1} \bmod 2.$$
In general we have
$$(x - 1)^{2^k - 1} \equiv \frac{(x - 1)^{2^k}}{x - 1} \equiv \frac{x^{2^k} - 1}{x - 1} \equiv x^{2^k - 1} + \dots + x + 1 \bmod 2$$
which gives
$$[n]_q! \equiv (q - 1)^{2^{\lfloor \log_2 n \rfloor + 1} - 1 - n} \prod_{o \equiv 1 \bmod 2, o \ge 3} \left( q^{\left( 2^{\lfloor \log_2 \frac{n}{o} \rfloor +1} - 1 \right) o} + \dots + q^o + 1 \right) \bmod 2.$$
As complicated as this looks I'm not sure it's possible to do much better, given this picture from the OEIS (this sequence is A186518) of what the Mahonian triangle $\bmod 2$ looks like (although I don't quite understand how to read it; the Mahonian triangle should have rows increasing in length quaratically...):

Let's see what our identity says explicitly for the small-but-not-too-small example $n = 7 = 2^3 - 1$. The first factor vanishes and we get
$$[7]_q! \equiv (q^9 + q^6 + q^3 + 1)(q^5 + 1)(q^7 + 1) \bmod 2$$
(the original product had $7$ factors with $21$ terms among them; this product has $3$ factors with $8$ terms among them). This expands out to
$$\begin{align} [7]_q! &\equiv (q^9 + q^6 + q^3 + 1)(q^{12} + q^7 + q^5 + 1) \\
 & \equiv (q^{21} + q^{18} + q^{15} + q^{12}) + (q^{16} + q^{13} + q^{10} + q^7) + (q^{14} + q^{11} + q^8 + q^5) + (q^9 + q^6 + q^3 + 1) \bmod 2 \end{align}$$
and in particular there is no further cancellation (this surprises me a little; I don't know whether this generalizes). So these exponents tell us which values of $k$ have the property that the number of permutations in $S_7$ with $k$ inversions is odd. Note that we really only have to compute half of these numbers because of the reflection symmetry.


Is there an "efficient" algorithm to compute hyperexponentation?

Question: Preface: understand that this should all be modulo some fixed $m$; otherwise the numbers become so ridiculously large that the question makes no sense. That said, I'll leave $m$ off the notation to make it more clear.

Hyperexponentation can be defined recursively as follows:
$a\uparrow_n 0=1$
$a\uparrow_0 b=ab$
$a\uparrow_{n+1}b+1 = a\uparrow_n(a\uparrow_{n+1}b)$
For small $n$ you recover familiar operations: $a\uparrow_1 b=a^b$, and $a\uparrow_2 b = a^{a^{a^{\cdots a}}}$ (repeated $b$ times).
Computation is challenging. Since $a\uparrow_{n+1}b$ tends to be "quite large," computing $a\uparrow_{n+1}b+1$ is only plausible if there is an "efficient algorithm" for $\uparrow_n$.
There is such an algorithm for $a\uparrow_1b$ (exponentiation), which runs essentially in logarithmic time in $b$, which follows essentially from the fact that $a\uparrow_1 2b=(a\uparrow_1b)\uparrow_1 2$.
However, I don't see an obvious equivalent, even for $\uparrow_2$ -- while the iterative nature seems like it should work out, it doesn't seem true that $a\uparrow_2 (2b) = (a\uparrow_2 (b)) \uparrow_2 2$, or any variation of the right I can think of.
Is there a way to compute this more efficiently?
Note there may be a connection to the Ackermann function, where (at least according to Wikipedia), $A(m, n)=2\uparrow_{m-2}(n+3) - 3$.
Comment: [Here's](https://math.stackexchange.com/questions/829351/efficient-algorithm-for-calculating-the-tetration-of-two-numbers-mod-n) a similar (unanswered) question regarding specifically tetration.
Comment: @Mark That's unfortunate ...
Answer: For modular arithmetic:

A modification of Euler's totient theorem can be given as

When $b>\log_2(p)$ we have
$$a^b\equiv a^{(b\bmod c)+c}\pmod p\tag{$\star$}$$
where $c=\varphi(p/\gcd(a^{\lfloor\log_2(p)\rfloor},p))$ and $\varphi$ is Euler's totient function.

which allows us to repeatedly push $\bmod$ into the exponent. This terminates when we reach either $p=1,\gcd(a^p,p)=p,$ or we've reached the end the power tower (or something we can directly compute).
After that, we can work our way down with modular exponentiation by squaring, as you have noted.
Try it online!
Example:
$818023620212985786400\uparrow\uparrow442883135576504326053\pmod{1158210822627198136417}$
$$a=818023620212985786400\\\begin{array}{c|c|c}p&\gcd(a^{\lfloor\log_2(p)\rfloor},p)&\varphi(p/\gcd)\\\hline1158210822627198136417&1&1158210822627198136416\\1158210822627198136416&32&24118439168417024424\\24118439168417024424&8&1676147829304314240\\1676147829304314240&640&1472026782156480\\1472026782156480&320&2787929510040\\2787929510040&40&46196895888\\46196895888&16&1437004800\\1437004800&25600&29160\\29160&40&486\\486&2&162\\162&2&54\\54&2&18\\18&2&6\\6&2&2\end{array}$$
Since $\gcd(a^1,2)=2$, we stop here. Now working back:
$$\begin{array}{c|c|c}p&(b\bmod c)+c&a^{(b\bmod c)+c}\bmod p\\\hline2&-&0\\6&2&1\\18&7&10\\54&28&10\\162&64&10\\486&172&172\\29160&658&18640\\1437004800&47800&260300800\\46196895888&1697305600&32572251856\\2787929510040&78769147744&910022074840\\1472026782156480&3697951584880&903930403260160\\1676147829304314240&2375957185416640&1215567107351528320\\24118439168417024424&2891714936655842560&14632068328029956416\\1158210822627198136416&38750507496446980840&373675920273457955680\\1158210822627198136417&1531886742900656092096&105094019098433015730\end{array}$$
Hence the remainder is $105094019098433015730$.
In the case of tetration, this directly gives us a method to compute it's last digits. In the case of higher hyperoperators, we can use the same strategy, working out a lower bound of the tetration height and then checking if the remainder is uniquely determined.

$(\star)$ This follows from a combination of the Chinese remainder theorem and Euler's totient theorem. $a^p$ is computed using modular exponentiation by repeated squaring as you have noted. The $\gcd$ is computed with the Euclidean algorithm. $\varphi$ is computed by iteratively searching for prime factors and be sped up using faster factorization algorithms.

For non-modular arithmetic:

There is no such algorithm possible since there are no nice relationships for $a\uparrow^nb$ for any $n\ge2$.
That problem aside, this isn't even reasonable to consider for any $a,b\ge2$ because the results quickly grow to a size that will make arithmetic on them slow, unless one chooses to go for a rough approximation.
This latter issue, however, can be circumvented if $0<a<e^{1/e}$ for tetration, where it converges. When $a>e^{-e}$ is in this range, then we may approximate it with
$$a\uparrow^2b\simeq q+[(a\uparrow^2n)-q]\ln(q)^{b-n}$$
for large $b$ and $q=a^q$. As $n\to\infty$ this approximation improves but relies on a large amount of precision. This can be avoided by using Aitken's delta squared acceleration method to make it converge faster. When $a<e^{-e}$, the same approach can be taken, but by considering solutions to $q=a^{a^q}$.
Of course, the same approach cannot be used for higher hyperoperations, since they require continuous lower hyperoperations and there is no agreed upon extension of tetration to non-integer heights.
Comment: See note at the top of the question; this was pertaining to going modulo a fixed m. Otherwise of course it grows so quickly the notion of efficiency is laughable, as you say.
Comment: Ah okay @RichardRast


Does a Galois extension always have the same order over the field from which it is extended for which polynomial it is a splitting field for?

Question: Does a Galois extension always have the same order over the field from which it is extended for which polynomial it is a splitting field for?
My example is the extension $\mathbb{Q}(\sqrt2,\sqrt3,\sqrt5)/\mathbb{Q}$
[let $L = \mathbb{Q}(\sqrt2,\sqrt3,\sqrt5)$]
Using the tower law and basic field extensions I was able to find that $[L:\mathbb{Q}] = 8$
However I know that L is the splitting field for the degree 6 polynomial $(x^2-2)(x^2-3)(x^2-5)$
I know it is Galois since $[L:\mathbb{Q}] = \text{Card}(\text{Aut}(L/\mathbb{Q}))= 8$, and also because it is the splitting field for a separable polynomial
I am stuck here, how is $[L:\mathbb{Q}]$ 8 but L the splitting field for a polynomial of degree 6 contained in $\mathbb{Q}[X]$, where am I fundamentally misunderstanding Galois theory?
P.S. I am doing an undergraduate course in Galois theory so my knowledge on the subject is evidently undeveloped.
Comment: Not sure what you are asking, but maybe this is relevant:  Consider $x^3-2$ over $\mathbb Q$.  The splitting field for that has degree $6$ over the rationals (easy exercise).
Comment: I'm finding the title a little hard to parse
Comment: Oh yes, that makes sense. Thanks a lot :)
Answer: The polynomial $(x^2-2)(x^2-3)(x^2-5)$ is clearly reducible over $\Bbb Q$, so it is not a minimal polynomial of (any of) the roots. We can't then claim $[L:\Bbb Q]=\text{degree of polynomial}$ despite the fact that $L$ is the splitting field for this polynomial. Indeed, all roots have degree $2$ over $\Bbb Q$.
Another place a confusion like this can arise: the Galois group acts transitively on the roots of irreducible polynomials,  but not necessarily over reducible ones.
Comment: Thanks a lot, your answer has helped me a lot, sorry for the confusing title :)
Comment: @MaxwellHolmes You're welcome :)


Node is not created, but nid is returned

Question: I have this code in my module.
  $node = new stdClass();
  $node->title = "YOUR TITLE";
  $node->type = "page";
  node_object_prepare($node);

  $node->language = 'it';
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;

  $node = node_submit($node);
  node_save($node);

  return "Nodo 222: " . $node->nid;

When I execute this code, it returns "Nodo 222: XXX," where XXX is an integer. If I execute it another time, I get XXX+1. When I try to load node/XXX or node/XXX+1, Drupal give me a Page not found error.
I have seen the "node" table in MySQL (via PHPMyAdmin), and nids XXX and XXX+1 are not present. When I create a page via node/add/page, the new nid is XXX+2 and it is saved in the "node" table too.
I have some modules installed (commerce, rules, logintoboggan and others), but this is the first time that I see this strange behavior.
So, where is my error?
Comment: Have you tried `$node->is_new = TRUE;`? Is there anything in the logs?
Comment: I dont see any issues with your code, try with `$node->body['it'][0]['value']   = 'Body goes here';` http://bit.ly/13iisqB
Answer: Hope this will help you,
In Drupal 7, The $node object you pass to node_save() wouldn't get it's nid member populated unless the node has been successfully saved to the node table in the database.
The auto-increment ID actually comes from the database table so if the $node object has a nid, you can pretty much guarantee the record has been successfully inserted into the table.
Im just guessing check for "node" table paging.
Clear drupal cache and check again.
I have used the below code and it is working fine for me, you can refer this.

  $node = new stdClass();
  $node->type = "page";
  node_object_prepare($node);
  $node->title = 'test node';
  $node->language = 'it';
  // Set node body details
  $node->body[LANGUAGE_NONE]['0']['value'] = 'test body';
  $node->body[LANGUAGE_NONE][0]['summary'] = text_summary('test body');
  $node->body[LANGUAGE_NONE][0]['format'] = 'filtered_html';
  //.. other fields goes here
  $node->uid = 1;
  $node->status = 1;
  $node->promote = 0;
  $node->comment = 1;
  if ($node = node_submit($node)) {
    node_save($node);
    drupal_set_message('NODE : ' .$node->nid);
  }

Answer: The error in the code shown in the question is that it's setting $node->nid, but not $node->is_new. For node_save(), the node is an existing node that needs to be updated. In fact, the function contains the following code.
// Load the stored entity, if any.
if (!empty($node->nid) && !isset($node->original)) {
  $node->original = entity_load_unchanged('node', $node->nid);
}
field_attach_presave('node', $node);
global $user;

// Determine if we will be inserting a new node.
if (!isset($node->is_new)) {
  $node->is_new = empty($node->nid);
}

// Save the node and node revision.
if ($node->is_new) {

  // For new nodes, save new records for both the node itself and the node
  // revision.
  drupal_write_record('node', $node);
  _node_save_revision($node, $user->uid);
  $op = 'insert';
}
else {
  // For existing nodes, update the node record which matches the value of
  // $node->nid.
  drupal_write_record('node', $node, 'nid');

  // …
}

It tries to update a database record that doesn't find, if there aren't nodes with that node ID, and it doesn't save anything. That's why you don't find a node with that node ID, in the table used for the nodes.


Paired t test: check normality with residuals or paired differences (or both)?

Question: One of the assumptions of the paired t test is that the underlying data is normally distributed. I've read either the paired differences should be normally distributed, or, that the residuals should be normally distributed (which I thought was the case for ANOVAs / regressions).
I've also read that the residuals in this case ARE the paired differences (link), or that the residuals for a paired t test are the paired differences for each pair minus the mean difference overall (link).
So, is there one simple answer to my question: when checking the assumption of normally distributed data for a paired t test, should you be checking the paired differences, or residuals?
Answer: The paired differences.
A paired t-test is the same as a one-sample t-test on the differences, so the assumption is that the differences are normally distributed. The residuals are simply the differences minus the mean difference.
<code>n = 10
x = rnorm(n)
y = x + 1 + rnorm(n, 0, 1)
t.test(x, y, paired=T)
# Paired t-test
#
# data:  x and y
# t = -3.0863, df = 9, p-value = 0.01301
# alternative hypothesis: true difference in means is not equal to 0
# 95 percent confidence interval:
#   -1.9138020 -0.2948852
# sample estimates:
#   mean of the differences
# -1.104344

d = y - x
t.test(d)
# One Sample t-test
#
# data:  d
# t = 3.0863, df = 9, p-value = 0.01301
# alternative hypothesis: true mean is not equal to 0
# 95 percent confidence interval:
#   0.2948852 1.9138020
# sample estimates:
#   mean of x
# 1.104344
</code>
Comment: +1 and let me emphasize that a paired t-test is a one-sample test.


Add column to SQL Server database when year changes

Question: I am developing a small project as an hobby and came to a dead end. I am using Visual Studio and SQL Server Management Studio.
I use Entity Framework model to be able to add data entries to a table with 4 columns. Two of those are supposed to log data entry taking place in 2017 like this:
<code>if (CheckBoxBulb.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();
    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Bulb_Replaced_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" + roomNo + "'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}
else if(CheckBoxFilter.Checked == true)
{
    string roomNo = "";
    roomNo = DropDownList1.SelectedValue.ToString();

    testtable2017 entry = new testtable2017();

    SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["iPadLoanConnectionString2"].ToString());

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "UPDATE testtable2017 SET Last_Cleaned_Filter_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" +roomNo +"'";

    cmd.Connection = dataConnection;

    dataConnection.Open();
    cmd.ExecuteNonQuery();
    dataConnection.Close();

    iPadEntities db = new iPadEntities();
    db.testtable2017.Add(entry);
    db.SaveChanges();
}
</code>
So far so good and it is working perfectly but lets say that when the year changes to 2018 I want to create two more columns that will hold all the data logged within 2018. Is there any way of achieving that and if so how could I also manipulate the code in C# to then start save any data entries to the newly created columns?
Thank you
Comment: Don't do that, it's horrible design. Just save the date in a `date/datetime(2)` column.
Comment: UPDATE testtable2017 SET Last_Bulb_Replaced_2017 = '" + Calendar1.SelectedDate.ToString() + "' WHERE Room_No ='" + roomNo + "'"; <-- this is super dangerous, and open to SQL injection. Go and read https://stackoverflow.com/a/30367283/34092 .
Comment: [SQL Injection alert](http://msdn.microsoft.com/en-us/library/ms161953%28v=sql.105%29.aspx) - you should **not** concatenate together your SQL statements - use **parametrized queries** instead to avoid SQL injection
Comment: You have combined ADO.NET and Entity Framework in your code. In any case the code will break when you add new column to table without changing the code.
Comment: What do you think to gain making a separate column for the year? This will only give you more problems when you need to query that data
Comment: @HoneyBadger I forgot to mention I am quite new to this so the probability of getting a bad design was pretty high from the starting point. The thing is i could log the date time in a separate column but I wouldn't want older entries to be overridden.
Comment: Why would older entries be overridden? If you log a new entry, you use `insert`, if you want to update an older entry, you'd use `update`.
Comment: The datetime column will have year information too. New date will not override old values if you don't allow it to be. You can always query the table to retrieve data for a specific year.
Comment: You can add a column for year and use a dynamic pivot to query it with a column for each year. https://stackoverflow.com/questions/10404348/sql-server-dynamic-pivot-query
Answer: I agree with all the people who say this is a bad design and a horrible idea.
However, treating your question as academic, you could simply add some logic to your program to check what year it is today, and query the database to see if the column exists with the year in the name.
If the column doesn't exist, then run an ALTER TABLE statement to add it before proceeding with the rest of the script.   You would also need to use the Year today to build your UPDATE query instead of hard-coding "2017" in it.
Answer: Adding Column: In Object Explorer, right-click the table to which you want to add columns and choose Design.
Click in the first blank cell in the Column Name column.
Type the column name in the cell. The column name is a required value.
Press the TAB key to go to the Data Type cell and select a data type from the dropdown. This is a required value, and will be assigned the default value if you don't choose one.


Populate dropdown with JSON and jQuery

Question: I am trying to populate a dropdown menu from another dropdown.
This happened with the onChange event of first dropdown but I have problem when I select one of the options from dropdown 1 then it do getJson and it returns correct values in JSON, but the problem is that dropdown is populated every time even if I select the same value.
Here is the code:
$.getJSON("ajax.php",
    { m: "modules/json/json-get-category",
      r: $('#id_project').has('option').val()
    },
    function(data){
        var html = '';
        var len = data.length;
        alert(len);
        //$('#id_category').val('').trigger('chosen:updated');
        for (var i = 0; i< len; i++) {
            html += '<option value="' + data[i].id + '">' + data[i].catName + '</option>';
        }
        $('#id_category').append(html);
});

Returned JSON:
[
    {"id":"27","catName":"Hardware support"},
    {"id":"29","catName":"test"}
]

The dropdown1 has correct value on first onChange event, but after it starts to duplicate values:
Example: I have 2 Hardware support, 2 test ... and it just goes to add on it.
Answer: At the beginning of your function, remove the existing options
$('#id_category').empty();

Answer: You need to remove all options before adding the new options. Before your for loop, add the following:
$("#id_category").find("option").remove();

This should remove the current items and make room for the new ones.

Populate dropdown with JSON and jQuery


Problem with semi acoustic guitar sound

Question: How can I get rid of the extra resonating sound coming off the amp ?I have been told that it's sympathetic vibrations.I adding a link for the sample.You can hear this weird sound in the background .You have to use headphones.
https://vocaroo.com/i/s14uqeUS2WhP
Comment: How do you know it's off the amp and not the walls? Small room? Large room?
Does the amp have an open back? Put the mic inside that box, tape a piece of cardboard on it and see if the additional vibrations are gone (it won't sound good but you'd be eliminating the walls.)
Comment: new link -https://instaud.io/3F9B
Comment: Used cans - can't hear anything untoward.
Answer: The link did not work.  It is hard to tell which resonances you are referring to.  For an acoustic guitar you want these resonances to create a full sound.  If you have a hollow body electric, or semi-hollow, like a Gibson 335 or other jazz style archtop, and you are using it with an amp then you have to experiment with the effects set up.  This is a notorious problem with hollow body electrics.  The body resonances get amplified and create feedback.  This get worse with distortion and other effects.  It depends on the type of musics you are playing.  But the problem usually isn't bad when you play clean.  Perhaps someone else in this group knows better how to dampen the feedback with effects.
Comment: new link-https://instaud.io/3F9B
Answer: On second listen I think I know what you're asking about. I would try moving the amp farther from the guitar, changing the angle of the guitar or amp or both, turning down the amp, using a larger room, or just not using an amp at all.
You could also get an EQ pedal or use any EQ built into the guitar or amp to try to eliminate the sound.
Most likely a combination of more than one of these ideas will help the most.

Problem with semi acoustic guitar sound


How to make a whole block clickable?

Question: I'm trying to make a little block that links to the logged-in user's profile. I've already created a view block with the necessary information, but I don't know how to make it clickable and link it to the user's profile.
How can I achieve this?

Edit: One can find some more details about the code that fixed this problem at https://stackoverflow.com/questions/23552893/how-to-create-a-clickable-block.
Comment: Can you share a screenshot of the block that you like to be clickable?
Comment: It's a simple user view that shows four user fields of the currently logged in user. I'll provide a screenshot later.
Comment: Are you displaying the block title? Do you want the block title to be included within the link? So, do you just want to wrap all of the fields within an anchor, such that the path is /user/[uid]?
Comment: @Jason: No, I don't display the block's title. Indeed, that's what I'd like to achieve.
Answer: If you can't edit the output html and don't want to make a custom template, you could do this with CSS by positioning the link div over the block and expanding it to 100% width & height. Apply it to both the container div and the a. Resize the a text & make transparent to so it should still work with screen-readers, ie:
.block-name .field--type-link,
.block-name .field--type-link a {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
color: transparent;
font-size: 1px;
}

title

Content

Link

Answer: Here's a possible solution. In your view, exclude all fields add field 'Global: Custom text'. You may also have to add fields to generate the appropriate path to the user profile.
Then, add the token replacement patterns for the excluded fields. You can either 1) wrap this output in an anchor with the appropriate path /user/[uid] (a field you may have to add, or you may be able to use the user's alias), or 2) in the rewrite section, tick 'Output this field as a link' and specify the path there (also use replacement patterns from UID or the alias).
Comment: I succeeded in implementing your second proposal, but it's not completely what I'd like to see. Now, every field is simply turned into a link, but I'd like the whole block to function as a "button", so no seperate clickable fields.
Comment: Can you elaborate what you mean as a "button"?
Comment: I mean something like the "button" one can find in the upper menu bar on this website. One can go to his/her profile by clicking the image, the medals, etc. I'd like to create something similar.
Comment: Take a look into the markup of what you are referencing. It's a few divs within an anchor. Styles are then added to give it's appearance. It's possible you can achieve a "button" look through css.
Comment: Yes, I checked it with Firebug too. :) I'll see what I can do.

How to make a whole block clickable?


Is it good practice to standardize your data in a regression with panel/longitudinal data?

Question: In general, I standardize my independent variables in regressions, in order to properly compare the coefficients (this way they have the same units: standard deviations). However, with panel/longitudinal data, I'm not sure how I should standardize my data, especially if I estimate a hierarchical model.
To see why it can be a potential problem, assume you have $i = 1, \ldots, n$ individuals measured along $t=1,\ldots, T$ periods and you measured a dependent variable, $y_{i,t}$ and one independent variable $x_{i,t}$. If you run a complete pooling regression, then it's ok to standardize your data in this way: $x.z = (x- \text{mean}(x))/\text{sd}(x)$, since it will not change t-statistic. On the other hand, if you fit an unpooled regression, i.e., one regression for each individual, then you should standardize your data by individual only, not the whole dataset (in R code):
<code>for (i in 1:n) {
  for ( t in 1:T) x.z[i] =  (x[i,t] - mean(x[i,]))/sd(x[i,])
}
</code>
However, if you fit a simple hierarchical model with a varying intercept by individuals, then you are using a shrinkage estimator, i.e, you are estimating a model between pooled and unpooled regression. How should I standardize my data? Using the whole data like a pooled regression? Using only individuals, like in the unpooled case?
Answer: I can't see that standardization is a good idea in ordinary regression or with a longitudinal model.  It makes predictions harder to obtain and doesn't solve a problem that needs solving, usually.  And what if you have $x$ and $x^2$ in the model.  How do you standardize $x^2$?  What if you have a continuous variable and a binary variable in the model?  How do you standardize the binary variable?  Certainly not by its standard deviation, which would cause low prevalence variables to have greater importance.
In general it's best to interpret model effects on the original scale of $x$.
Comment: I'm not clear on how such standardization adds clarity rather than subtracts from it.  Also, the mean is not the obvious choice for centering (median? mode? 43rd percentile? choice of dispersion measure is even more problematic)  Relative importance can be judged in many ways, e.g., partial $R^2$, partial $\chi^2$, inter-quartile-range covariate effects, ...  Also I have not found standardization to be helpful computationally when using modern matrix math routines such as the ones R uses under the hood.  Kenny note that standardization is not the way to compare slopes.
Comment: @Frank, I suppose it depends on what type of models you are running, but standardization of predictor variables is often useful.  Centering them means that the intercept becomes interpretable as the mean predicted outcome and the relative importance of different predictors becomes more obvious.  I usually leave binary predictors alone, but sometimes other scaling options are worth considering.  Finally, in some cases having predictors with wildly different standard deviations can lead to computational/convergence problems.
Comment: If you have binary variables, don't standardize them, only continuous one. See this article by Gelman (, suggesting dividing variables by two standard deviations. In any case, it helps to achive convergence if you are fitting a Bayesian model.
Comment: @Frank Harrell - good points about the problems associated with the conditions you outline but if one has all continuous variables with different scales then isn't standardization the only way to compare slopes?
Comment: And I don't see why it would be better to interpret effects on the original scale. The effect of GDP on a logistic regresssion is hard to interpret looking only to coefficients, because GDP is much bigger than probability scale. Interactions are better understood with standardized coefficients or centered variables. Finally, if you have $x$ and $x^{2}$, in this case don't standardize.
Comment: There are too many exceptions then for standardization to be a recommended procedure in general.  And standardization does not make interpretation of odds ratios easier.  In fact the reverse is true.  Instead, by computing an inter-quartile-range odds ratio (as done automatically in the R rms package) you can say that the effect of moving GDP from a to b absolute units is to increase odds of Y=1 by x.  And there are too many choices of standardization (IQR, Gini's mean difference, SD, inter-decile range, etc.) to make interpretation of interactions straightforward.
Comment: One further comment.  It is almost an accident that a relationship is linear.  This only happens in general in Newtonian mechanics or when relating one variable to the same variable measured at a different time.  Nature is nonlinear the vast majority of the time.  With sufficient sample sizes, the nonlinearity (e.g., significance of nonlinear spline basis functions) becomes apparent.
Comment: I never interpret logitic regression coefficients in odds-ratio, I find them confusing! In any case, interactions without standardization is pretty annoing to interpret in logistic regressions. My regresssions always have interactions terms, sometimes more than one.
Comment: @Frank Harrel, thanks for your anwer. I voted it up, because it's a good answer, with a valid point of view, which enhanced my knowledge of the subject. However, I still desagree with you about standardization, even though it is not always the case the best solution to help interpreting coefficients. And because I desagree with you and I think my question was not properly answered, I'll not mark your answer as an accepted answer.
Comment: I maintain that such standardization (which is arbitrary - why not standardize by the inter-quintile range?) makes interpretation worse.  Staying close to the original scale usually helps because that's the scale of the experiment.  It is absolutely necessary to understand odds ratios to understand logistic regression.
Answer: There is an alternative to standardization to bring variables measured with different scales to the same metric. It's called Proportion of Maximum Scaling (POMS), and it dies not mess with the multivariate distributions as z-transformation tends to do.
Todd Little explicitly recommends POMS over z-standardization in his book on longitudinal structural equation modeling. Z-transformation comes with additional problems when dealing with longitudinal data, see here: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC4569815/


Prevent infinite loop on update function that updates itself?

Question: I'm using Drupal 7 with Commerce, although that doesn't really matter I think.
There's a hook (function) hook_entity_update() that is called when an entity (my shopping cart) is updated.
I want to recalculate my shipping in this hook, the issue is that it saves the entity again once the shipping is recalculated and so it calls the hook again, getting me stuck in an infinite loop.
What would be the best way to solve something like this?
I was thinking of using a simple $_SESSION variable, like $_SESSION['updating'] and set it to TRUE at the start of the hook, then set it to FALSE again at the end of the hook and prevent the function from running with a return at the start if the variable is set to true? I'm not sure if this is a good solution?
Using a session variable because it's a form and the function seems to be called multiple times when submitting.
Not sure if a regular variable would work?
One issue I'm already running into is that the variable is somehow not reset at the end of the function and so the function is never called again ...
Comment: Would `hook_entity_presave()` be more appropriate?
Comment: Would cause the same issue I think?
Comment: If you look at the docs (https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_entity_presave/7.x) it seems to be for exactly what your asking for.
Comment: Looking at it, but don't see how this would help, could you elaborate? This will just call the update a bit later, but it will still start a new update and still loop in the presave function?
Comment: Just a suggestion - can you try using it.  All your doing is altering the data BEFORE the update, so it shouldn't cause another event to be triggered.  Just in this method calculate your shipping and set the value.
Comment: Tried it, doesn't work - My function calls the Commerce contrib module function commerce_cps_add_order_shipping which calls commerce_order_save, so causes an infinite loop.
Answer: Using the session variable seems to work.
Stupid function is somehow called like 7 times when clicking one button ...
Added this at the start of the function:
      // Check if entity is a commerce_order
      if ($type != 'commerce_order') {
        return;
      }

      // Only apply if order is still in cart
      if ($entity->status != 'cart') {
        return;
      }

      if (isset($_SESSION['bab_checkout']['updating']) &&
        $_SESSION['bab_checkout']['updating'] === true) {
        return;
      }
      $_SESSION['bab_checkout']['updating'] = true;

And then this at the end of the function:
  // We're done updating
  $_SESSION['bab_checkout']['updating'] = false;

Still wonder if there is no better solution?


Subdomain does not load scripts and styles

Question: Good afternoon,
1- I created a new solution in Visual Studio 2012
2- I created ASP.NET MVC 4 Web Application. I opted for one project "BASIC" and the Framework 4.5, Razor Engine
3- I created the controller Home
4- I created a View Index.cshtml
The content of Index.cshtml page is only a " Index "
I did nothing, just the main content of a project "BASIC".
Published, see the result:
www.meudominio.com.br -> loads the scripts and styles
imobiliaria589s42d78.meudominio.com.br/ -> NOT load scripts and styles
What should I do to make the subdomain load scripts and styles?
I appreciate the help.
Answer: I am not seeing any issues with styles not loading, so I presume this is an issue with caching in your browser. You can force most browsers to reload cached resources by pressing
<code>CTRL + F5
</code>
Comment: Chrome..    PRESS F12 ... Again in the F5 Network tab and will see What NOT Loads . ( 404 Not Found )


Number of ways of distributing k balls of different colors (all balls of each color indistinguisable) into n bins.

Question: I have a question that I have not been able to find the answer to. Suppose I have balls of $k$  different colors (the balls of each color indistinguishable), $a(j)$  of each color for $j \le  k$ . How many ways can I distribute those balls (i.e., the sum of the $a(j)$ ) into $n$  distinguishable bins? Most balls to bins problems assume that there is only one color, sometimes limiting the maximum number of balls allocated to a given box.
I have looked at binomial type generating functions to no avail (for the general case), and the "twelvefold way" stars and bars approach, but no luck.  I understand the Polya/Burnside approach might work, but haven't been able to formulate the problem precisely.  Can anyone provide solution or point me in the right direction?
Comment: Are you requiring that each bin receive at least one color, or is there some other constraint?
Answer: You can regard each color as a separate stars-and-bars problem, then multiply the answers.  If there are $n$ ways to distribute the blue ones and $m$ ways to distribute the red ones, there are $nm$ ways to distribute the two colors.  This works as long as the distribution of one color does not restrict the distribution of any other color.
Comment: Thanks, Ross.  I did consider that approach.  However, your caveat seems to be precisely my problem.  The choice of balls of one color does restrict the number of choices of the remaining colors.  The total number of balls (across all colors) is fixed.
Comment: @dan:  then bgins and I are not understanding the question.  We assumed the different outcomes were the number of each color in each bin.  You start with some number of blue ones and put them into the bins.  Then you put the red ones into the bins, ignoring the presence of the blue ones.  Yes, the total number of balls is given, as the sum of the number of each color.
Comment: OMG, Ross. I forgot a key piece of information in my problem statement.  You are right about your solution to the problem as stated.  However, the number of totals selected to be put in the bins is a subset of s balls, not necessarily all of them.  If s equals the sum of the a(j) over all j, then you solution works perfectly (in fact I had already discovered that for the limiting case).  Sorry.
Comment: Spelling typo above: "However, the total number of balls selected to be put in the bins...."
Comment: @dan:  I think now you have a two step process.  First, given $s$, find each composition of $s$ subject to your constraint of the maximum number of balls of each color.  Then put those balls into the bins with each color independent.
Comment: Yes...two step I agree is called for.  Unfortunately, I am having trouble formulating the first step in general.  That's where I get stuck....the number of weak compositions under constraints.  In fact the second step depends on each candidate selected from the first step.
Answer: For each color, you have to find the number of partitions $p_n(a_j)$ of each $a_j$ into $n$ nonnegative summands. This can be found with a "blocking" technique: how many ways can you place $n-1$ blocks/divisions between the integers $\{1,\dots,a_j\}$? The answer is $p_n(a_j)={a_j+n-1 \choose n-1}$.
These are ordered partitions, since the blocks act as sequential dividers between the subgroups assigned to adjacent bins.
Thus, your answer, since the colors are independent as @RossMillikan notes, is the product of these: $$\prod_{j=1}^k{a_j+n-1 \choose n-1}$$

I'm still not sure what you want really, but I if you also allow some balls to not be drawn, then you can model this with an extra "null" bin: balls that are assigned there are simply not used. This would of course then give you $\prod_{j=1}^k{n+a_j \choose n}$, with the colors still independent.
If we want $n$ positive summands for each $a_j$, then these are indeed compositions as Ross points out, so then there are ${a_j-1 \choose n-1}$ ways of choosing an ordered composition, or ${a_j-1 \choose n}$ with a "null" bin.

Okay, so we want $s$ balls for some $0\le s\le a=\sum_{j=1}^ka_j$. For starters, as a warm-up, without regard to the bins, the number of ways of choosing $s$ balls of any available color combination is the coefficient of $x^s$ in the (univariate, polynomial) generating function
$$
p(x)=\prod_{j=1}^k\frac{x^{a_j+1}-1}{x-1}.
$$
If we now count the number of distinct monomials of degree $s$
in $p\left(\sum_{i=1}^nx_i\right)\in\mathbb{Z}[x_1,\dots,x_n]$ (a polynomial in $n$ variates), we have our answer. This is a reasonably efficient general solution for moderately sized problems, which can be computed in a straighforward manner.

A little explanation of the above is perhaps in order.
First, recall that $$\frac{x^{c+1}-1}{x-1}=1+x+\cdots+x^c$$
is the sum of a geometric series, provable by telescoping sums.
This is the generating function for choosing $s$ of $c$ identical balls:
you can choose any number $s$ of them, as long as $0\le s\le c$,
in precisely one way ($c+1$ monomials $x^s$, each with coefficient $1$).
Next, if we take these polynomials for $c$ equal to each $a_j$
and multiply them all together, then since polynomial multiplication
"convolves" the coefficients, the coefficient of $x^s$ in the product
gives us the number of ways of picking $s$ balls from the available
(constrained) numbers $a_j$ of each color.
The monomial $x^s$ has a multiple of $x$ for each ball,
regardless of color and bin.
The nice -- and final -- trick is that by substituting $x_1+\dots+x_n$ for $x$,
we can model how many balls each bin gets, to effectively account for
the bins being ordered. Note, by way of analogy, that Gröbner bases
require an ordering of monomials in the ring $K[x_1,\dots,x_n]$.
Thus, the coefficient of the monomial $x_1^{s_1}\cdots x_n^{s_n}$
of degree $s=\sum_is_i$ tells us how many
assignments place $s_i$ balls in bin $i$,
and the number of monomials of degree $s$
tells us how many ways there are of choosing $s$ balls
from the given amounts of distinct (but unordered) colors
and placing them distinctly into the $n$ ordered bins.
Comment: As I understand the question, he wants compositions, not partitions, as the bins are distinguishable and order matters.  Your answer is right.
Comment: Thanks, bgins.  See my comment below.
Comment: So what is it exactly that you need?
Comment: I left out key sentence in problem.  Only s balls are selected to be put in bins.  There are sum of a(j) [over all j less than or equal to k] balls altogether, but only s are selected to go into the n bins.
Comment: Thank you so much, bgins.  I need to puzzle out your explanation as to why p(x) is the correct generating function (not my strong point), but I accept it.  Obviously you understand the problem and I have no doubt you have presented the solution. You have sent me back to Stanley for a refresher on using generating functions for counting problems.
Comment: The only tricky part is convincing yourself that it is correct (or not) up to permutations of the set of colors.
Comment: I added some additional explanation; please let me know whether it helps or not.
Comment: I will get back if I have any questions, but this really does the trick.  Thanks again.


In MVC 5, returning a View with a specified name is returning the entire page within a  tag

Question: Bear with me please, its been years since I have use MVC so I am quite rusty. But I swear this used to work. I have a view using a layout page. The layout page has a couple forms within it, in case that matters.
The Body view contains a grid and some ancillary data. On the click event of the grid, I use JavaScript to submit the form that is within the body.
Tracing through the controller code, everything looks good, the model looks good within the code, but it renders in the client within a pre tag.
I can't for the life of me figure out what I am doing wrong, and my searches are not coming up with anything relevant. Any help would be greatly appreciated! I'm slowly wearing a divot in my desk from banging my head against it.
I have trimmed out a lot of formatting garbage. Hopefully its not relevant; I have the suspicion I am doing something fundamentally wrong or out of date.
Looking at Page Source, it shows regular page source:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Facilities</title>

    ...

Bringing up developer tools, it shows the pre tags:

            "<!DOCTYPE html><meta charset="utf-8" /><meta name="viewport" "
            ...

Controller:
public ActionResult Facilities(int selectedFacility = 0, string selectedFacilityName = "")
{
    // builds model, sets values
    return View("Facilities", model);
}

[HttpPost]
public ActionResult SelectFacility(int selectedFacility)
{
    // Gets selected facility name

    // Originally tried creating a new view model, updating the
    //    two values and displaying like this:
    // return View("~/views/account/Facilities.cshtml", model);

    // Currently trying this:
    return Facilities(selectedFacility, facilityName);
}

ViewModel (I don't think its too relevant though):
public class FacilitiesViewModel
    {
        public string UserId { get; set; }
        public int SelectedFacility { get; set; }
        public string SelectedFacilityName { get; set; }
        public List<Facility> FacilityList { get; set; }
        public int? DefaultFacility { get; set; }
        public string DefaultFacilityName { get; set; }
    }

View:
@model FacilitiesViewModel
@using NonFactors.Mvc.Grid
@{
    ViewBag.Title = "Facilities";
    Layout = "~/Views/Shared/_LayoutWithMenu.cshtml";
}

        Facilities

    @using (Html.BeginForm("SelectFacility", "Account", FormMethod.Post, new { name = "frmFacilities", id = "frmFacilities" }))
    {
        @Html.AntiForgeryToken()

            @(Html
                .Grid(Model.FacilityList)
                .Build(columns =>
                {
                    columns.Add(model => model.FacilityId).Css("d-none");
                    columns.Add(model => model.FacilityName).Titled("Name").Css("text-start");
                    columns.Add(model => model.City).Titled("City").Css("text-start");
                    columns.Add(model => model.State).Titled("State").Css("text-start");
                })
                .Empty("No data found")
                .Filterable()
                .Sortable()
                .Pageable())

        @Html.HiddenFor(m => m.SelectedFacility, new { @id = "SelectedFacility" })
        @Html.HiddenFor(m => m.DefaultFacility)
    }

Comment: I'm encountering the same issue, and there's no JavaScript involved in the execution path that causes it. It's also kind of inconsistent because it can sometimes not happen, but once it does it seems to happen every time that particular controller is hit.
Answer: If you are using Javascript to do the post and it is returning the content to put into a placeholder on the page, then rather than returning View(), you need to return PartialView() instead.
View always returns your _layout.cshtml with the view mixed in, hence you get the full html body again.  PartialView sends back just the view without the _layout.cshtml


Electric guitar amplifier works with headphones but not without

Question: So the problem is whenever I plug my headphones into the amplifier, I can hear the sound amplified but if I unplugged the headphones, the amplifier does not release any sound. What could be the cause of this?
Answer: Sounds like the headphone socket switch has been wired wrong: it usually is responsible for switching the amplified sound off when the headphone is plugged in.
However, that sounds like something that cannot happen without intention, or at least without the one soldering the headphone socket in noticing.
So are you sure this is a headphone socket?  Is it labelled as such?  Does it behave in other respects like one (for example, following the volume setting)?  Is that a stereo or a mono headphone (the plugs are somewhat different, and if you are using a non-headphone socket, the reactions may differ)?  Are you using some kind of headphone adapter for plugging it in?
I am assuming that if you write "I can head the sound amplified" you mean that the amplifier is producing sound through its normal loudspeakers as well as the headphones.
In any case, your situation is unusual and so it would be quite important that you describe very accurately what output you hear through what devices with exactly which plugs and adapters in which socket labelled as what in which situation.
Only then will it be possible to figure out what is different from how it is intended to be.
For example, if you put a headphone into a socket for a footswitch (reverb on/off for example), it's anyone's bet what will happen.
Comment: Yeah I was using a headphone adapter for plugging in and I happened to forget plugging it out and instead I only took out the headphone jack. A silly mistake I know :/ but thank you for helping me out so much!!


Drupal GraphQL logic for Resolver for a field with multiple values

Question: My first Drupal headless project with GraphQL and I am struggling with the logic behind the resolvers.
There is a content type "project" with a field "field_project_description". The field can store multiple values.
This is part of my schema:
type Project {
  id: Int!
  project_title: String!
  project_description: [ProjectDescription]
}

type ProjectDescription {
  value: String
}

And this is how the one part of the corresponding resolver looks:
    $registry->addFieldResolver('ProjectDescription', 'value',
      $builder->produce('property_path')
        ->map('type', $builder->fromValue('entity:node'))
        ->map('value', $builder->fromParent())
        ->map('path', $builder->fromValue('field_project_project_desc.value'))
    );

But as far as I understand there has to be another resolver like
$registry->addFieldResolver('Project', 'project_description',
And I can't figure out, what this resolver has to look like.
Answer: Okay, I solved the problem myself. The answer is very simple actually.
You don't need a second resolver. Just one resolver with an additional PHP function, which flattens the arrays to the strings is enough. This is what the code looks like now.
The schema:
type Project {
  id: Int!
  project_title: String!
  project_description: [String]
}

And the resolver:
$registry->addFieldResolver('Project', 'project_description',
  $builder->compose(
    $builder->produce('property_path')
      ->map('type', $builder->fromValue('entity:node'))
      ->map('value', $builder->fromParent())
      ->map('path', $builder->fromValue('field_project_project_desc')),
    $builder->callback(function ($entity) {
      $list = [];
      foreach($entity as $item){
        array_push($list, $item['value']);
      }
      return $list;
    })
  )
);

I hope I can help someone else with this.


Chrome-Extension: Running Content Editor on Client Side

Question: I'm working on a very simple form filler with Chrome Extension to a spcific site.
I'm getting the name, subject and the message from the user, and just put it in the right places.
I've got a problem with the message part, because it uses an HTML editor. I want to be able to let the user create text message with href links using Microsoft Word or even Front Page and of course a content editor, and just copy the content the user made into the extension, and it will fill it in the right place on the site.
I tried using http://ckeditor.com/ but it can't work without a server. (Use the 1 Visual Studio create to test it).
Is there a content editor like ckeditor, that can work on client side too, and that I can use Javascript to get the info from the user?
I know this is a weird request, and even sound illogical, but is for a friend (and for learning).
(sorry for my english)
Comment: Editors based on `contenteditable` might work for you: http://stackoverflow.com/questions/5228957/whats-a-good-wysiwyg-editor-to-use-with-contenteditable
Comment: thank u, but do u have a direct link to the contenteditable? becuse the link in the page u gave me dosnt work any more (404)
Comment: @apsillers nvm found it, thanks i will check it!
Answer: Afther some days for serching the web i found this: http://html5demos.com/contenteditable
it work only for html 5, and it amazing feature!
if any 1 have this wierd request too, this simple code with get your start:

this is a smaple

this attribute is what make the megic happend: contenteditable="true"
in that div, you can throw any thing from out side your work space. meaning, you can do a href with WORD, and just copy it to the div, and it will set it up for you!
1 thing that is still wierd, if you dont have borders to the div, it will not set 1 for you like normal text field or textarea. so if u dont see it, it dosnt mean is not there!
enjoy.


Product Page Uploads and Automatic Updates

Question: Right now my website has ubercart. I was wondering if there was a way to make it so when a user uploads a file with a description/price/etc that the product page would automatically update with their new upload.
I'm making a user based artist website. Where the users can upload their own art works and sell either a digital copy of their work or a physical copy (their choice ultimately), and I was wanting some help with the logistics of doing such a thing.
The website is currently running with Ubercart and all of its required addons AND the CorporateClean theme.
Any help would be very appreciated.
Comment: I found out more details of what exactly I am looking for. I am looking to setup a user based marketplace.
Comment: So, when you update a description or price the corresponding page still shows the previous details? Or are you looking for a 'user page' with his/her products?
Comment: I am looking for a user page with his/her products. Say SusyQ is selling XYZ and Jake is selling ABC, I want to be able to go to their individual profiles and see that SusyQ is selling XYZ and Jake is selling ABC....

Also, the ability to conglomerate everyone's products under "Categories", say both John and Susyq's products are Electronic. I want to be able to see ABC & XYZ within the "Electronics" category.
Answer: You probably will have to alter the 'ubercart product-content type' and add some taxonomy fields to create the categories (electronics etc.). (Not sure if ubercart has this by default.)
Then you will have to use a view to override the ubercart product page. Look into views and Contextual filters. You can for instance create a block (user-product-block) and use a contextual filter to fill this. You can choose to get the user id from url and then select all products created by that user.
Filtering by category is exactly as done on the page above.