Transitioning from arranger keyboard to piano

Question: (Apologies for any wrong terminology or ignorance - I'm relatively new to music!)
I have been learning to play arranger workstation (using auto-accompaniment) for the past three years with a music teacher. I had no real prior musical background (other than some forced violin and flute lessons in grade school and a year of drum lessons as a teenager) and found these past three years to be very helpful and educational as I have learned a lot about playing melody with the right hand and chords with the left (with some right-handed chords thrown in). I have progressed pretty quickly (according to my teacher) and am now starting to play small events with a guitarist friend. I started with a Yamaha PRS-443 and am now playing a Korg PA700.
I would now like to move on to learning to properly play two-handed piano (for now I would probably continue with my Korg arranger and possibly pick up a workstation or digital piano down the road) - not necessarily classical pieces, but I would like to be able to play rock, pop, and dance music with a band without using the auto-accompaniment. What are some good ways to go about this? I am interested in hearing about techniques and tips, as well as links to online lessons (paid or free). I am in my late thirties and have a busy career, but I try to devote about an hour a day to practicing.
Comment: Playing piano accompaniment without other instruments is pretty much completely different than playing keyboard parts in a pop/rock band. Piano accompaniment is a more extensive matter, but for pop keyboard parts, start listening to what the various instruments do in your arranger keyboards backing rhythms. If there's e.g. an organ part, listen to what the organ is playing in the rhythm variations, and try to replicate that. Keep in mind that you're only playing _one_ instrument part, no more. But for piano accompaniment alone, you're the whole band, and that's a bigger question.
Comment: I had for school a subscription for the EASY PIANIO edition of SIKORSKY with the current hits, (there was also one for accordion and organ). It was very useful and helpful. But today you will find a lot of good tutorials on Youtube and chords to songs in the guitar tabs. What you may need now would be some theory basics in harmony, as chords and chords progression. For finding accompaniment patters you may try some classical sonatinas. I can't prevent myself promoting the Prelude nr. 1  in C by J.S. Bach.
Comment: @AlbrechtHügli thanks - I have some theory basics (I still have a lot to learn) and am pretty good at figuring out the chords when using the auto-accompaniment. I obviously still have a lot to learn, but I have a fairly decent basic grasp of chords and progression. At this point I'm looking to learn to play accompaniment with other instruments, but what I'm mostly looking for is to learn technique. Most of the online lessons I've found assume I know nothing about chords and I'm looking to skip that (since I'm familiar with it already) and jump to actual playing technique.
Answer: Piano accompaniment is a wide and deep subject, but I tried to cut corners and make it look like it's doable in the following eight steps. I made a two-minute video that demonstrates these steps using the beginning of "Amazing Grace" as an example.

Starting point: you're able to play songs so that you play basic root position chords with your left hand and single-note melody with your right hand.
Step 1: Break the chords to both hands so that with your left hand you only play the chord's bass note and with your right hand you play the whole chord. Focus only on learning these roles for your hands for playing chords, don't try to play the melody.
Step 2: Combine with melody! Play the melody with the rightmost two or three fingers of your right hand, and on the "one" of each bar (or if the chord changes in the middle of a bar) add two chord tones below the melody note with your thumb and index finger (or middle finger). If this is too difficult at first, even one chord tone is fine. (By stacking chord tones below the melody note, you're in a sense playing "chord inversions".) The left hand plays bass almost like in the previous step, but playing a new note or repeating the previous one at the beginning of every bar, creating a very basic rhythmic pulse.
Step 3: Play chords with a rhythm pattern. Leave out the melody again, and play just chords with a rhythm pattern with both hands. Your left hand is like the kick drum and the bass, playing on "one". The right hand is like the snare drum, hi-hat or guitar back-beat.
Step 4: Combine with melody! Even one harmony note is enough for the rhythm pattern, if you can't do more. Emphasize the beginning of each bar, and each chord change, by play the whole chord at least lightly, regardless of the chosen rhythm pattern.
Step 5: Make the chord progression more interesting by adding movement and leading tones. Make the bass walk along chord tones e.g. at bar boundaries. (Later on as you get more skilled, you can do walking bass, boogie-woogie, funk bass, many other things, but simple chord tones are easy to start with.) For example, make the plain F major an F7 before going to Bb. Focus on harmony, don't play melody or rhythm patterns. (This is an endless journey - there's always more harmony tricks to add, when you get too used to the ones you already know.)
Step 6: Combine with melody! Don't play a rhythm pattern. Combining the more advanced chords with the melody should be enough.
Step 7: Make your rhythm playing more interesting. Add weaker notes to the pattern. Add swing whenever you can. (I love swing) Don't play melody, focus on rhythmic comping. Groove!
Step 8: Add everything together! Add melody, harmony, and rhythm embellishments as you learn them. You're the whole band now. Listen to pop records and try to identify the essential "hummable" elements in each song and arrangement. What's happening with the rhythm pattern? How could you do it on the piano? How's the bass walking? Are there some interesting riffs and hooks you could imitate? How to do bossa nova comping? Funk? Ballads?

As you learn these steps, play songs together with someone. Get accompaniment gigs. Sing and play songs with family, friends, neighbours, church, random people. Make your playing serve a purpose - I've noticed that that's a very important motivation booster, and it makes the world better too.
And here's the video:
Comment: Wow I was only expecting a few tips and here you gave me what feels like another three years work of learning! Thanks for this and the video - I definitely have what to work with here!
Comment: @ReversePsychologist No problem. I've played pop piano accompaniment all my life, learned it by myself without any proper training, and now I'm interested in finding out if I could explain or teach it to others. I'm using the questions on this site as a pretext for explicating my thoughts. I made the video completely from scratch in a little over two hours, most of it writing the text slides. At first I thought your question couldn't be answered in any short text or video, but I decided to try it anyway. Thanks for asking! (the pop/rock band-member aspect of the question is still unanswered)


Does a twig template know in which region it is?

Question: Or: how do I output conditional classes depending on the region a twig template is being rendered?
Answer: No, it doesn't.
With render caching, it is even possible that the same template/thing is not rendered again and put into a different region (not directly a block, but for a example a rendered entity, in a view or so).
It's easy to do targetting in CSS based on a parent region class. I know there are some recommendations to avoid that, but that's not always possible, especially when working with a complex system like Drupal, where you don't have 100% control over the HTML output in every scenario.


Embedded video thumb has been displayed on all overlay windows

Question: I have been created a block to display YouTube videos on my website ,When ever i tried to open admin windows that video thumbnail has been displaying on every overlay windows how can i disable that any suggestions ?

Screenshot :
Answer: You could try CSS z-index Property

Definition and Usage
The z-index property specifies the stack order of an element.
An element with greater stack order is always in front of an element
  with a lower stack order.
Note: z-index only works on positioned elements (position:absolute,
  position:relative, or position:fixed).

Try setting a higher value to the overlay or a lower value to the youtube player.


Fight in which Mike Tyson knocked out opponent with first punch?

Question: I remember once seeing a clip in which a young Mike Tyson knocked out his opponent with the very first punch of the fight (or round).
It was an unusual knockout because he hit him in the top of the head. As soon as the bell rang, Tyson charged towards his opponent, jumped a little and punched the guy right above the forehead and he crumpled to the ground.
What fight was that?
Answer: Maybe this fight? Mike Tyson vs Marvis Frazier on July 26, 1986.
He landed a few punches though.
Comment: This was, according to Wikipedia, the quickest fight of Tyson's professional career, so it's almost certainly the right answer. OP most likely just misremembers how many punches Tyson threw.


How To Capture Frame With Opencv

Question: This is the main code that loads a pyqt gui form and it has 2 button one is for
starting webcam and second one is for capturing photos from frame .
I write the first button but i can't write the capture button.
import sys
import cv2
import numpy as np
from PyQt5.QtCore import QTimer
from PyQt5.QtGui import  QImage,QPixmap
from PyQt5.QtWidgets import QApplication , QDialog
from PyQt5.uic import loadUi

img_counter = 0

class video (QDialog):
    def __init__(self):
        super(video, self).__init__()
        loadUi('video.ui',self)
        self.image=None
        self.startButton.clicked.connect(self.start_webcam)
        self.capture.clicked.connect(self.keyPressEvent)

    def start_webcam(self):
        self.capture =cv2.VideoCapture(0)
        self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
        self.capture.set(cv2.CAP_PROP_FRAME_WIDTH,640)

        self.timer=QTimer(self)
        self.timer.timeout.connect(self.update_frame)
        self.timer.start(5)

    def update_frame(self):
        ret,self.image=self.capture.read()
        self.image=cv2.flip(self.image,1)
        self.displayImage(self.image,1)

    def keyPressEvent(self):
        flag, frame= self.capture.read()
        path = 'J:\Face'
        cv2.imwrite(os.path.join(path,'wakka.jpg'), frame)

    def displayImage(self,img,window=1):
        qformat=QImage.Format_Indexed8
        if len(img.shape)==3 :
            if img.shape[2]==4:
                qformat=QImage.Format_RGBA8888
            else:
                qformat=QImage.Format_RGB888

        outImage=QImage(img,img.shape[1],img.shape[0],img.strides[0],qformat)

        outImage=outImage.rgbSwapped()

        if window==1:
            self.imgLabel.setPixmap(QPixmap.fromImage(outImage))
            self.imgLabel.setScaledContents(True)

if __name__=='__main__':
    app=QApplication(sys.argv)
    window=video()
    window.setWindowTitle('main code')
    window.show()
    sys.exit(app.exec_())

I want to capture photos from frames and save it in a folder.
The self.capture.clicked.connect(self.keyPressEvent) is for when we clicking on button.
I should write the function in keyPressEvent def
the capture.is for clicking a button
can someone help me through this?
Edit Note :
    if flag:

         QtWidgets.QApplication.beep(i)
         img_name = "opencv_frame_{}.png".format()
         cv2.imwrite(os.path.join(path,img_name), frame)

I want the condition for loop so that i can save the  img_name format with counter but the counter must be number of clicking times
Answer: keyPressEvent is a method that allows you to capture the keys while the widget has the focus, and in your case it is not necessary, the solution is simple change its name, on the other hand I have improved your code.
import os
import cv2
import numpy as np
from PyQt5 import QtCore, QtGui, QtWidgets, uic

class video (QtWidgets.QDialog):
    def __init__(self):
        super(video, self).__init__()
        uic.loadUi('video.ui',self)
        self.startButton.clicked.connect(self.start_webcam)
        self.capture.clicked.connect(self.capture_image)
        self.imgLabel.setScaledContents(True)
        self.capture = None
        self.timer = QtCore.QTimer(self, interval=5)
        self.timer.timeout.connect(self.update_frame)
        self._image_counter = 0

    @QtCore.pyqtSlot()
    def start_webcam(self):
        if self.capture is None:
            self.capture =cv2.VideoCapture(0)
            self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
            self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.timer.start()

    @QtCore.pyqtSlot()
    def update_frame(self):
        ret, image=self.capture.read()
        simage = cv2.flip(image, 1)
        self.displayImage(image, True)

    @QtCore.pyqtSlot()
    def capture_image(self):
        flag, frame= self.capture.read()
        path = r'J:\Face'
        if flag:
            QtWidgets.QApplication.beep()
            name = "opencv_frame_{}.png".format(self._image_counter)
            cv2.imwrite(os.path.join(path, name), frame)
            self._image_counter += 1

    def displayImage(self, img, window=True):
        qformat = QtGui.QImage.Format_Indexed8
        if len(img.shape)==3 :
            if img.shape[2]==4:
                qformat = QtGui.QImage.Format_RGBA8888
            else:
                qformat = QtGui.QImage.Format_RGB888
        outImage = QtGui.QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)
        outImage = outImage.rgbSwapped()
        if window:
            self.imgLabel.setPixmap(QtGui.QPixmap.fromImage(outImage))

if __name__=='__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = video()
    window.setWindowTitle('main code')
    window.show()
    sys.exit(app.exec_())

Comment: thanks for your big help and quick response ,can i ask a little favor? how to loop the capture_image for multiple capturing?
Comment: make a for loop: `for i in range(some_number): flag, frame= self.capture.read()
        path = r'J:\Face'
        if flag: ...`

How To Capture Frame With Opencv


Solution of the ODE $\sum_{k=0}^N\frac{d^k}{dt^k}x(t)=0$

Question: I'm finding a general formula to solve the ODE:
$$\sum_{k=0}^N\frac{d^k}{dt^k}x(t)=0$$
I suppose the solution to be a combination of $\exp$ and $\sin$ and $\cos$ functions, but I'm unable to find a general formula for $x_N(t)$. Thanks
Comment: This is just an ODE with constant coefficients.
Comment: ...also initial conditions would be nice...
Comment: No problem.  First figure out how to factor $1-k+k^2-k^3+\dots$ as a polynomial in $k$.
Comment: @JpMcCarthy: without to specify the initial conditions I expect to have $N$ undeterminated coefficients.
Comment: @Riccardo.Alestra I understand but it might open it up to some Laplace?
Comment: @EricTowers I am having a moment... why the minuses?
Comment: @JpMcCarthy: If the Laplace transform can help to find the solutions we can suppose we have $N$ initial conditions.
Comment: @JpMcCarthy:  Habit.  $\mathrm{e}^{-k t}$ ...
Answer: The characteristic polynomial $\sum_{k=0}^N \lambda^k = \dfrac{\lambda^{N+1}-1}{\lambda-1}$.  The roots are the $N+1$'th roots of unity, except for $1$.
So the general solution is
$$ \sum_{j=1}^{N} a_j \exp(e^{ij/(2 \pi (N+1))} t)$$
Comment: +1 I am profoundly embarrassed that I wrote down $\lambda^n+\cdots+\lambda+1$ in front of me and didn't think geometric series.


Problema com valores randômicos

Question: Boa noite, galera.
Estou resolvendo um exercício onde devo, a cada execução, gerar um número randômico e depois transformá-lo em letra.
Para isso fiz uma função. Está quase tudo certo, o número é gerado e é transformado em letra. Porém, cada vez que executo o programa, ele sempre dá a mesma sequência de números/caracteres. Ou seja, não está randômico.
O código da função é:
int inserir_fila(int x)
{
char ch;
if (fim_fila<=MAX)
    {
        x= rand()% 26;
        ch= x + 'A';
        fim_fila++;
        fila[fim_fila]=ch;
    }
     else
      {
        printf("Fila Cheia!\n");
      }
 return(x);
}

Se precisar, posto o código inteiro.
Muito obrigado
Answer: A função rand() vai buscar um número a uma lista fixa de números aleatórios.
Se não escolheres uma lista específica, o C usa a lista #1.
Para escolheres uma lista específica usa srand() passando o número da lista que vais usar.
srand(1);          // usa lista #1
srand(42);         // usa lista #42
srand(1234567);    // usa lista #1,234,567
srand(time(NULL)); // usa lista #(numero de segundos desde 1970-01-01)

Nota que deves apenas especificar a lista a usar uma única vez em cada execução do teu programa. Principalmente não ponhas o srand() dentro dum ciclo. O uso básico, é colocar o srand(time(NULL)) no princípio da função main e a partir daí, usar sempre e só rand() as vezes necessárias para ir percorrendo a lista de números pseudo-aleatórios.
O teu programa ficaria então:
#include <stdlib.h>
#include <time.h>

int main(void) {
    srand(time(NULL)); // especificar lista de numeros aleatorios
    // ...
    for (int k = 0; k < 100; k++) {
        inserir_fila(k);
    }
    // ...
}

Comment: Agora não está mais repetindo, porém, está apresentando caracteres que eu não posso apresentar, como caracteres especiais e letras minúsculas.
PS. Não estou usando void
Answer: Ve os meus comentarios abaixo. Os comentarios dizem respeito as linhas assinaladas
int inserir_fila(int x)      // [1]
{
char ch;
if (fim_fila<=MAX)
    {
        x= rand()% 26;
        ch= x + 'A';
        fim_fila++;          // [2]
        fila[fim_fila]=ch;   // [3]
    }
     else
      {
        printf("Fila Cheia!\n");
      }
 return(x);                  // [4]
}

[1] Para que serve o parametro x? Ele nao e usado na funcao!
[2] e [3] Assumindo que fila e fim_fila sao variaveis globais correctamente definidas Nunca vais escrever no primeiro elemento de fila. fila comeca com fila[0], mas o valor de fim_fila passa a 1 antes da atribuicao.
[4] Qual a razao de devolveres o ultimo caracter aleatorio gerado?
[*] E ainda: o array fila precisa de um terminador para ser uma string. A ultima letra aleatoria deve ser seguida por '\0'.
Habitua-te a NAO USAR variaveis globais.

Problema com valores randômicos


Sample Library: Orchestra vs Band

Question: I'm an amateur composer interested in purchasing a high quality orchestral sample library like Garritan Personal Orchestra. The problem is that I plan on composing a piece for my schools concert band, and I can't decide between Garritan's "Personal Orchestral" or the "Concert & Marching Band" sample libraries: https://www.garritan.com/
I am in the process of reading Rimsky Korsakov's "Principles of orchestration", so it would be ideal to have a high quality virtual orchestra. I would still use the concert band library for other projects, but I plan on pursuing film/video game composing as a career, and these typically use orchestral sounds. I also just enjoy orchestral music more in general.
Advice from composers/musicians who have experience in both the orchestra and concert band would be greatly appreciated. Do most of the orchestration principles apply to both groups? Would writing one concert band piece while learning orchestration for the orchestra be confusing. Thanks in advance!
I also play the clarinet and alto saxophone.
Answer: Samples can be dangerous. First and foremost you need to remember that you're writing for real people, and that should always be your end goal. If you have limited experience, samples can distort your perception of balance, texture, and response throughout register. There are also many things that can't be played back, for example, if I specify a passage on violin to be written played "sul G", it won't make a difference for playback.
It often seems like every young person wants to be a film composer, and it makes sense because what other access would they have to what composers do? The film market is quite crowded and chances are it's not actually what you think it is. Same thing with being hung up writing for Orchestra. They're big and political and bloated and often too afraid to program new things. Writing for orchestra is an incredible and rewarding experience, but don't do the classic amateur thing and romanticize film scoring and orchestra sound. I have more to say on this but I don't want to digress too far here.
Samples can be great, but if you don't have the real world sounds in your ear they can mess you up. Use whatever you have. The only real difference between the libraries you mention is strings, which sound okay even with terrible MIDI and saxes which always sound terrible without exception.
Regarding orchestration texts, there are much, much more current things you should be reading such as the Adler and the Blatter texts. Also do yourself a huge favor and get the Solomon book on percussion.
Comment: Thanks for the advice. Maybe, once I finish my first decent score for a full orchestra I'll have it recorded by the "$99 Dollar Orchestra".
Comment: Also, when I said "pursuing film/video game composing as a career" I wasn't implying getting a degree and going all out on it; I'll probably end up working a day job while composing in my free time with the hope of one day composing for high profile media.
Comment: Well, unless you dedicate your life to the pursuit of creation, it's highly unlikely you'll find yourself in a high-profile situation. Few musicians ever have the luxury of being so derelict and creating so much with so little effort.
Comment: I wan't implying that "composing in my free time" meant composing frivolously; I'll just be incorporating my dream into a reasonable lifestyle. Hans Zimmer started out in a rock band, John Williams didn't score a movie until he was 26, and Beethoven started out as an assistant organist. Hell, the Brandenburg Concertos sold for $24 dollars after Bach's death. There are two types of composers: the realists who go to music school and spend their days pointing out your counterpoint errors and the ones who compose for hours on end into the late night until they are satisfied with their work.
Comment: And btw, I knew the difference between an orchestra and concert band... What I was wondering was whether arranging music for band while studying orchestration would be confusing.
Comment: @GreenPlasma I am sorry to see that your understanding of composition is so binary; there are many more types than the ones you describe. Williams scored television before film, and Bach was famous as an organist during his lifetime; all but forgotten after he passed if it wasn't for Mendelssohn. I know composers who toiled in film for decades before finding success elsewhere. Sometimes you don't have a choice. The type of ensemble doesn't matter: everything is orchestration. Orchestration is the craft, the act of doing. You will learn no matter what you do. Just make sure you hear it live.
Comment: THAT WAS MY POINT EXACTLY!; following your passion means things can turn out differently than planned, which can be good. This is why I'll follow my desires, which DON'T include: spending lots of money on a music degree and moving to Hollywood. Thanks for the advice, but I don't agree with your pessimistic artistic views. Dreams motivate people; mine motivates me to compose with hope that my music might one day be enjoyed by other people (it isn't bad now though). I was implying in my post that film would is my preferred medium for music, not that I'll risk everything for it specifically
Comment: @GreenPlasma This is good dialogue but will have to be my last comment here as these comments aren't intended for discussion. Some of my views might seem pessimistic, but they are colored with life experience; I live this and do it; I know the work involved and I know better than most the surprising turns a career can take. Just don't want you to be hurt b/c of inexperience. Never stop writing and never, ever apologize for your music. If you want it, work. Cut your teeth on student / low-budget films and then go from there. Work as an orchestrator / copyist. Do it everyday.
Answer: I have both libraries and have used both. The same principles apply with two big exceptions: first, the lack of strings in the band, and second, the difference in percussion instruments. There are minor differences: the band has things like alto clarinets and the whole family of saxes but usually lacks bassoons or oboes.
Allocation of lines to instruments is the big difference. No basses or celli or bassoons to carry the bass lines (although some bands have bassoonists and oboists.)

Sample Library: Orchestra vs Band


Erro ao instalar o pacote RSQLite do R no Windows10

Question: Ao tentar instalar o pacote RSQLite do R no Windows 10 recebo a seguinte mensagem de erro.
make: *** [C:/R/R-3.6.1/etc/x64/Makeconf:215: DbDataFrame.o] Error 1
ERROR: compilation failed for package 'RSQLite'
* removing 'C:/R/R-3.6.1/library/RSQLite'
Warning in install.packages :
  installation of package 'RSQLite' had non-zero exit status

Alguém sabe como resolver esse problema?
Comment: Tem o [Rtools](https://cran.r-project.org/bin/windows/Rtools/) instalado? Em Windows precisa de instalar esse conjunto de ferramentas, que são ferramentas padrão em unix/linux.
Answer: Tente instalar o este pacote com o comando a seguir:
install.packages("ggplot2", dependencies=TRUE)

Fonte
Comment: Caro amigo, instalei o ggplot2 sem problemas. Esse pacote (ggplot2) não precisa de compilador já o RSQLite necessita. Pelo que já pesquisei o problema deve estar relacionado ao compilador gcc. O que acha? Após instalar o pacote ggplot2, tentei novamente instalar o RSQLite e retornou o mesmo erro.
Comment: Tem razão viajei na questão, não vi que não tinha nada a ver com o ggplot, desculpe. Está instalando pelos binários ?
Comment: Caro Andrey, realmente, resolvi a questão com a ajuda da equipe de suporte do Data Science Academy.  Como comentou em sua reposta, fiz o download do arquivo binário para minha máquina e instalei por ele.  Tudo certo! Muito obrigado!


Java selection sort not working correctly

Question: I have just created an int[ ] class called 'Statistics' and it has two selection sort methods for listing the integers in a Statistics object (int[ ]) in ascending or descending order. When I use either of these methods they tend to work about half of the time and then not work the other half of the time. Here's a couple examples of what I mean:
New Run
Test1 = {2, 5, 3, 7, 8, 9, 6}
Test1.sortDataDsc() will give me: Test1 = {8, 7, 6, 9, 3, 5, 2}
Test1A = {8, 7, 6, 9, 3, 5, 2}
Test1A.sortDataAsc() will give me: {2, 5, 3, 6, 7, 8, 9}
New Run
Test1 = {2, 5, 3, 7, 8, 9, 6}
If I do Test1.sortDataAsc() first it will sort the data correctly and also correctly sort it in descending order if I do that after.
New Run
Test2 = {7, 4, 5, 8, 0, 1}
Test2.sortDataAsc() will give me: {1, 0, 4, 5, 7, 8}.
It will then correctly sort these numbers in descending order and back to the correct ascending order.
All of the test cases I have tried are repeatable if you enter the numbers in the same order. If you change the order of the numbers, then the output could be correct or it could be a different wrong order. I have ruled out every problem I can think of that could cause this and I cannot find any similarities between test cases. If anyone sees anything in my code I could fix or add to remedy this situation it would be greatly appreciated.
count = the number of elements in the array
//sortDataAsc Method - Sorts data elements in Statistics array from least to greatest
public void sortDataAsc(){
    int min, temp;
    for(int index = 0; index < count; index++){
        min = index;
        for(int scan = index + 1; scan < count; scan++){
            if(data[scan] < data[min]){
                min = scan;
            }
        temp = data[min];
        data[min] = data[index];
        data[index] = temp;
        }
    }
}

//sortDataDsc Method - Sorts data elements in Statistics array from greatest to least
public void sortDataDsc(){
    int max, temp;
    for(int index = 0; index < count; index++){
        max = index;
        for(int scan = index + 1; scan < count; scan++){
            if(data[scan] > data[max]){
                max = scan;
            }
        temp = data[max];
        data[max] = data[index];
        data[index] = temp;
        }
    }
}

Answer: Try to change your code as
//sortDataAsc Method - Sorts data elements in Statistics array from least to greatest
public void sortDataAsc(){
    int min, temp;
    for(int index = 0; index < count; index++){
        min = index;
        for(int scan = index + 1; scan < count; scan++){
            if(data[scan] < data[min]){
                min = scan;
            }
        } // closing parenthesis here
        temp = data[min];
        data[min] = data[index];
        data[index] = temp;
    }
}

//sortDataDsc Method - Sorts data elements in Statistics array from greatest to least
public void sortDataDsc(){
    int max, temp;
    for(int index = 0; index < count; index++){
        max = index;
        for(int scan = index + 1; scan < count; scan++){
            if(data[scan] > data[max]){
                max = scan;
            }
        } // closing parenthesis here
        temp = data[max];
        data[max] = data[index];
        data[index] = temp;
    }
}

P.S. for ascending sort you can use
Arrays.sort(array);

and for descending sort
Integer[] arr = {2, 5, 3, 6, 1};
Arrays.sort(arr, Collections.reverseOrder());

Comment: I haven't actually ran this yet, but I think you are "swapping" elements too many times. The inner for loop is to find the next element to swap, then you swap with the current index after that loop.
Comment: You swap elements on every iteration of inner for cycle
Comment: No, I'm saying you swap *after* the inner for loop. Your edits are now correct.
Comment: Now I understand what you mean. I`m edited my answer to 'swapping' element not many times (as you mean)
Comment: Changing the closing brackets resolved the issue. Thanks for your help!


How do you call a Javascript function from an ASPX control event?

Question: How do you call a Javascript function from an ASPX control event?
Specifically, I want to call the function from the SelectedIndexChanged event of a DropDownList.
Answer: I get a little nervous whenever I see this kind of question, because nine times out of ten it means the asker doesn't really understand what's going on.
When your SelectedIndexChanged event fires on the server, it fires as part of a full postback.  That means that for that code to run, the entire rest of your page's load code also had to run.
More than that, the code runs as the result of a new http request from the browser.  As far as the browser is concerned, an entirely new page is coming back in the result.  The old page, and the old DOM, are discarded.  So at the time your SelectedIndexChanged event code is running, the javascript function you want to call doesn't even exist in the browser.
So what to do instead?  You have a few options:

Change the page so the control doesn't post back to the server at all.  Detect the change entirely in javascript at the client.  This is my preferred option because it avoids odd onload scripts in the browser page and it saves work for your server.  The down side is that it makes your page dependent on javascript, but that's not really a big deal because if javascript is disabled this was doomed from the beginning.
Set your desired javascript to run onload in the SelectedIndexChanged event using the ClientScript.SetStartupScript().
Apply the expected results of your javascript to the server-model of the page.  This has the advantage of working even when javascript is turned off (accessibility), but at the cost of doing much more work on the server, spending more time reasoning about the logical state of your page, and possibly needing to duplicate client-side and server-side logic.  Also, this event depends on javascript anyway: if javascript is disabled it won't fire.
Some combination of the first and third options are also possible, such that it uses javascript locally if available, but posts back to the server if not.  Personally I'd like to see better, more intuitive, support for that built into ASP.Net.  But again: I'm talking about the general case.  This specific event requires javascript to work at all.
Comment: Newbie now suitably educated, and gives answer credit accordingly... Thanks! :)
Answer: As Muerte said you have to just put the javascript, or a call to it on the page from the code behind. Personally I use this:
ClientScript.RegisterClientScriptBlock("customscript", "")

Of you can call the function if you already have a more complex one on the page instead of the  stuff I have.
Answer: You can't do it directly from an event, because ASPX control event is server side.
What you can do is emit a Javascript in the ASPX event which will call the JavaScript function when the page reloads.
For example, if in your ASPX page you have a Javascript function called "DoSomething()", in you ASPX control event, add the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "myEvent", "DoSomething()", true);
}

The last boolean parameter defines that  tags are added automatically.
Comment: Sounds like an idea, but I haven't a clue how you do something like that.  Could you be more specific please?
Comment: I edited my post with the code sample, basically Google for RegisterStartupScript() and you'll find a ton of examples.
Answer: In the code behind, attach some markup to the server side control via its attributes collection. This assumes that the function is already in a client script file that is already available to the page.
MyServerDDLControl.Attributes.Add("SelectedIndexChanged", "MyClientSideFunction();");


Is logical AND between Twitter streaming API filter parameters possible?

Question: I'm interested in gathering some Twitter data for my project, connecting to the stream and gathering data based on an number of locations AND a number of track keywords. However, as apparent in the docs, it appears that I will get all status postings that match either condition. Is it at all possible to filter based on location and track?
I'm querying for around 10 cities, and it seems like a crazy prospect to have to open up a pipe to all of them and then have to do my own keyword filtering on my end. I'll be throwing out 99.9% of the data I collect if this is required...
What is the right way to do this? Should I use the Search API instead? The rate limitation seems like an issue, and the Search API won't be capable of delivering the amount of data I'm interested in.
Thanks.
Answer: No you can't define any complex filters on streaming API; there is nothing wrong in throwing out 99.9% of tweets (just do it quickly - before wasting your CPU on processing them)


Why does docker say my container's disk is full when it's not (QubesOS)?

Question: Why does a fresh container on a small-ish docker image say that its disk is full of 10G when it's not?
I'm running this in a Debian 10 AppVM in QubesOS. In Debian 10, I do:
sudo apt-get -y install docker.io
sudo docker pull node:13-buster-slim

At the time of writing, this gives me docker v18.09.1 using the 'overlay2' storage driver by default.
root@coviz:~# sudo docker --version
Docker version 18.09.1, build 4c52b90
root@coviz:~# docker info | grep Storage
Storage Driver: overlay2
root@coviz:~#

My docker host now has only this 181M docker image and no containers. The docker host is using only 0.5G out of 20G available. Plenty of free space.
root@coviz:~# sudo docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
root@coviz:~# sudo docker image ls -a
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
node                13-buster-slim      e4217af9b7c7        9 days ago          181MB
root@coviz:~# sudo docker system df
TYPE                TOTAL               ACTIVE              SIZE                RECLAIMABLE
Images              1                   0                   180.7MB             180.7MB (100%)
Containers          0                   0                   0B                  0B
Local Volumes       0                   0                   0B                  0B
Build Cache         0                   0                   0B                  0B
root@coviz:~#

I'm working on creating a Dockerfile for my project, so I execute the following command to spin up a new container from the above base image and drop me in a shell on that temporary container
root@coviz:~# docker run --rm -it --entrypoint /bin/bash e4217af9b7c7
root@97a318c599ab:/#

It isn't long before I encounter issues when testing out commands to install dependencies with apt-get. I think the issue is that apt needs to store cache data to /var/lib/apt/lists/. The actual error is at least one invalid signature was encountered, but it actually appears to be a disk fill issue (the apt key verification fails because it can't store the signature to disk). Running an apt-clean doesn't help; it's already empty. This is a fresh container based on a fresh image.
Checking the disk with df in this fresh container immediately shows that there's only 17M of disk space available, but I can only account for ~200M with du. Again, this is a fresh container, so I highly doubt this is an issue with a file stuck in a 'deleting' state still opened by a process.
root@97a318c599ab:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay         9.6G  9.1G   17M 100% /
tmpfs            64M     0   64M   0% /dev
tmpfs           255M     0  255M   0% /sys/fs/cgroup
/dev/xvda3      9.6G  9.1G   17M 100% /etc/hosts
shm              64M     0   64M   0% /dev/shm
tmpfs           285M     0  285M   0% /proc/asound
tmpfs           285M     0  285M   0% /proc/acpi
tmpfs           285M     0  285M   0% /proc/scsi
tmpfs           285M     0  285M   0% /sys/firmware
root@97a318c599ab:/# du -sh /*
4.8M    /bin
4.0K    /boot
0   /dev
612K    /etc
20K /home
12M /lib
4.0K    /lib64
4.0K    /media
4.0K    /mnt
5.2M    /opt
du: cannot access '/proc/11/task/11/fd/4': No such file or directory
du: cannot access '/proc/11/task/11/fdinfo/4': No such file or directory
du: cannot access '/proc/11/fd/4': No such file or directory
du: cannot access '/proc/11/fdinfo/4': No such file or directory
0   /proc
136K    /root
8.0K    /run
4.1M    /sbin
4.0K    /srv
0   /sys
2.2M    /tmp
160M    /usr
5.9M    /var
root@97a318c599ab:/#

Moreover, docker ps -s shows that the size of the "writable layer" on my container is empty (0B):
root@coviz:~# docker ps -a -s
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS               NAMES               SIZE
320af1498086        e4217af9b7c7        "docker-entrypoint.s…"   15 minutes ago      Up 15 minutes                           epic_leakey         0B (virtual 181MB)
root@coviz:~#

So why is this fresh docker container's disk (based on a ~200M image) full? What's taking-up those ~9G of unaccounted space?
Comment: Please include how much disk space you are using on the host, not just inside the container, with the same `df -h` command.
Comment: See also https://unix.stackexchange.com/questions/203168/docker-says-no-space-left-on-device-but-system-has-plenty-of-space
Answer: This is an issue with the way QubesOS also layers its disk space for AppVMs.
This was the disk space on the docker host (the Debian 10 AppVM). Note that its 20G of free disk space is in /rw/ but that the available disk space mounted to / is the same as what was reported inside the container.
user@coviz:~$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda3      9.6G  9.1G   17M 100% /
none            9.6G  9.1G   17M 100% /usr/lib/modules
devtmpfs        1.9G     0  1.9G   0% /dev
tmpfs           1.0G     0  1.0G   0% /dev/shm
tmpfs           777M   17M  760M   3% /run
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           776M     0  776M   0% /sys/fs/cgroup
/dev/xvdb        20G  418M   20G   3% /rw
tmpfs            32M   12K   32M   1% /run/user/1000
user@coviz:~$

The solution was to add a config to /rw/config/qubes-bind-dirs.d/ that binds the docker dirs '/var/lib/docker and /etc/docker into /rw/. Not only does this actually give the docker containers access to Qubes's bigger "Private storage", but it also makes that storage persistent across reboots.
The above can be achieved by executing the following on your Debian 10 AppVM:
sudo mkdir -p /usr/lib/qubes-bind-dirs.d
sudo cat << EOF > /usr/lib/qubes-bind-dirs.d/50_user.conf
binds+=( '/var/lib/docker' )
binds+=( '/etc/docker' )
binds+=( '/root/.docker' )
EOF

On older versions of QubesOS (< r4.0), the qubes-bind-dirs.d is in /rw/config/ [1]:
sudo mkdir -p /rw/config/qubes-bind-dirs.d
sudo cat << EOF > /rw/config/qubes-bind-dirs.d/50_user.conf
binds+=( '/var/lib/docker' )
binds+=( '/etc/docker' )
binds+=( '/root/.docker' )
EOF

And then reboot the AppVM. When it comes back up, it will be like this:
root@coviz:~# df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/xvda3      9.6G  8.9G  217M  98% /
none            9.6G  8.9G  217M  98% /usr/lib/modules
devtmpfs        1.9G     0  1.9G   0% /dev
tmpfs           1.0G     0  1.0G   0% /dev/shm
tmpfs           777M   17M  760M   3% /run
tmpfs           5.0M     0  5.0M   0% /run/lock
tmpfs           776M     0  776M   0% /sys/fs/cgroup
/dev/xvdb        20G  617M   20G   4% /rw
tmpfs            32M   12K   32M   1% /run/user/1000
root@coviz:~# docker run --rm -it --entrypoint /bin/bash e4217af9b7c7
root@66766a23ca1b:/# df -h
Filesystem      Size  Used Avail Use% Mounted on
overlay          20G  618M   20G   4% /
tmpfs            64M     0   64M   0% /dev
tmpfs           246M     0  246M   0% /sys/fs/cgroup
/dev/xvdb        20G  618M   20G   4% /etc/hosts
shm              64M     0   64M   0% /dev/shm
tmpfs           274M     0  274M   0% /proc/asound
tmpfs           274M     0  274M   0% /proc/acpi
tmpfs           274M     0  274M   0% /proc/scsi
tmpfs           274M     0  274M   0% /sys/firmware
root@66766a23ca1b:/#


Problema ao tentar exibir dados numa tabela - php

Question: Estou a ter um problema ao tentar mostrar a nproposta, a informação do pedido e a dataregistada. Agradeço desde já qualquer ajuda. Obrigado
<?php
    $ligaBD=mysqli_connect("localhost","root","","pap");

If(!$ligaBD) {
    printf("Ligação falhou: %\n",mysqli_connect_errno());
    exit();
}
?>

titulo

                      <input class="form-control" type="text" placeholder="Pesquisar Nº de Proposta">

                    Nº da Proposta
                    Pedidos
                    Data

            <?php
              $selectProp = "SELECT * FROM propostas,registo
                            WHERE propostas.nproposta=registo.nproposta AND propostas.nproposta='$nproposta'";
              $resultado = mysqli_query($ligaBD, $selectProp);
              if (mysqli_num_rows($resultado) > 0) {
               // output data of each row
               while($row = mysqli_fetch_assoc($resultado)) {

            ?>

                    <?php
                    echo $row["nproposta"];
                    ?>

<a href=".\informaçãopedido.php?nproposta=<?php echo $row["nproposta"];?>">Pedido

                    <?php
                    echo $row["dataregistada"];
                    ?>

            <?php
                    }}
                mysqli_close($ligaBD);
            ?>

                Registar Aquisição/Requisição

Comment: você tem alguma variavel chamada $nproposta fora essa coluna?
Comment: O erro é porque você está chamando uma variável na sua query que não foi definida.
Answer: Sua Query:
"SELECT * FROM propostas,registo
 WHERE propostas.nproposta=registo.nproposta AND propostas.nproposta='$nproposta'";

'$nproposta' não está definida ou inicializada, por isso o erro


Does haproxy cache content by default?

Question: We are currently using haproxy in round-robin mode distribute load across some of our application servers. The basic configuration looks like:
<code>listen  dev 0.0.0.0:15984
    balance roundrobin
    server  dev1 dev1:5984 check
    server  dev2 dev2:5984 check
    server  dev3 dev3:5984 check
</code>
I'm performing some performance testing and wondering, does haproxy cache something in this configuration or just redirect the requests?
Answer: Nope, HAproxy does not cache anything.

Does haproxy cache content by default?


Create a dummy interface inside a Windows container

Question: I am trying to isolate the networking inside a Windows container, which is very easy using --network none.
The problem comes when I have two threads in the same process trying to communicate each other using multicast through a network interface, so this is the reason why I need to create an interface inside the container. The objetive of using network isolation is to avoid sending noise to the same process running in parallel inside another container.
So in other words, I need the equivalent to these commands in Windows:
ip link add dummy0 type dummy
ip addr add 10.0.0.1/24 dev dummy0
ip link set dev dummy0 multicast on
ip link set dummy0 up

I haven't found a tool to create network adapters on Windows so far.
Answer: This is an interesting use case. By default, Windows containers use the NAT network. I think your case would benefit from using some overlay. That way, you can have multiple networks and direct IP addresses from each network to each container. Does that helps? There are more details here: https://learn.microsoft.com/en-us/virtualization/windowscontainers/container-networking/network-drivers-topologies


Two conflicting (?) versions of the Downward Löwenheim-Skolem Theorem

Question: I found two definitions of the Downward Löwenheim-Skolem Theorem:

Def.1: If Γ is consistent, then it has a countable model, i.e. it is satisfiable in a structure whose domain is either finite or countably
  infinite.

From Zach et al.

Def. 2: Let B be a model for ℒ and let κ be any cardinal such that |ℒ| ≤ κ ≤ |B|. Then, B has an elementary submodel A of cardinality κ.

From Weiss et al.
What confuses me is that the first definition makes statements of finite models while the second definition makes statements only about models of cardinality |ℒ| ≤ κ, i.e. κ must be at least countably infinite, since "any language ℒ contains infinitely many variables".
Is there an explanation that somehow unifies those two definitions? Or are they fundamentally different?
Looking forward to the responses .
Answer: Well the difference is that the first version of the theorem is simply false if there are not more assumptions on the language; and even if the right hypotheses are given, the first version is incredibly weaker than the second one.
Note that, as stated, version 2 is also false, $\kappa$ needs to be assumed to be infinite for it to be true.
With these precisions, let's compare the two versions. For simplicity, and to make the first version true and the second version easier to state, let's assume the language is at most countable.
In this case the first version becomes true, and the second one becomes : if $B$ is an $\mathscr{L}$-structure and $\kappa$ an infinite cardinal, $\kappa\leq |B|$ then $B$ has an elementary substructure of size $\kappa$.
From this we may deduce the first version by simply saying : if $\Gamma$ is consistent, then either it has a finite model, in which case we are done; or it has an infinite model, in which case we may apply version 2 with this model $B$ and $\kappa = \aleph_0$.
Since $B$ is a model of $\Gamma$, any elementary substructure is also a model of $\Gamma$, so we get a countable model and we are done.
Now version 1 is much weaker than version 2 because it does not speak about any cardinals beyond $\aleph_0$, and it does not even speak about elementary substructures; you only get models of a certain theory.
I don't know if this weakness can be quantified, but for instance I wouldn't be surprised if there were models of ZF+(version 1) + $\neg$ (version 2) (note that I have to put ZF and not ZFC because of course ZFC proves version 2 - the existence of these models of course relying on the consistency of ZF) - though I can't be sure, someone more qualified than me should be able to answer.
Comment: This answer is very clear. The book by Zach et al. does use the "old fashioned" approach in which there is a single, countable signature that is shared by every first-order theory (p. 64ff). So, in their set of definitions, their statement of the Lowenhiem-Skolem theorem is correct. This is an important point for the OP: **you cannot mix and match theorems from introductory logic books without checking the exact definitions in each book to see if they match**.
Comment: Related to the question at the end of the answer, the general Lowenheim-Skolem theorem is equivalent to the principle "Dependent Choice", slightly weaker than AC, over ZF. The first version of the LS theorem above, for countable theories, is provable in ZF.  There is some info linked from https://math.stackexchange.com/questions/1367342/does-lowenheim-skolem-theorem-depend-on-axiom-of-choice
Comment: In def.2 $\kappa$ is assumed to be $\ge |\mathcal L|$, so it must be infinite.
Comment: @Berci : it depends on the definition of $|\mathscr{L}|$; but if you say that $|\mathscr{L}|$ must be infinite then yes
Comment: @CarlMummert good point about introductory textbooks, and thanks for mentioning the equivalence between LS and choice principles
Comment: Thanks for clarifying! And yeah, I may have butchered the definitions a bit

So, if I got this correctly, the first definition in the given context would not be very practical, because |ℒ| ≤ κ ≤ |B|, where |ℒ| = κ = ℵ0 and thus, there is no smaller infinite elementary submodel to be derived?
Comment: No, the first version is not practical because it cannot derive an elementary submodel; it can only derive models but this not very informative


Process unicode strings in python

Question: I am using fasttext pre-trained model based on english wikipedia. It works as expected...
https://github.com/shantanuo/pandas_examples/blob/master/nlp/fasttext_english.ipynb
But when I try the same code with some other language, I get an error as shown on this page...
https://github.com/shantanuo/pandas_examples/blob/master/nlp/fasttext_marathi.ipynb
The error is related to unicode:
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 15: invalid start byte

I tried to open the file using Raw Binary option. I changed the function load_words_raw in load.py file:
with open(file_path, 'rb') as f:

And now I get a different error:

ValueError: could not convert string to float: b'\x00l\x02'

I have no idea how to handle this.
Comment: When you get errors like these, you should print `repr(s)` to the console to see what the string `s` really contains.
Comment: Can you post the result of the execution of "head -n 5001 cc.mr.300.bin  | tail -n 5000 > /tmp/marathi.vec" somewhere we can download it?
Comment: Ok I just compared both vec files, and the marathi.vec file contains binary data and cannot be processed directly, while the english.vec file is pure float numbers represented as plain ASCII.
Answer: byte 0x80 in position 15. There is a possibility that file may be encoded in UTF-16.
Try this:
with open(path, encoding='utf-16') as f:
   // your logic

Answer: You should change the second line of the notebook file to:
#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.mr.300.vec.gz

So pointing to the vec file, instead of the bin file:
#!wget https://dl.fbaipublicfiles.com/fasttext/vectors-crawl/cc.mr.300.bin.gz

Answer: Try this one :
data : str
with open('crawl-D.txt' ,'r', encoding='utf8') as file:
    data = file.read()

str will contains the whole file as string.
parse float with float().

Process unicode strings in python


English translation of Brahms' essay: "Octaven und Quinten"?

Question: I am now doing some research on Brahm's essay, Octaven u. Quinten. I cannot read German, so I cannot do anything with the original manuscript. I have read some secondary sources about this essay, but they only summarise the main topics without going into details.
Is there an English translation to this essay, Octaven u. Quinten? It does not have to be an exact translation. I am just looking for an article that includes Brahms's main ideas, including exactly what types of consecutive fifths are considered appropriate or inappropriate by Brahms.
Comment: There isn't even the German original text to find (as Pdf or downloadable book)

I found a lot of secondary literature and especially this here:

http://www.schenkerdocumentsonline.org/profiles/work/entity-003331.html

Schenkers handwritten letters copied and translated in English.

Could this help? Do you have an digital copy of the original you could share?
Answer: The English wikipedia has a reference to a printed book:

Oktaven und Quinten translated by Paul Mast 1971
Comment: The most convenient location of this translation is likely Volume 5 (1980) of *The Music Forum*.
Answer: There isn't even the German original text to find (as Pdf or downloadable book)
I found a lot of secondary literature and especially this here:
http://www.schenkerdocumentsonline.org/profiles/work/entity-003331.html
Schenkers handwritten letters copied and translated in English.
Maybe you have access to this site:
https://academic.oup.com/ml/article-abstract/73/1/48/1220490/?redirectedFrom=PDF
Comment: I fail to see, how this answers the question, given that the OP already mentioned studying secondary sources.
Comment: secondary sources very often contain translated  quotations of whole passages. Well, I have overseen that OP has already found some secondary sources as I was looking - in my own interests - for the original and a translation. I have found Paul Mast too, but if OP can't afford to buy it? May be one of the sources above OP didn't find as OP also didn't find Paul Mast. :)


Shopify: Does different Version of same Theme with different number of posts loses Posts

Question: I have two different versions of the same theme and two different Shopify stores.
One is live and has some latest blog posts,
other one is used for development purpose i.e some styling and has less number of blog posts.
Will download the theme from the development version and publishing it to the live website remove blog posts?
If it does then what is the best way to apply only front-end changes from one store to other?
Answer: Blog Articles (Posts I assume) exist in Shopify as resources you create, the same as any Product, Page or Collection. They do not disappear or otherwise change with Theme Changes.
When your theme is set to render a blog, it renders a number of articles based on some criteria. These days, likely a setting you can touch with the Setup of your theme, requiring no code.
If you update a theme, theoretically, the display of blog articles would not change. You should be safe as houses in other words, to play with your theme, and not see a difference in the blog articles save for what you actually change theme-wise or settings wise with regards to rendering a theme.
If you're really interested in the little bit of code involved, check your theme files for blog.liquid and article.liquid for ways you can tweak your display.
Comment: Problem is not with the layout of blog posts
actually I tried uploading the customized theme after publishing theme all of the latest blog posts disappeared and when published the previous theme all came back.
Comment: I stand by my answer. It is correct. It tells you all you need to know.
Comment: The new theme is probably pointing to a wrong blog handle. There should be a setting somewhere in the theme customizer that lets you select the blog to use.
Comment: what is a blog handle. Sorry I am newbie and not familiar with it so much.
Answer:
Will download the theme from the development version and publishing it to the live website remove blog posts?

No, your data is complete decouple from your theme.

If it does then what is the best way to apply only front-end changes from one store to other?

One way to avoid any data sync issue or syncing configuration between environments is to you your production environment as your dev environment.
You can duplicate your production theme, in your production environment and make changes to it and make sure you keep your theme unpublished. Shopify has a "theme preview" feature that allows users to see an unpublished theme, which can be considered as your development theme.
Most likely your environment is out-sync in some way that is why it looks like you are missing your data.


How can I solve form "errors has been found" with custom Ajax dependant field and other Ajax fields?

Question: I've altered a node\edit form where there are two taxonomy refence fields with a select widget.
I've added a custom ajax callback on the first field, in order to populate the options of the second one only with a subset of values.
This works fine, the problem is the presence of another ajax field - e.g. a image field.
If the user set the "select fields" first and then try to add an image, the ajax of the image field always returns "1 error has been found" on the second select field. Debugging that part kinda makes sense, as the form_state values only contains at that point the values of "image field" and thus the 2nd select field is left only with "_none" value.
With this patch the problem is somewhat better, as the ajax on the image fields works. However if the user populate the select first and the image field after, the form submit validation returns again the "1 error has been found" on the second select field, with that field populated only by "_none" value, while the first select field still contains the correct selected value.
I don't know if this is a known bug of D9, if there are other relative patches I couldn't find, or if I'm doing something wrong in my custom code - attached below.
Thanks for any help.
<?php

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_my_node_form_alter(&$form, $form_state, $form_id)
{
    my_module_node_custom_form_alter($form, $form_state);
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_node_my_node_edit_form_alter(&$form, $form_state, $form_id)
{
    my_module_node_custom_form_alter($form, $form_state);
}

function my_module_node_custom_form_alter(&$form, $form_state)
{
     $form['my_first_field']['widget']['#ajax'] = [
        'callback' => 'my_module_my_first_field_callback',
        'wrapper' => 'my-second-field-wrapper',
        'event' => 'change',
        'progress' => [
            'type' => 'throbber',
        ],
     ];
     $form['my_first_field']['#limit_validation_errors'] = [];

     $selected_value = !empty($form_state->getValue('my_first_field')) ? $form_state->getValue('my_first_field')[0]['target_id'] : null;
     if(empty($selected_value)) {
         if(!empty($form["my_first_field"]["widget"]["#default_value"])) {
             $selected_value = $form["my_first_field"]["widget"]["#default_value"][0];
         }
     }

    my_module_set_my_second_field($form, $selected_value);
}

function my_module_set_my_second_field(&$form, $selected_value)
{
     $form['my_second_field']['#limit_validation_errors'] = [];
     $options = my_module_get_my_second_field_options($selected_value);

     $form['my_second_field']['#prefix']='
';
     $form['my_second_field']['#suffix']='
';
     $form['my_second_field']['widget']['#options'] = $options;
     $form['my_second_field']['#limit_validation_errors'] = [];
}

function my_module_get_my_second_field_options($selected_value, $vid = 'my_vid')
{
    if(empty($selected_value)) {
        return ['_none' => t("- Select 'my first field' first -")];
    }

    $options = ['_none' => t("- Select a value -")];

    $terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadTree($vid, 0, null, true);
    foreach($terms as $term) {
        if($term->field_to_check->target_id == $selected_value) {
            $options[$term->id()] = $term->getName();
        }
    }

    return $options;
}

function my_module_my_first_field_callback(array &$form, \Drupal\Core\Form\FormStateInterface $form_state)
{
    return $form['my_second_field'];
}

edit:
as I had to deliver something usable, as workaround I've set up a check on the triggering_element: it does the logic if that is empty (case of page load\submit) or has the name of "my_field", otherwise skip it.
Not probably the correct or most elegant way to do it, but it seems to work so for now I'm doing this way. Kudos to anyone who know and explains how to do it better.
Updated relative code:
function my_module_node_custom_form_alter(&$form, $form_state)
{
     $form['my_first_field']['widget']['#ajax'] = [
        'callback' => 'my_module_my_first_field_callback',
        'wrapper' => 'my-second-field-wrapper',
        'event' => 'change',
        'progress' => [
            'type' => 'throbber',
        ],
     ];

     if( !isset($triggering_element) || (isset($triggering_element['#field_name']) && $triggering_element['#field_name'] === 'my_first_field')) {
      $selected_value = !empty($form_state->getValue('my_first_field')) ? $form_state->getValue('my_first_field')[0]['target_id'] : null;
      if(empty($selected_value)) {
          if(!empty($form["my_first_field"]["widget"]["#default_value"])) {
              $selected_value = $form["my_first_field"]["widget"]["#default_value"][0];
          }
      }

      my_module_set_my_second_field($form, $selected_value);
    }
}

Comment: A few tips: try adding the `['#limit_validation_errors']` to the `[''widget']` instead. Use Xdebug to see what causes an error in form validation.
Comment: @milkovsky thank you for the answer, limit_validation_errors attached to the widget didn't solve the problem. I tried to skim a little in the validation process but I had no time to understand\find the eventual problem here. I resolved for now with a (dirty?) workaround, I've edited the question with the relative code.
Answer: I had to work again on this part of my site. This time to check a dependant field inside a paragraph, so I had the same problem - empty form_state values - in a more complicated situation.
In the end what worked was to switch to form_state->getUserInput, which seems to always contain the updated data.
Please note, as stated by the docs, this array insn't sanitized nor validated so it could be vulnerable to user injection - however my case was safe enough, as only integer are allowed values.
Here the code I'm using to get the 1st select value, from node and paragraph alter hook:
  $user_input = $form_state->getUserInput();

  //check to avoid user injection, my case was a taxonomy term select, so allowed values are integer
  $my_field_value = isset($user_input["my_field"]) ? intval($user_input["my_field"]) : NULL;

  // in case of edit node, when loading the form user input is empty -> get the initial value
  if (empty($my_field_value) && !empty($form["my_field"]["widget"]["#default_value"])) {
    $my_field_value = $form["my_field"]["widget"]["#default_value"][0];
  }

  if(empty($my_field_value)) {
    $my_field_value = '_none';
  }

  return $my_field_value;


how to extract API from websites in laravel 5.2?

Question: I am new to the Laravel5 framework , so that I have no idea about this.I want to fetch data from a website and store that in my database.can anyone provide a sample coding that will come under model , view , controller and route, so that I can understand it in better way.
Comment: Hi and welcome to SO. Please make sure you [read this](http://stackoverflow.com/help/mcve) and try to improve your question. It will make it easier for others to understand it and help you out.
Answer: everything except something's come under model controller view and routes.
start from the Tutorials docs and continue to The Basics
navigate in the left navigation from top to bottom


Qual a diferença entre Template e Layout?

Question: Gostaria de saber a diferença semântica, visual e no desenvolvimento web front-end e back-end.
@edit
Relacionadas:

Existe algum tipo de dependência? Para ter o layout é necessário ter
o template?
Comment: Acho que a pergunta está completamente dentro do escopo do site
Comment: Trabalho com desenvolvimento web já faz algum tempo, seria difícil dar uma definição que não fosse baseado em opinião então só me arrisco a dizer o seguinte: Acho que são sinônimos.
Answer: Os conceitos para Template e Layout se aplicam além da web, e são utilizados por N áreas. Focando ao desenvolvimento web como sua dúvida:
Template

É um conjunto de arquivos e instruções, contendo apenas a parte visual da  apresentação do conteúdo. É um modelo de documentos que dará forma ao conceito final.

Layout

É a forma como o conteúdo é formatado e apresentado, a estrutura e diagramação.

Fazendo uma analogia barata: Imagine que vamos construir uma pipa(espero que já tenha feito isso), a estrutura básica de uma pipa é a mesma:

Nesse caso, é o template.
Porém a cor da seda, o tamanho da rabiola ou os desenhos dela podem ser alteradas sem influenciar na estrutura principal dela e são apenas para enfeite. Aqui temos o layout.
@edit

Existe algum tipo de dependência? Para ter o layout é necessário ter o template?

Um template terá um layout, a forma como os dados são organizados para exibição - mas um layout não precisa estar em um template, você pode criar um documento único e que não precise de template ( um modelo padrão a seguir ).
Fontes:
Layouts

Definição: http://dictionary.cambridge.org/pt/dicionario/ingles/layout
Layout de um slide - https://support.office.com/pt-br/article/O-que-%C3%A9-um-  layout-de-slide-3a67bbc6-f433-4890-8549-398c3b0bf934
Estudo do layout - http://www.producao.ufrgs.br/arquivos/disciplinas/393_seq_3_tipos_layout.pdf
Sobre layout - http://www.uff.br/sta/textos/ar022.pdf
Layout de empresas e seus benefícios - http://www.abepro.org.br/biblioteca/enegep2013_TN_STO_177_010_23292.pdf

Templates

Definição: http://dictionary.cambridge.org/pt/dicionario/ingles/template
Modelos de documentos - http://www.governoeletronico.gov.br/sisp-conteudo/nucleo-de-contratacoes-de-ti/modelo-de-contratacoes-normativos-e-documentos-de-referencia/templates-modelos-de-documentos
Template em C++ - http://www.dei.isep.ipp.pt/~hleitao/EI/Templates.pdf
Comment: Basicamente o que eu pensava, pode citar fontes (mesmo que não se referindo ao desenvolvimento web)?
Comment: Existe algum tipo de dependência? Para ter o layout é necessário ter o template?
Comment: @RowAraujo editei a resposta e adicionei sua pergunta em quote, respondendo-a.
Comment: @KaduAmaral adicionei algumas fontes.
Answer: Layout é a forma com que um conteúdo é apresentado, formatado e diagramado. É mais ligado à sua estrutura de apresentação. (O que?)
Normalmente não é o arquivo final da sua ideia, mas pode ser parte integrante dele.
Template é o conjunto de arquivos e orientações para a disposição do conteúdo e da apresentação visual. (De que forma?) Este conjunto de arquivos dá a forma ao conceito ou o tema do projeto, da ideia, do site/app.
Existe uma dependência entre eles, pois um template já foi um layout. Pode-se ter um template com um layout específico, e em cima do mesmo template se trocar o layout. É possível também ter um template único que possui vários layouts.
Quando penso nesta temática, lembro do Powerpoint. Você abre o programa, e ele te dá algumas opções de slides (slide branco, título, subtitulo, imagem, conteudo, coluna). É um modelo simples, e você utiliza aquilo que faz sentido à sua apresentação. Você pode utilizar esta ideia e pode alterar. (layout)
Ou você pode pegar um modelo pronto, que já vem com animações aplicadas, com desenhos diferenciados, caixas de texto localizadas em locais determinados e até diferenciados, tudo isto com o objetivo de formar um conceito visual. Para chegar a este arquivo fechado, alguém pegou um layout e o modificou até que este fosse coerente com o tema que se pretende.(template)
Ou um exemplo ainda mais simples. Desenhe uma pessoa. Um boneco de palito é um layout. Tem cabeça, tronco e membros, na ordem necessária, nos locais certos, e na quantidade suficiente para sua identificação. Agora se você vai fazer seu desenho com tinta, com lápis, com uma certa espessura de traço, realístico, colorir, com determinado estilo, etc; isto seria o template.


session and PHP ( two site on localhost)

Question: I am working on a website , everything worked good , but I maked a copy of my website (I run at localhost)
when I login at new site , the session created but , for old site ! I can easily login to old site with new site =))
my problem is here new site do not store (or find) the session , when I check with firebug , a new cookie created successfully.
how can I solv it ?
Comment: possible duplicate of [Same session variable for different systems](http://stackoverflow.com/questions/1790130/same-session-variable-for-different-systems)
Comment: Just put sites on different subdomains (one.localhost, two.localhost). Set up apache correct ways, and put host/ip to hosts file.
Answer: Use a different session_name(String) for each site and before session_start().
More info: http://php.net/manual/en/function.session-name.php


Prove $(\forall x\ Q(x))\to P ⊢ \exists x (Q(x)\to P)$ using Natural Deduction

Question: I have stumbled upon this predicate logic sequent which I have trouble proving using natural deduction:
$(\forall x\ Q(x))\to P ⊢ \exists x (Q(x)\to P)$
I started with ∀xQ(x) → P as the premise. I wanted to start using universal elimination but since the ∀x doesn't cover Q(x) → P completely, I refrained from doing so. I had to assume ∀xQ(x) but when I did, I couldn't reach ∃x(Q(x) → P) out of the assumption's scope.
I have also tried proof by contradiction but I couldn't progress. I tried to prove p → q ⊢ (¬p V q) with natural deduction to be able to incorporate it into the solution, but I couldn't prove it either.
So, I think I am completely stuck this one. Could you help me prove this (or tell me if this cannot be proved by natural deduction for any reason)?
If it helps, I am using the inference rules listed under
https://en.wikipedia.org/wiki/List_of_rules_of_inference
Comment: https://math.stackexchange.com/questions/3419952/prove-using-natural-deduction-in-predicate-logic-forall-x-px-to-q-⊢-exis/3422899#3422899
Answer: Hint: you will need to use the law of the excluded middle (LEM) in whatever form it is presented in your system of natural deduction. By LEM, it suffices to consider two cases: (i) when $P$ is true and (2) when $P$ is false. In case (i) any implication of the form $A \to P$ is true and hence so is $\exists x(A \to P)$ for any formula $A$. In case (ii), we must have that $\forall xQ(x)$ is false, given that $\forall xQ(x) \to P$, so $\exists x \lnot Q(x)$ and an $x$ that witnesses that will also witness $\exists x (Q(x) \to P)$. I leave it to you to translate this into the system of natural deduction you are using.
Answer: Here's a skeleton of a proof by reduction to absurdity.  Prove that it is absurd to assume that such a conditional does not exist.
$$\def\fitch#1#2{~~~~\begin{array}{|l}#1\\\hline#2\end{array}}
\fitch{(\forall x~Qx)\to P}{\fitch{\lnot\exists x~(Qx\to P)}{\fitch{\boxed a}{~~\vdots\\Qa}\\\forall x~Qx\\P\\\exists x~P\\\fitch{\boxed c~P}{~~\vdots\\\bot}\\\bot}\\\lnot\lnot\exists x~(Qx\to P)\\\exists x~(Qx\to P)}$$
Comment: Thank you for your answer. This part was exactly where I got stuck when I tried proof by contradiction. Inside the scope of ¬∃x (Qx→P), I can obtain ¬(Qx→P) and ¬∀x Qx but I cannot use them to reach falsity.
Comment: Exactly; so you don't want to do that.  Rather, derive $\forall x~Qx$ via universal-introduction so you may then derive a contradiction via universal-elimination .


Faceted search using fields from a related node, is it possible?

Question: Drupal 7
Modules:
Facet_api 7.x-1.3
Search_api 7.x-1.6
Relation 7.x-1.0-rc4
My site has two nodes, node one provides a description of various astronomical objects and node two are images and their composition details. I've built a many to many relationship between the two nodes and there is a node index (search_api) which contains all fields from the two content types with facets enabled on the primary fields.
I've created the faceted search page for the Astronomical objects which works fine and I now want to extend the Astronomical facets to gallery search page (. e.g. Show all images containing an astronomical object of type galaxy) which is where I have become stuck as I can't see a way to create an index which joins relationships and nodes.
If this approach isn't possible the only alternative I can think of is building out the relation type with extra fields duplicating the data that I want from either node and building the index on it, which just feels like a hack. Any suggestions?
Answer: At the bottom of the fields page you can see additional fields. This allows you to join nodes via relationships.
Search API > Default index > Fields > [Scroll to bottom} > Add related fields

Select your field that is an entity reference.
You'll have access to the fields of the reference too.
Then select the fields on the referenced node that you need and save.
And return to facets.

http://example.com/admin/config/search/search_api/index/default_node_index/fields#edit-additional
Answer: I can't post comments, so excuse me, but I think that I should warn you about one moment.
The first answer is right for me, but you must remember that if related field was changed - you must manually rebuild index. I found one solution: use hook and
<code>search_api_track_item_change($entity_target, $entity_ids);
</code>
search_api_track_item_change
hook_node_insert
Another way is to rebuild index via cron.


get ErrorLog value from PHP

Question: How can I know the apache log directory from PHP?. For example, I have a machine where the log path is /var/log/httpd and others with /var/log/apache2 and I don't want to hardcode it or to find the path with tryouts...is it possible to read any constant or php function which gives such information?
thanks in advance!
pablo.
Comment: You should look at your php.ini
Answer: in php.ini theres a variable called error_log
you can get it with ini_get
<code>$logpath = ini_get('error_log');
</code>
now you have the path of the log stored in your variable.
Comment: As a addon, if you need to know the path, use above code and add: print_r($logpath); It will print the path for you.
Comment: I tried before but this variable comes empty, also I've tested ini_get_all() but there is nothing about logs there.
Comment: check if the line is not empty in php.ini

get ErrorLog value from PHP


Combining variables

Question: I'd like to combine several variables into one variable.  Here is some context:
Let's say I have two variables Red.Beads and Blue.Beads and each observation of each variable is a number representing the number of beads for that observation.  Say each red bead has a mass of 5 grams, and each blue bead has a mass of 1 gram.
I can a single variable representing overall bead mass for observation by doing the following:     5*Number.Red.Beadsi + 1*Number.Blue.Beadsi.
But, if I do not have access to the mass of each type of bead, is there a meaningful way to combine the variables to get some proxy for mass of beads present.  My initial thought was to standardize each variable (i.e. compute z-score), and then combine (i.e. z-score.Redi + z-score.Bluei).  I recognize that this approach suffers from some problems, and I wonder what other options exists for combining the variables?  In my situation, I want to combine different numbers of variables from 2 or 3 up to about 40 variables.  Thanks in advance for any thoughts.  Best Regards.
Comment: Why would a z-score help? Do you have any kind of guess as to which "beads" are heavier than others? Would the distribution of the number of beads have any relationship to the mass of the beads? (If not, then there is no better solution than just summing them).
Answer: If you have no idea about the weights of bead types, then you can't combine them meaningfully. Period.
Imagine two types of beads one with mass 1 tonn, and the other with a mass 1 mg. Unless you have some additional information about the total weight, there's no way to devise the combined variable. Of course, you always have some idea about the total weight, maybe typical values of total wight. In this case you can come up with a reasonable weights to get a combined variables.
Comment: Thanks.  I may be able to get mass categories (i.e. 0.01 - 0.1 g for Red and 0.001 to 0.01 g for Blue) for a wider range of beads than I have accurate mass information for.  I'll likely have the same problem of no information for some bead types (i.e. maybe there is no mass information for Green beads), and it means reaching out to the cantankerous bead-mass-expert community for insights...

Combining variables


Fail to load ExtractingRequestHandler when running the Solr Quickstart Tutorial

Question: I installed Solr 5.0.0 on OS X 10.10.2 using Homebrew. I am trying to follow the quick start instructions and am getting errors when I try to index a directory of files.
I am able to successfully start the sample Solr server by running
bin/solr start -e cloud -noprompt

as directed by the tutorial. I then try to index a directory of files by running
./bin/post -c gettingstarted docs/

(Note that this has to be done from the libexec subdirectory of the Solr install root.)
I get a server error 500 for every file it tries to add. The relevant stack:
Caused by: org.apache.solr.common.SolrException: Error loading class 'solr.extraction.ExtractingRequestHandler'
    at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:492)
    at org.apache.solr.core.SolrResourceLoader.findClass(SolrResourceLoader.java:423)
    at org.apache.solr.core.SolrCore.createInstance(SolrCore.java:559)
    at org.apache.solr.core.SolrCore.createRequestHandler(SolrCore.java:632)
    at org.apache.solr.core.RequestHandlers$LazyRequestHandlerWrapper.createRequestHandler(RequestHandlers.java:326)
    at org.apache.solr.core.RequestHandlers$LazyRequestHandlerWrapper.getWrappedHandler(RequestHandlers.java:298)
    ... 30 more

The issue appears to be that ExtractingRequestHandler is not on the classpath.
ExtractingRequestHandler is in the solr-cell-5.0.0.jar.
jar tf dist/solr-cell-5.0.0.jar | grep ExtractingRequestHandler
org/apache/solr/handler/extraction/ExtractingRequestHandler.class

It's not clear to me if it needs to be on the classpath of the command doing the posting or the Solr instance. The answer to this question makes it sound like the latter. However, I tried setting
export CLASSPATH=dist/solr-cell-5.0.0.jar

before trying to index the files and saw the same error.
I don't see anything in the tutorial about how to configure this. What is the error and how do I get past it?
Answer: Looks like the problem is incorrect paths in the Solr example configuration. A workaround is to add softlinks from SOLR_ROOT/contrib and dist to the corresponding directories beneath SOLR_ROOT/libexec/contrib
Details here and here.
Comment: First link is broken.


Get Timezone using method FindSystemTimeZoneById not returning proper Timezone object

Question: I am using method to get timezone from TimeZoneId
var timezoneObject= TimeZoneInfo.FindSystemTimeZoneById("UTC");

What I am expecting as
timezoneObject.Id : UTC
timezoneObject.DisplayName :(UTC) Coordinated Universal Time
timezoneObject.StandardName: Coordinated Universal Time
timezoneObject.DaylightName: Coordinated Universal Time

but I am getting result as
timezoneObject.Id : UTC
timezoneObject.DisplayName :UTC
timezoneObject.StandardName: UTC
timezoneObject.DaylightName: UTC

But in case of
var timezoneObject= TimeZoneInfo.FindSystemTimeZoneById("Dateline Standard Time");

its giving desired output.
Comment: Timezone info comes from the registry.  Except for "UTC", [that is intercepted early](http://referencesource.microsoft.com/#mscorlib/system/timezoneinfo.cs,d48f12bc885a787a).  The source code suggests that there might be Windows versions that don't have it in the registry.  Not sure if that is accurate, I could however imagine programmers that solved their datetime problem by editing the registry :)  Feature, not a bug.
Answer: You'll get your desired result by using this method:
var timezoneObject = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(x=> x.Id == "UTC");

Ouput:
timezoneObject.Id : UTC
timezoneObject.DisplayName :(UTC) Coordinated Universal Time
timezoneObject.StandardName: Coordinated Universal Time
timezoneObject.DaylightName: Coordinated Universal Time

From Docs:

The id parameter must correspond exactly to the time zone's registry
  key in length, but not in case, for a successful match to occur; that
  is, the comparison of id with time zone identifiers is
  case-insensitive. If you want to retrieve time zone objects based on
  partial matches, you can write custom procedures that work with the
  read-only collection of TimeZoneInfo objects returned by the
  GetSystemTimeZones method.


An inequality obtained in a minimum point

Question: I'm trying understand the article "The Heat Equation Shrinking Convex Planes" by Gage and Hamilton and I'm get stuck in the proof of Theorem $3.2.1$, specifically, in the proof of this inequality:

$\frac{\partial^2 g}{\partial s_1^2} \frac{\partial^2 g}{\partial s_2^2} - \left( \frac{\partial^2 g}{\partial s_1s_2} \right)^2 \geq 0,$
$\textbf{EDIT:}$
where the left expression on this inequality is evaluated in a minimum point of $g$, $g$ is defined by $g(u_1,u_2,t) = f(u_1,u_2,t) + \varepsilon t$, $f$ is defined by $f: S^1 \times S^1 \times [0,T) \longrightarrow \mathbb{R}$ ($S^1$ is interpreted by the authors like $\mathbb{R}/\mod 2 \pi$), $f(u_1,u_2,t) := |F(u_1, t) - F(u_2,t)|^2$ and $F$ is a parametrization of a closed convex regular curve which trace is contained in $\mathbb{R}^2$.
The parameters $s_1$ and $s_2$ are the parameters by arc length with respect the curve $F$ in the instante $t$ in the points $F(u_1,t)$ and $F(u_2,t)$ respectively.

It is stated that an easy calculation verifies this inequality, but I can't see why this inequality it's true. I know that $\frac{\partial }{\partial s} = \frac{1}{v} \frac{\partial }{\partial u}$ $\left(v = ||\frac{\partial F}{\partial u}|| \right)$. Adopting the following notation to simplify the computations, $v_1 = ||\frac{\partial F}{\partial u_1}||$ and $v_2 = ||\frac{\partial F}{\partial u_2}||$, I found
$\frac{\partial^2 g}{\partial s_1^2} = \frac{\partial^2 f}{\partial s_1^2} = \frac{1}{v_1} \frac{\partial }{\partial u_1} \left( \frac{1}{v_1} \frac{\partial f }{\partial u_1} \right) = \frac{1}{v_1} \left[ \left( - \frac{1}{v_1^2} \right) \frac{\partial v_1}{\partial u_1} \frac{\partial f }{\partial u_1} + \frac{1}{v_1} \frac{\partial^2 f}{\partial u_1^2} \right] = \frac{1}{v_1} \left[ \left( - \frac{1}{v_1^2} \right) \langle \frac{\partial^2 f}{\partial u_1^2},\frac{\partial f }{\partial u_1} \rangle \frac{\partial f }{\partial u_1} + \frac{1}{v_1} \frac{\partial^2 f}{\partial u_1^2} \right]$
$\frac{\partial^2 g}{\partial s_2^2} = \frac{\partial^2 f}{\partial s_2^2} = \frac{1}{v_2} \frac{\partial }{\partial u_2} \left( \frac{1}{v_2} \frac{\partial f }{\partial u_2} \right) = \frac{1}{v_2} \left[ \left( - \frac{1}{v_2^2} \right) \frac{\partial v_2}{\partial u_2} \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_2^2} \right] = \frac{1}{v_2} \left[ \left( - \frac{1}{v_2^2} \right) \langle \frac{\partial^2 f}{\partial u_2^2}, \frac{\partial f }{\partial u_2} \rangle \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_2^2} \right]$
$\frac{\partial^2 g}{\partial s_1s_2} = \frac{\partial^2 f}{\partial s_1s_2} =
\frac{1}{v_1} \frac{\partial }{\partial u_1} \left( \frac{\partial f}{\partial s_2} \right) = \frac{1}{v_1} \frac{\partial }{\partial u_1} \left(
\frac{1}{v_2} \frac{\partial f}{\partial u_2} \right) = \frac{1}{v_1} \left[ \left( - \frac{1}{v_2^2} \right) \frac{\partial v_2}{\partial u_1} \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_1 u_2} \right] = \frac{1}{v_1} \left[ \left( - \frac{1}{v_2^2} \right) \langle \frac{\partial^2 f}{\partial u_1 u_2}, \frac{\partial f}{\partial u_2} \rangle \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_1 u_2} \right]$
Computing $\frac{\partial^2 g}{\partial s_1^2} \frac{\partial^2 g}{\partial s_2^2} - \left( \frac{\partial^2 g}{\partial s_1s_2} \right)^2$, I obtained something plus the Hessian of $f$, I tried compute $\langle \frac{\partial^2 f}{\partial u_1^2},\frac{\partial f }{\partial u_1} \rangle$, $\langle \frac{\partial^2 f}{\partial u_2^2},\frac{\partial f }{\partial u_2} \rangle$ and $\langle \frac{\partial^2 f}{\partial u_1 u_2},\frac{\partial f }{\partial u_2} \rangle$, I tried study the signs of $\frac{\partial v_1}{\partial u_1}$, $\frac{\partial v_2}{\partial u_2}$ and $\frac{\partial v_2}{\partial u_1}$ in order to express $\frac{\partial^2 g}{\partial s_1^2} \frac{\partial^2 g}{\partial s_2^2} - \left( \frac{\partial^2 g}{\partial s_1s_2} \right)^2$ in terms of the Hessian of $f$, because I know that in a minimum point $\det Hess \  f \geq 0$ and I would obtain the inequality desired, but I didnt have success with my attempts. Can anyone help me why this inequality its true?
Thanks in advance!
Comment: It would be helpful if you included some relevant information to make your question self-contained: what are $s_1, s_2, u, v$ and how are they related? Just looking at your question it looks like you're starting with the determinant of the Hessian in the coordinates $s_1,s_2;$ so there should be no calculation necessary at all. What am I missing?
Comment: @AnthonyCarapetis, sorry for don't put all details. I edit the topic and add some details about $g$. I put the link for the article too if you need more details.
Comment: @George I have nothing to contribute to this question, but I think it's interesting and it deserves more attention. Maybe this question will be better received in the Physics StackExchange site. You can either cross post or migrate it over there.
Answer: I realized now that $\frac{\partial f}{\partial u_i} = 0$ for $i = 1,2$ because the derivatives is computed in a minimum point of $g$ (and consequently of $f$), then we have that
$\frac{\partial^2 g}{\partial s_1^2} = \frac{\partial^2 f}{\partial s_1^2} = \frac{1}{v_1} \frac{\partial }{\partial u_1} \left( \frac{1}{v_1} \frac{\partial f }{\partial u_1} \right) = \frac{1}{v_1} \left[ \left( - \frac{1}{v_1^2} \right) \frac{\partial v_1}{\partial u_1} \frac{\partial f }{\partial u_1} + \frac{1}{v_1} \frac{\partial^2 f}{\partial u_1^2} \right] = \frac{1}{v_1} \left[ \frac{1}{v_1} \frac{\partial^2 f}{\partial u_1^2} \right]$
$\frac{\partial^2 g}{\partial s_2^2} = \frac{\partial^2 f}{\partial s_2^2} = \frac{1}{v_2} \frac{\partial }{\partial u_2} \left( \frac{1}{v_2} \frac{\partial f }{\partial u_2} \right) = \frac{1}{v_2} \left[ \left( - \frac{1}{v_2^2} \right) \frac{\partial v_2}{\partial u_2} \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_2^2} \right] = \frac{1}{v_2} \left[ \frac{1}{v_2} \frac{\partial^2 f}{\partial u_2^2} \right]$
$\frac{\partial^2 g}{\partial s_1s_2} = \frac{\partial^2 f}{\partial s_1s_2} =
\frac{1}{v_1} \frac{\partial }{\partial u_1} \left( \frac{\partial f}{\partial s_2} \right) = \frac{1}{v_1} \frac{\partial }{\partial u_1} \left(
\frac{1}{v_2} \frac{\partial f}{\partial u_2} \right) = \frac{1}{v_1} \left[ \left( - \frac{1}{v_2^2} \right) \frac{\partial v_2}{\partial u_1} \frac{\partial f }{\partial u_2} + \frac{1}{v_2} \frac{\partial^2 f}{\partial u_1 u_2} \right] = \frac{1}{v_1} \left[ \frac{1}{v_2} \frac{\partial^2 f}{\partial u_1 u_2} \right]$
Finally, we have the inequality desired
$\frac{\partial^2 g}{\partial s_1^2} \frac{\partial^2 g}{\partial s_2^2} - \left( \frac{\partial^2 g}{\partial s_1s_2} \right)^2 = \left( \left( \frac{1}{v_1} \right)^2 \frac{\partial^2 f}{\partial u_1^2} \right) \left( \left( \frac{1}{v_2} \right)^2 \frac{\partial^2 f}{\partial u_2^2} \right) - \left( \frac{1}{v_1 v_2} \frac{\partial^2 f}{\partial u_1 u_2} \right)^2 = \left( \frac{1}{v_1 v_2} \right)^2 \left[ \left( \frac{\partial^2 f}{\partial u_1^2} \right) \left( \frac{\partial^2 f}{\partial u_2^2} \right) - \left( \frac{\partial^2 f}{\partial u_1 u_2} \right)^2  \right] = \left( \frac{1}{v_1 v_2} \right)^2 \text{Hess} \ f \geq 0$
because the Hessian of $f$ is non-negative in a minimum point.


Syntax diagram confusion

Question: Have a look at the syntax diagram for the escape language:
I read the second set of transitions as follows:

The state transitioned to by the \ symbol can transition to the accepting state if the next symbol is not in the newline or hex digit languages (or in other words, is in any language but the newline or hex digit languages).

The state transitioned to by the \ symbol can transition to a different state if the next symbol is in hex digit language.

Isn't this contradictory?
Comment: Why do you think this is contradictory?
Answer: First off, there is no contradiction in the fact that different symbols lead to distinct states in an automaton. That is the very nature of these devices. So your two assertions do not bear any contradiction.
However, they do not really capture the referenced diagram.

There is no "accepting state" here. The escape graph is only a part of the big graph. If the next symbol after the \ state is not a hex digit or a newline, then the next state is "not newline or hex digit," not an accepting one; railroad/syntax diagrams like this one do not have accepting states at all.
After this, the next symbol will take you out of this part of the diagram to whatever part is entered at the exit point on the right hand side.
The "different state" transitioned to with a hex digit is the state "hex digit."

While this diagram is similar to a finite automaton, it is really something a little different.

Syntax diagram confusion


The Rankine-Hugoniot condition

Question: In this notes, example 5, page 5. It gives an example on how to solve a PDE where characteristics might cross using the Rankine-Hugoniot condition. The example is in an initial-value problem for Burgers' equation $u_t + u u_x = 0$, with piecewise linear initial data
$$
u(x,0) = \phi(x) = \left\lbrace\begin{aligned}
&1 &&\text{if}\quad x<0\\
&1-x &&\text{if}\quad 0<x<1\\
&0 &&\text{if}\quad 1<x
\end{aligned}\right.
$$
I have two questions about it:
1). In my opinion, Rankine-Hugoniot condition is just a necessary condition for the discontinuous points of a solution. How does it guarantee the thing we get is indeed a solution?
2).Using the Rankine-Hugoniot condition we can only calculate the speed of the curve of discontinuities. How do we locate its exact formula?(i.e. how to choose one-point on it). Can we choose any arbitrary point where the characteristics cross?
Answer: If needed, here is a sketch of the characteristic curves in $x$-$t$ plane, which may help to see better what happens:

The solution obtained by the method of characteristics up to the breaking time satisfies $u = \phi (x-ut)$ for $t<1$, i.e.
$$
u(x,t) = \left\lbrace\begin{aligned}
&1 & &\text{if}\quad x \leq t \\
&\tfrac{1-x}{1-t} & &\text{if}\quad t \leq x\leq 1\\
&0 & &\text{if}\quad x\geq 1
\end{aligned}\right.
$$
At the breaking time, the shock speed $s$ is given by the Rankine-Hugoniot condition $s = \tfrac12 (1 + 0)$.
Therefore, after the breaking time $t\geq 1$,
$$
u(x,t) = \left\lbrace\begin{aligned}
&1 & &\text{if}\quad x < 1 +\tfrac12 (t-1) \\
&0 & &\text{if}\quad x > 1 +\tfrac12 (t-1)
\end{aligned}\right.
$$
To your questions:

The Rankine-Hugoniot condition $[\![\frac{1}{2}u^2]\!] = s [\![u]\!]$ is a condition satisfied by discontinuous weak solutions of the Burgers' equation. A weak solution which satisfies the Rankine-Hugoniot condition is not necessarily a solution to the proposed initial-value problem $u(x,0) = \phi(x)$. To be a solution, it must be in agreement with the characteristics equation until they cross, i.e. the fact that $u$ is constant along the curves $u = \phi(x - ut)$. Moreover, since weak solutions are not unique, it must satisfy an additional entropy condition. In the case of Burgers' equation, the Lax entropy condition amounts to the following statement: "if characteristics cross, then a shock-wave arises; but if they separate, a rarefaction wave occurs".
The location of a discontinuity is deduced from the characteristics equation, whereas its speed is deduced from the Rankine-Hugoniot condition. In the present case, a shock occurs at the time $t=1$ (characteristics intersect). Its speed deduced from the Rankine-Hugoniot condition is $s=\frac{1}{2}$.
Comment: @CBBAM Using $u=\phi(x-ut)$ and the piecewise definition of $\phi$ (see also the figure). Consider for instance the first option $\phi(x-ut)=1$ for $x-ut<0$. We have $u=1$ and $x-t <0$ which gives us the first line, etc.
Comment: @CBBAM Yes, that's it!
Comment: My apologies if I am commenting on an old post, but how did you obtain the bounds $x \leq t$, $t \leq x \leq 1$ and $x \geq 1$ for the solution when $t < 1$?
Comment: Thanks! So if I understood correctly, in the scalar case where $u_L > u_R$ or $u_R > u_L$ then we use the theorem which states either we have a rarefaction or a shock and use the corresponding bounds. In this case where the wave is not constant and so there is not an obvious shock we use the method you just described, which is to calculate directly from the original bounds?

The Rankine-Hugoniot condition


Laying out logistic function equation with Euler's number

Question: Sorry for the incredibly basic question. I've not studied maths but need to understand the how to formulate an equation for something I'm revising.
In the image below I cannot get the same result of 0.0924. I'm sure the result is correct but I cannot reproduce it because I don't know how to formulate the equation using a scientific calculator, ie any brackets, order of operations, etc. I have tried so many permutations but just cannot get the right result.
Please could someone lay out how this should be entered into a calculator as I need to use this formula repeatedly.
Using https://web2.0calc.com/
I have tried e(-2.91+6.26*0.01)/1+e(-2.91+6.26*0.01)
and e-2.91+6.26*0.01/1+e-2.91+6.26*0.01
The same on my scientific calculator.
formula image
Comment: Please [edit] the question to show us your best attempt, with whatever parentheses you tried. You should also tell us what kinds of keys your calculator has (for example, is there an exp or ln?). If you need to use this often consider using a spreadsheet, or entering the formula in the google search bar - better than all that keypunching.
Comment: Question edited - thanks
Answer: You typed 0.01 instead of 0.1, left out the power operator ^, and forgot to put brackets around the denominator. The following works:
e^(-2.91+6.26*0.1)/(1+e^(-2.91+6.26*0.1))

Comment: You can paste that line into the linked calculator, or into the google search bar.


Sql Azure Data Sync Agent invalid key error message

Question: Windows 8 64 bit
DAta sync agente ver. 188.8.131.52
Error message  , I tried reinstall 3 times data sync and 4 tiems new agent and new key also.
No prosy or internet fire wall one no other fire wall software also.
Please enter a valid agent key to proceed. The key must be generated from SQL DAta Sync web portal
agent key 16f25226-2a20-49c3-acfc-062057c42b41:gWpFO0NHm4Xq9bw7fLzo8YS49iSowEDQToYpbMCKqFk=
id:LocalAgentUX_Info, rId:, sId:00000000-0000-0000-0000-000000000000, traceLevel:Warning, version:188.8.131.52, methodName:AgentModel_AgentStatusChanged, message:Agent UI stopped polling for the latest status from Microsoft SQL Data Sync Windows service due to errors. Please address any errors displayed in the UI and then restart Microsoft SQL Data Sync Windows service on your machine and Agent UI to resume polling.
Comment: Please edit your question with the available formatting options and make sure you actually ask a 'question'. I can't understand head nor tails of it now.
Answer: This is a common error. You have to change your system's date to match azure server's time.
Go to the Azure Website and check the location of the server, than set your system's date and time to the same location's time zone.
This worked fine for me,
Comment: This worked for me as well. The server time wasn't syncing correctly. I changed from time.windows.com to one of the NIST servers and forced a sync. Then the key was accepted.
Comment: Thanks for that. Saved our bacon ;-) Our server was 6 minutes out for some reason. Changed time and all good.
Answer: If there's no time difference it's also worth checking that the password doesn't contain any special chars like quotes ' and double quotes "
Browser auto-generated passwords might include that without you realising it.