How do I filter the command gcloud container operations list? What's the syntax?

Question: If you have 20 GKE clusters, gcloud container operations list returns too much data.
Google Cloud's official docs lack good examples of how to do filtering:

Their docs just mention --filter=[EXPRESSION], which isn't helpful at all without syntax of what the expressions should look like...
gcloud container operations list --help just mentions see gcloud topic filters for more info, which tries to explain, but it's difficult to understand without examples.

So the question is what should filtering look like?
Answer: export PROJECT=name-of-your-project
export CLUSTER=name-of-your-cluster

gcloud container operations list \
--filter="(targetLink ~ $CLUSTER) AND (2024-01-04)" \
--sort-by=START_TIME --format=yaml --project=$PROJECT

gcloud container operations list \
--filter="(targetLink ~ $CLUSTER) AND (startTime > 2024-01-04) AND (startTime < 2024-01-08)" \
--sort-by=START_TIME --format=yaml --project=$PROJECT

gcloud container operations list \
--filter="(targetLink ~ $CLUSTER) AND (startTime > 2024-01-08T06:18:55.104-08:00) AND (startTime < 2024-01-08T15:18:55.104-08:00)" \
--sort-by=START_TIME --format=yaml --project=$PROJECT

Explanation of Syntax:

--format=yaml ends up improving verbosity (hidden feature), and tells you the accurate name of keys you can filter by.
(that's how I identified targetLink and startTime as a valid keys)
--sort-by=START_TIME is just handy
--filter needs the "double quotes"
"(true boolean expression) AND (true) AND (true)"
--filter="targetLink ~ $CLUSTER"
The ~ acts as a string in value of key
so string "$CLUSTER" is contained within the long string value of key named targetLink
If you have 20 clusters this lets you filter the results to a single cluster :)
--filter="2024-01-04"
This checks for that string in the value of all keys
Let's you check the operations that occurred on a particular day.
--filter="(startTime < 2024-01-06)"
Is also valid and handy if you want to see entries before a particular date. Note the key always has to be on the left, startTime can't be on the right side of the inequality.


How can I clear a TextBox?

Question: I have a pretty decent background in Java and C++, but I'm struggling to do something trivial in C#. I have two TextBoxes: MessageBox and SenderBox. I want to send the text from SenderBox to MessageBox (which is easy), but I want to clear SenderBox once that is done. The following is basically the code that is fired when you press Enter to send the text:
string temp = SenderBox.Text;
SenderBox.Text = "cleared";
MessageBox.Text = temp;

Most programming languages are somewhat procedural or at least execute in some orderly way. Why does C#/WPF for Windows 8 apps seem to defy this standard? You would expect temp to be set equal to the value of SenderBox, first of all. If you look at the code, temp should not equal "cleared" unless that's what SenderBox contains. At that point (line 1), it doesn't. I tried to create a send(msg) function to dereference the weird string, but that didn't change a thing. The following code runs as expected:
string x = "abc";
string y = x;
y = "123";
MessageBox.Text = x;

Can someone enlighten me? Not sure what's going on here.
Comment: Your code works for me, I can not duplicate your problem, which event are you using to process the enter key? Make sure it is not being fired twice.
Comment: This really shouldn't happen... It works here, too.
Answer: If you're not trying to switch the contents of the two boxes, why not just do:
MessageBox.Text = SenderBox.Text;
SenderBox.Text = "cleared";

Comment: Well, I would suggest `MessageBox.Text = string.Copy(SenderBox.Text);` with the caveat that if this works it is a framework bug since they have specified that strings are supposed to be immutable.
Comment: Because it doesn't work for the same reason my code doesn't work. Someone already proposed this then revoked their answer... thanks for trying though.

How can I clear a TextBox?


Is it possible to get $\phi \in S_{16}$ if the order of $\phi$ is 56?

Question: I had an exam of Abstract Algebra today, and one of the questions was: Is it possible to get $\phi \in S_{16}$ if the order of $\phi$ is $56$? If so, give an exam, if not prove it.
$S_{16}$ is simply the permutation group of $16$ elements.
Does someone could enlighten me on this? I did not find answers to this question.
Answer: Hint: if $\sigma, \tau\in S_{16}$ are disjoint cycles, what is the order of $\sigma\tau$ in terms of the orders of $\sigma$ and $\tau$?
Comment: So the answer at this question is no, right?
Comment: Why do you say that?
Comment: I have needed more informations please. An example maybe?
Comment: Take $S_5$ as an example. What is the order of $(1\ 2)$? What is the order of $(3\ 4\ 5)$? And, what is the order of $(1\ 2)(3\ 4\ 5)$? Can you generalize that to your question? (I'm not going to just give you the answer to your question...)


Is there anything similar to AWTListener in JavaFX?

Question: I am looking for a way by which I can capture all events (specifically keyboard/mouse events) in a JavaFX application. Is there anything similar to AWTListener in JavaFX? In Java, by creating a AWTListener and adding it to default toolkit I can capture all the events.
Adding some background
I am involved with Marathon, a test automation tool for Java/Swing applications, and currently in the process of evaluating how complicated it is to add JavaFX support. By design, I do not have access to the JavaFX application itself. For Java/Swing we use javaagent to load Marathon hook into the AUT and use AWTListener to listen for all events. I suspect that something similar should be possible for JavaFX.
Comment: Take a look at the event capture feature on the [ScenicView tool](http://fxexperience.com/scenic-view/), perhaps it's similar to what you want.  I don't know how it works though, or the source code for it.  You could ask the ScenicView developers.  Even if the way ScenicView handles it isn't exactly what you want to do, the developers will probably know a good way to achieve what you want.
Comment: Thanks for the information. Had a look at scenic view and tried to get in touch with the developers without success. A thread on java.net forums gave some information, but that doesn't help. Currently, I am thinking of using java agent instrumentation to  add handlers whenever a node is constructed. I shall post my findings here.
Answer: Not sure how exactly your goal can be achieved, but I would start by taking a look at the EventDispatcher of a Scene.
final EventDispatcher eventDispatcher = scene.getEventDispatcher();
scene.setEventDispatcher( new EventDispatcher()
{
    @Override
    public Event dispatchEvent( final Event event, final EventDispatchChain tail )
    {
        System.out.println( "Dispatching event [" + event + "]." );
        return eventDispatcher.dispatchEvent( event, tail );
    }
} );


Can I run Apache2 and Nginx on the same server with only 1 IP

Question: I recently set up an Ubuntu 12 server (on Rackspace Cloud's next-gen servers). I will be serving about 10 small web apps on this server. Due to how these apps were built, the PHP app need to run on Apache and the Rails apps need to run on Nginx. Rackspace will not allow multiple IPs on a single server. Is it possible to run apache2 and nginx on the same server using the same IP address both on port 80?
The only information I have found involves using nginx to proxy requests to apache for the apache domains. The proxy information I have found mentions only static pages server directly by nginx.
How can I set up my Ubuntu server to run apache2 and nginx on the same server with only 1 IP address?
Comment: What Rails server are you using (passenger, thin, mongrel, etc.)? There's no reason you have to use it in nginx instead of apache, or vice-versa.
Comment: I'm using Thin as the rails server.
Comment: Then you could just have Apache proxy to thin, or have nginx run PHP. No need to have both Apache and nginx.
Comment: I think you can configure both of then on same IP but different ports.
Comment: @ArashMousavi I will need them both on port 80
Comment: @MichaelHampton The problem with running PHP through nginx is that the apps have specific .htaccess criteria that requires apache. For instance, there are 2 wordpress apps/sites and 4 CakePHP apps.
Answer: On the same port? No.
However, both Apache and Nginx had reverse proxy support. So run one of them on port 80 and the other on another port. Then configure the one on port 80 to reverse proxy requests matching a particular format (one possibility is subdirectories) to the other.
Comment: Thanks. Can you explain or provide a guide on how to set up nginx to proxy requests across to apache? As noted, the information I found doesn't explain how to do this using both dynamic rails apps on nginx and php apps on apache: http://blog.ludovf.net/configure-nginx-to-proxy-virtual-hosts-to-apache/
Comment: That article you linked to is exactly what you need. Configure nginx how you normally would for rails and add a location entry for some subpath to proxy to apache.
Comment: I would suggest using nginx as a reverse proxy instead of apache because nginx is light weight. http://www.cyberciti.biz/tips/using-nginx-as-reverse-proxy.html for configuring nginx as reverse proxy
Comment: Thanks. I finally got both servers working using nginx as the reverse proxy and apache2 sitting behind it on 127.0.0.1. I had a few problems with configuration, but this page was a great start: http://www.howtoforge.com/how-to-set-up-nginx-as-a-reverse-proxy-for-apache2-on-ubuntu-12.04


Getting back to the Piano

Question: I am a 20 year old student. I use to play a lot of piano while I was a child, and I was very very good at it, a natural talent even though I didn't like playing the classics at Junior Music School. I was in the school from year 7-13, I was really good at it but my stubbornness got over my head so I stopped playing until the day before when I sat down out of curiosity with a mild will to play again. But it was damn horrible. My hearing is in tact, still perfect as ever, but my aim and coordination on the keypad is nothing more but a disaster after 6 and a half years of not playing and I find it playing different tempos and such with both hands nearly impossible. I would very much love to get back in my former shape when I could play any song I would like and such. If I were to get back in my former shape how long would it take, and how and what should I start practicing again?
Comment: best advice I can give... get  a good teacher.
Comment: When you started learning, you certainly also had trouble coordinating both hands at high tempos and such.  Back up to that point and start learning the same way again, though you can progress faster as it comes back to you.
Answer: I have been through almost the exact same experience. I had piano lessons from ages six to thirteen. When I was thirteen, I quit piano. When I was 19, I had a friend who was studying music and restarted my love of music, and I wanted to get back to playing the piano.
Here's what I did: I went through the university library and found most of the old beginner pieces that I was taught by my piano teacher. I also found some of the more advanced pieces, and I found some old exercises for warmup and technique. I was also able to use the university practice rooms, so I didn't have to buy a piano. Now, you could easily find classical repertoire on IMSLP and you could find a good 88-key keyboard controller and some good software for a lot less than a real piano.
Then I started practicing:

Practice every day! Even if it's only for 15 minutes.
Don't expect to be able to play the most difficult pieces you used to play.
Always warm up with a simple exercise or set of exercises. I use a few of Czerny's Exercises in Passage-Playing.
Start with the simplest beginner pieces - especially if you have any that you used to play. You may master them very quickly in which case you can move on quickly. Or it may take you some time to master the simplest pieces, which means you have a bit more to remember and the pieces are appropriate for you.
Practice each piece you are working on two or three times every day, going slowly enough to make very few or no mistakes.
Start off working on one or two pieces at most. You can build up to three or four over time but pay attention to how you're doing and how much practice time you have.
Keep in mind you are doing this for your own enjoyment, it is a lifelong investment in time, there is no need to hurry and there is no need to ever become "great". Set goals for pieces you would like to play and enjoy the process of learning the pieces even when you can't yet play them the way they sound on your favorite recordings.
If you have the money, there's nothing better for learning an instrument than having a good teacher.
Answer: I too had the same experience with an instrument. I played the Flute in school band beginning from age 11. I continued all the way through high school earning medals and awards for my progressive accomplishments on this instrument. I absolutely loved music, and still do! It was my favorite subject in school and the one class that I always excelled in.
I then went on to college as a Music Ed Major and hit a wall about two years in when I realized my only realistic career option was to teach music in a school (the horror!). I wasn't a fan of school to begin with so I left college and found other work.
I still enjoyed my musical passions and became more interested in singing. I no longer had a reason (at that time) to continue playing the flute so I put it on the shelf for about 15 years and never touched it during that time.
Then one day, after a music friend encouraged me to start playing the flute again, I went home and took it out of the case and when I raised it to my lips nothing but air came out. OMG! Had it been that long? I still remembered the fingerings for most of the notes, but my embouchure and air strength was completely lost.
I immediately picked up the phone and called the local music store to schedule Flute lessons. I was so horrified regarding my loss of ability I believe I started lessons the next day. Three years later, at the encouragement of that same flute teacher, I have been teaching flute lessons for a full year and a half.
How ironic since I was not a fan of school over 30 years ago and couldn't stand the thought of a lifetime of teaching in a school environment. Time changes us and I love the teaching part, but am so happy I can be a mentor without the constraints of a school administration bearing down on my creative spirit.
In addition to the recommendation to find a teacher, get a book called The Musician's Way, by Gerald Klickstein. It has been a source of guidance for me as a musician. Enjoy your revived musical journey with the piano and keep your mind open to anything. Maybe you too will find yourself mentoring young musicians just a short time from now!

Getting back to the Piano


Using glArrayElement with LWJGL

Question: I'm following along with the OpenGL tutorial found here. I'm on chapter 2 right now and it's going over the advantages of using glArrayElement to render objects. Currently, my code is as follows:
glEnableClientState(GL_VERTEX_ARRAY);
    glEnableClientState(GL_COLOR_ARRAY);

    double vertices[] = {100, 200, 0, 200, 100, 0, 100, 100, 0};
    double colors[] = {1, .5, .8, .3, .5, .8, .3, .5, .8};

    DoubleBuffer vertexBuffer = BufferUtils.createDoubleBuffer(9).put(vertices);
    DoubleBuffer colorBuffer = BufferUtils.createDoubleBuffer(9).put(colors);

    glVertexPointer(3, 0, vertexBuffer);
    glColorPointer(3, 0, colorBuffer);

    while(!Display.isCloseRequested()) {

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBegin(GL_TRIANGLES);
        glArrayElement(0);
        glArrayElement(1);
        glArrayElement(2);
        glVertex3d(300, 200, 0);
        glVertex3d(400, 100, 0);
        glVertex3d(300, 100, 0);
        glEnd();

        //Display.sync(60);
        Display.update();
    }

The second triangle, defined explicitly by calls to glVertex3d is rendered fine. Bu the first triangle does not render at all. Am I making a simple mistake?
Comment: Have you considered using floats rather than doubles?
Comment: What is the advantage?
Answer: While scouring for more sample code, I came across a snippet that said you had to "flip each buffer." Adding
vertexBuffer.flip();
colorBuffer.flip();

Right before the while loop solved my problem!

Using glArrayElement with LWJGL


Como aplicar o "goto" no quicksort? (c, c++)

Question: Estou realizando um trabalho para minha faculdade onde pede que um algortimo quicksort seja feito em C, utilizando o "goto" o máximo que puder.
No código abaixo eu apliquei o "goto" até onde meu conhecimento permite, porém gostaria que alguem me ajudasse a aplicar o "goto" no resto do algoritmo.
#include<stdio.h>

void quickSort(int *vetor, int inicio, int fim)
{

int i, j, meio, aux;

init0:

i = inicio;
j = fim;
meio = vetor[(inicio + fim) / 2];

init1:

if (i <= j) {

init2:
if(vetor[i] < meio){
i++;
goto init2;
}

init3:
if(vetor[j] > meio){
j--;
goto init3;
}

if(i <= j)
{
aux = vetor[i];
vetor[i] = vetor[j];
vetor[j] = aux;
i++;
j--;
}

goto init1;

}

if(inicio < j) {
quickSort(vetor, inicio, j);
}

if(i < fim){
//quickSort(vetor, i, fim);
inicio=i;
goto init0;
}

}

int main(){

int arr1[10] = { 55, 44, 32, 11, 68, 97, 92, 30, 62, 74 };
int pivot, j, e, i, aux;

i=0;
j=9;

quickSort(arr1, i, j);

i=0;
inicio3:
if (i<10) {
printf("%d ,", arr1[i]);
i++;
goto inicio3;
}

}

Comment: Eu odeio esses requisitos. Além dele não servir pra nada, não ensinar algo útil, ele depende de interpretação. Quando parar de usar o `goto`? Dá pra você sair enfiando `goto` onde não é estritamente necessário, mas pra que? Eu acho que está bom assim. Na verdade é um código horroroso, mas não é culpa sua, pelo menos em parte.
Comment: Sim, eu também de certa forma acho desnecessário, porém é uma atividade que me foi solicitada. não sei se o professor vai achar o meu código suficiente. Suspeito que ele queira que eu substitue a função pelo "goto" também.
Answer: O goto é um pulo não condicional, pode ser considerado base pra todo controle de fluxo.
Com uma combinação de if e goto você pode criar qualquer controle de fluxo, creio que esse é o objetivo do peculiar exercício.
Embora seu código já esteja reduzido a ifs. Recomendo que você escreva o código de maneira normal e depois substitua os controles de fluxo por construções usando goto (caso não tenha sido assim que resolveu), como nos exemplos:
if / else
if(x==0)
{
    printf("verdadeiro\n");
}
else
{
    printf("falso\n");
}
printf("fim if else\n");

Pode ser representado com gotos:
if(x==0)
    goto if_1; //se o if for verdadeiro, executa essa expressão
    goto else_1; //se for falso, ignora a expressão anterior e executa essa

if_1:
    printf("verdadeiro\n");
    goto fim_if_else1;

else_1:
    printf("falso\n");
    goto fim_if_else1;

fim_if_else_1:
    printf("fim if else\n");

for
Dados:
int a=0;
int b=5;
int x;

O loop:
for(x=a; x<b; x++)
{
    printf("{for entre [%d e %d)} x = %d,  \n", a, b, x);
}
printf("fim [for]\n");

Pode ser explicitado usando gotos:
inicio_for_1:
    x=0;
verifica_for_1:
    if(x<b)
        goto corpo_for_1;
        goto fim_for_1;
corpo_for_1:
    printf("{for entre [%d e %d)} x = %d,  \n", a, b, x);
incremento_for_1:
    x++;
    goto verifica_for_1;
fim_for_1:
    printf("fim [for]\n");

do...while
O código
int x = 5;
do
{
    x--;
    printf("%d\n", x);
}
while(x>0);
printf("fim do{...}while(...)\n");

pode ser representado assim:
inicio_dowhile_1:
    int x=5;
corpo_dowhile_1:
    x--;
    printf("%d\n", x);
verifica_dowhile_1:
    if(x>0)
        goto corpo_dowhile_1;
fim_dowhile_1:
    printf("fim do{...}while(...)\n");

Chamada de função
O C requer a função main, onde o programa inicia. Outras funções podem ser codificada dentro dessa, e os argumentos podem ser declarados como variáveis locais. Você estará emulando uma chamada de função e passagem de parâmetros:
int func1(int x, int y)
{
    return x*y;
}

int main(void)
{
    int r = func1(4,5);
    printf("%d", r);
}

Pode ser representado assim:
int main(void)
{
    //espaço para declarar todas variáveis necessárias
    int func1_argx;
    int func1_argy;
    int func1_resultado;
    int r;

    //equivalente a chamar função:
        func1_argx = 4; //define primeiro argumento
        func1_argy = 5; //define segundo argumento
        goto func1_interna; //~chama função~
    ponto_retorno:  //nomeia ponto de retorno

    //resto do código da main
        r = func1_resultado;
        printf("%d", r);

    goto main_final; //vai para o final do main, ignorando código da função

    //parte reservada para função:
    func1_interna:
        func1_resultado = func1_argx*func1_argy;
        goto ponto_retorno;

    main_final: ;
}

Além de substituir os controladores de fluxo, você pode fazer um código tão complexo e confuso quanto queira, dando origem ao que se chama de código spaghetti, mas não creio que seu professor está querendo algo assim...
Essa resposta tem fins didáticos, procure compreender a equivalência das construções =)
Talvez seu curso vá para linguagens de baixo nível depois... Em nível de hardware os controles de execução são implementados por testes em registradores e pulos, algo diretamente relacionado a ifs e gotos.


django - UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 32: ordinal not in range(128)

Question: Boa noite galera!
estou com o ubuntu 16.04, tentando voltar pro django, ms quando eu tento iniciar um projeto da esse erro aqui:

raceback (most recent call last):
  File "/home/alekys/Envs/test3/bin/django-admin", line 11, in <module>
  sys.exit(execute_from_command_line())
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/init.py", line 353, in execute_from_command_line
  utility.execute()
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/init.py", line 345, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv
  self.execute(args, cmd_options)
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute
  output = self.handle(args, options)
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/commands/startproject.py", line 33, in handle
  super(Command, self).handle('project', project_name, target, options)
  File "/home/alekys/Envs/test3/local/lib/python2.7/site-packages/django/core/management/templates.py", line 162, in handle
  if new_path.endswith(extensions) or filename in extra_files:
  UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 32: ordinal not in range(128)

usando virtualenv, baixei o django 1.9.7
alguém que possa me ajudar? já tentei varias coisas que achei pela net, até remover e instalar novamente o python 2.7
desde já agradeço!
Answer: Segundo essa resposta o que está acontecendo é. No path do seu projeto existe algum caracter que o django não consegue processar.
Exemplo:
/home/usuario/AndrÀ/projetos/

nesse caso o Django não será capaz de processa o caracter À. Esse foi o erro similar que foi encontrado. Se possível publique qual é o path que você está tentando criar o projeto.
Como o código que não pode ser decodificado é o 0xc3, você possui um caracter À
Comment: esse é o PATH: /home/alekys/Envs/test1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

criei um ambiente virtualenv, usando virtualenvwrapper
export WORKON_HOME=~/Envs
source /usr/local/bin/virtualenvwrapper.sh
Comment: quando eu digo path, não é a sua variavel de ambiente PATH. Mas sim o caminho que você está tentando criar o novo projeto. Qual é o caminho que você está tentando criar o projeto? E qual  o nome que você está dando ao projeto?
Comment: /home/alekys/Documentos/Programação/Django nome do projeto é test
deve ser a pasta Programação, vou testar em outra pasta.
vlw cara!
Comment: provavelmente é isso. Espero que tenha resolvido


RHEL6 - Fips140-2 - Apache fails when trying to start with SSLFIPS on directive

Question: Hello server warriors!
I have a situation where I need to make my RHEL6 system FIPS140-2 compliant...which includes apache and mod_ssl.  However, after I make the server run in "fips 140 mode" Apache does not recognize the SSLFIPS directive...and fails with the following error:
<code>Invalid command 'SSLFIPS', perhaps misspelled or defined by a module not included in the server configuration
</code>
I installed mod_ssl from yum.  This is a subscribed RHEL6 system...and is wired into RHN.
Answer: Ok...
So after much searching and some time spent with some professional support staff, turns out mod_ssl is not "approved" for use on a fips 140-2 enabled system.
In order to have SSL, you must leverage mod_nss instead.
Comment: How to use in Redhat 4/5 system? or how to compile apache to use `mod_nss`
Comment: I'm assuming you mean RHEL 4 or RHEL 5?  I would think mod_nss would be in the base repos for at least RHEL 5.


Commutative and associative exponentiation

Question: As you know, exponentiation as a binary operation is neither commutative nor associative: $$a^b \neq b^a$$ in general and $$(a^b)^c \neq a^{(b^c)}$$But we can, with a little poking around, find a "commutative version" of exponentiation. Indeed, by defining $$a \wedge b = (a+b)^{ab+1}$$we see that we have generalised exponentiation to a commutative operation (we can write every exponentiation as a $\wedge$ and every $\wedge$ as an exponentiation, the neutral element of this new operation is $0$ and the inverse of $a$ is $-a$). My question is then: is it possible to determine such a procedure to give exponentiation associativity? And if so, is it possible to do so while preserving commutativity, and why not even distributivity with respect to multiplication? If it is impossible, what are the reasons?
Comment: It's not clear to me what "generalized exponentiation" means here. You've given the summary "we can write every exponentiation as as $\wedge$ and every $\wedge$ as an exponentiation," but this is pretty vague: to express $a\wedge b$ in terms of exponentiation we need to use additional operations (namely addition, multiplication, and a constant for $1$), and in the other direction I don't actually see a way to express $a^b$ in terms of $a\wedge b$ in any nice way.
Comment: Not in a "nice way" that's true, but this is not necessary
Comment: Actually I don't immediately see *any* way to do it. What method do you have in mind?
Comment: Well you can solve the equation $a \wedge b = c^d$, in other words : $$\frac{c-\sqrt{c^2-4d+4}}{2} \wedge \frac{c+\sqrt{c^2-4d+4}}{2} = c^d$$is an example of solution
Answer: Define $a\land b:=a^{\ln b}$. Then
$$a\land (b\land c)=a\land b^{\ln c}=a^{\ln(b^{\ln c})}=a^{\ln b \ln c}=\left(a^{\ln b}\right)^{\ln c}=a^{\ln b}\land c=(a\land b)\land c,$$
so we have associativity. We have commutativity as well:
$$a\land b = a^{\ln b}=e^{\ln(a^{\ln b})}=e^{\ln a \ln b}=e^{\ln (b^{\ln a})}=b^{\ln a}=b\land a.$$
For the identity element, we have $e$, and the inverse elements $a^{-1}=e^{1/\ln a}$.
Finally, distributivity over multiplication? Yes:
$$a\land (b\cdot c)=a^{\ln(b\cdot c)}=a^{\ln b+\ln c}=a^{\ln b}\cdot a^{\ln c}=(a\land b)\cdot(a\land c).$$


CSS/JS - Force a line break at a comma in comma separated list

Question: I have a table cell in which there is list of aircraft registration numbers in the format 'X-XXXX'. The width of the table cell means that the list gets word-wrapped on the hyphen, like so:
G-ABCD,G-
EFGH,G-
IJKL

What I'd like to happen is that the line-break is forced on the comma:
G-ABCD,
G-EFGH,
G-IJKL

However, I cannot insert any special characters. This is because when the form is submitted, the data in the table is submitted as JSON format which is then json_decoded in PHP. Any special characters in the comma separated string then stops the json_decode function from turning it into an array.
So I really need a solution that does not alter the list in anyway? Sounds impossible...
Comment: Can you affect the width of the cell / column. If you shrink it down it will force the line break after the comma anyway, wouldn't it?
Comment: Would using the non-breaking hyphen `‑` be a solution here ?
Comment: ...and shouldn't each tail number be in a separate cell?
Comment: Each row is for a part - then this cell lists all the aircraft that part is used on, so separate cells isn't an option.
Comment: The problem I have with using special characters like ‑ is that I'd need to insert them when the datatables.editor does the .join. If I use a special character, when I do the json_encode I get field:"G-ABCD,‑,"G-EFGH‑,"
Where as I really need field:["G-ABCD","G-EFGH"]
Comment: I seem to have got it working with a combination of padding and this answer: http://stackoverflow.com/questions/14190420/firefox-word-break-breaks-short-words-at-random-points/14191114#14191114

However it seems a bit hacky. For instance if the number of characters in the registration number ever increases this fix won't work.

Not sure there is a better solution other than to add another column in the datatable for display purposes only.
Answer: To force a line break, use the
 tag. If you cannot have it in the HTML markup, add it with JavaScript.
This answers the question asked. The actual problem is probably different. You need to post more code and ask differently to have it solved. What is the context, what are the constraints, and what do you actually want to do? (From the discussion in the comments, it seems that you rather want to prevent line breaks after hyphens than force any breaks.)


Programmatically get View Custom Text

Question: I created a view with a "Custom text" field and want to get this field programmatically in Drupal 8.
I have:
$view = Views::getView('my_view');
$view->execute();
foreach($view->result as $row){
    $node = Node::load($row->nid);
    // Get here the view custom field with label "An example view field".
}

The $row field doesn't have the fields, nor the $node.
A screenshot of the view:

I now have:
$customField = $view->field['nothing'];

customField is an instance of Drupal\views\Plugin\views\field\Custom.
dpm($customField->render($row));

This returns class Drupal\views\Render\ViewsRenderPipelineMarkup with protectecd string with the same markup: {{ title }} test.
Thanks,
Answer: You should have something like
//already loaded
$node = $row->_entity;

Best way to get properties easily is probably to inspect variables with xdebug
If it is some king of header/footer, you can get the rendered array this way :
$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header); // $view->header['area'] or something else
$rendered = $area->render(); // rendered array

Ok, then :
$view = \Drupal\views\Views::getView('YOUR VIEW');
$view->execute('YOUR DISPLAY ID OR DEFAULT');
$nothing = $view->getHandler('YOUR DISPLAY ID OR DEFAULT','field', 'nothing');
$text = $nothing['alter']['text'];

Comment: Could you get nid with $row->_entity->id() ?
Comment: No way to get the information from _entiity using print_r (memory exhausted). Something with bundle perhaps.
I require something like \Drupal::entityManager()->getFieldDefinitions($entity_type_id, $bundle), but for views.
Comment: You should be able to get your text with something like : $row->_entity->get('field_text')->value, what about the id above ?
Comment: I understand, you are not requiring $node's custom text but views custom text, right ?
Comment: Hi, correct. When I inspect in the elements (HTML) of the results in view, I got "nothing" as unique class. There should be a way to get that "nothing" field value.
Comment: If it is some king of header/footer, you can get the rendered array this way :

$view = \Drupal\views\Views::getView('Your view');
$view->execute();
/* @var $area \Drupal\views\Plugin\views\area\Text */
$area = reset($view->header);
$rendered = $area->render();
Comment: Easier to help you with screenshot, try this.
Answer: Please install the devel module
Go to /drupal8/devel/php
You can try:
$view = \Drupal\views\Views::getView('my_view');
$view->execute();

foreach($view->result as $row){
dpm($row->_entity->get('Custom text')->getValue());
}

note: change "Custom text" by machine name of the field
if your result is similar to:
Array
(
    [0] => Array
        (
            [value] => 43
        )

)

you can access the field with
$row->_entity->get('Custom text')->value

if your result is similar to:
Array
(
    [0] => Array
        (
            [target_id] => 1
        )

)

you can access the field with
$row->_entity->get('Custom text')->target_id

Comment: Hi, I want to get the custom field of the row generated by the field. Not the field of the node itself. See screenshot in my post.
Comment: @s3go11, i feel your pain. I am trying to find the D8 version of views_get_view_result (which exists in D8 but doesn't do anything useful like in D7). All the answers here referring to $node; do not understand the question.
Answer: You can also use hook_preprocess_views_view_field in order to change your custom text field:
function hook_preprocess_views_view_field(&$variables) {
  if ($variables["view"]->id() == "VIEW_ID" && $variables["field"]->options["id"] == "nothing") {
    $doYourCalculation = "New Text";
    $variables["output"] = ViewsRenderPipelineMarkup::create($doYourCalculation);
  }
}

Answer: This is what I have, however, I feel there must be a better way to do this.
Some notes:

$view->render(); is critical, without it, it doesn't work
'nothing' is the default name of custom field, adding additional fields will result 'nothing_1', 'nothing_2', etc. You can see the name when hovering over the field (in the link) or in the replacement patterns.
The value returned with a lot of \n in it. I'm replacing them here, but this can have unwanted side effects.

The code:
// The machine name of your view.
$viewname = 'name_of_the_view';

// Get the view.
$view = \Drupal\views\Views::getView($viewname);

// Display machine name.
$view->setDisplay('default');

// Execute the view.
$view->preExecute();
$view->execute();
$view->render();

foreach(array_keys($view->result) as $row_index){
  $custom_field = str_replace("\n", '', $view->field['nothing']->tokenizeValue((string)$view->field['nothing']->original_value, $row_index));
}

Answer: I had a similar problem and the only way worked for me was the following:
function MODULENAME_preprocess_views_view_fields(&$vars) {
  $view = $vars['view'];
  if(isset($view) && $view->id() === 'test') {
    foreach ($view->field as $id => $field) {
      // change the global custom text content for a specific
      // result row.
      if ($vars['row']->nid == 149) {
        $vars['fields']['nothing']->content = 'some new text';
      }
    }
  }
}

Comment: The posted question is how to get a view's rendered field in code. Not within a view's hooks.
Answer:   $view = \Drupal\views\Views::getView( 'view_name' );
  $view->execute();
  foreach ($view->result as $row) {
  kint($row->_entity->get( 'nid' )->getValue()[0]['value']);
  }

Comment: Hey, could you please add some explanation of what this code actually does. Or what else you are trying to suggest. It's hard to distinguish if you have the same problem or if this is an actual answer ;)

Programmatically get View Custom Text


EF 4.1 Code First complex type with inheritance TPH

Question: Is it possible to use a complex type of inheritance TPH in EF 4.1?
    [ComplexType]
    public class Unit
    {
        public double Value { get; set; }

        public Unit() { }

        public Unit(double Value)
        {
            this.Value = Value;
        }
    }

    public class Celsius: Unit
    {
       public Celsius(double Value) : base (Value)  { }

       public static explicit operator Kelvin(Celsius c)
       {
         return new Kelvin(c.Degrees + 273.16d);
       }

       [NotMapped]
       public double Degrees
       {
         get { return this.Value; }
       }
    }

I use in this class association one-to-one:
When I invoke() SaveChanges() raise Exception
public class Measurement
{
    [Key,
     Column("Id"),
     DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public DateTime MTime { get; set; }
    public Unit Value { get; set; }
}

and Context:
class TestContext : DbContext
{

    public DbSet<Measurement> Measurements { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        try
        {
            modelBuilder.ComplexType<Unit>().Property(u => u.Value).HasColumnName("Value");

            modelBuilder.Entity<Unit>()
                        .Map<Celsius>(m => m.Requires("TypeName").HasValue("Celsius"))
                        .Map<Kelvin>(m => m.Requires("TypeName").HasValue("Kelvin"));
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
    }
}

Is it possible to use complex types with inheritance one-table-hierarchy in the FE 4.1 code first?
Answer: OK, I tested in EF 5 beta, however I think this should work the same. This is sort of a workaround, but one you might be able to live with. The discriminator portion does not seem to work when this is a complex type, so I initialized it in the respective constructors.
I have this and it works:

public class Measurement
{
    [Key,
        Column("Id"),
        DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public DateTime MTime { get; set; }
    public virtual Unit Value { get; set; }
}

[ComplexType]
public class Unit
{
    protected Unit()
    {
    }

    protected Unit(double value)
    {
        Value = value;
    }

    [Column("Value")]
    public double Value { get; set; }

    [Column("TypeName")]
    public string TypeName { get; set; }
}

public class Celsius : Unit
{
    public Celsius(double value) : base(value)
    {
        TypeName = "Celsius";
    }

    public static explicit operator Kelvin(Celsius c)
    {
        return new Kelvin(c.Degrees + 273.16d);
    }

    public double Degrees
    {
        get { return this.Value; }
    }
}

public class Kelvin : Unit
{
    public Kelvin(double value) : base(value)
    {
        TypeName = "Kelvin";
    }

    public static explicit operator Celsius(Kelvin k)
    {
        return new Celsius(k.Degrees - 273.16d);
    }

    public double Degrees
    {
        get { return this.Value; }
    }
}

class TestContext : DbContext
{
    public DbSet<Measurement> Measurements { get; set; }
}

Here is the migrations code for this to see what is generated in the DB:

public partial class Initial : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Measurements",
            c => new
                {
                    Id = c.Long(nullable: false, identity: true),
                    MTime = c.DateTime(nullable: false),
                    Value = c.Double(nullable: false),
                    TypeName = c.String(),
                })
            .PrimaryKey(t => t.Id);

    }

    public override void Down()
    {
        DropTable("dbo.Measurements");
    }
}


Exporting comments only from one drupal site to another

Question: How can i export only comments from a Drupal Site (Live) to a Drupal site (Dev).
The content of both sites is same. The live site only has new users and comments. I already exported the users and imported into Dev Site.
I looked into many modules but non on them only allow comments to be exported. Can i simply copy some MySql tables ?
thanks
Answer: Assuming you are using Drupal 7.
Use the Views module and create a table view of node comments.
Add fields: Node ID (nid), Comment ID (cid), Comment Title, Comment Body, Commment Author, Created Date.
For export, use Views Data Export and export the CSV file.
For import, use the Feeds module + Feeds Comment Processor and import your CSV.
Checkout this Feeds Video Tutorial (this is for nodes, not comments, but it will give you an idea on how feeds with the CSV import works).
--
Exporting MySQL tables approach:
Never done it like this, but if I were you, I would look for all the tables that have the name comment, export those and import.
Note sure if it will work as simply as that, but worth a try.
Comment: perfect, works like a charm. (y)
Comment: @brainHax just wondering, which method did you use?
Comment: the first one. Views , feeds and data export.
Comment: What about Drupal 8?
Comment: @Progonat you'll need to use the [Migrate API](https://www.drupal.org/docs/8/api/migrate-api). I highly suggest you watch youtube videos about it, it can be hard to grasp from just reading the docs.


Storing ajax callback variables in PrivateTempStore

Question: I have an issue with changing / obtaining variables in form element's ajax callback function. (Sorry for typos, I just placed a pieces of whole code).
I have form with input field, where user can select how many pieces of each product he want
$form['wrapper_amount']['value'] = [
        '#type' => 'number',
        '#prefix' => '
',
        '#suffix' => 'pcs
',
        '#name' => "amount--product-1",
        '#ajax' => [
            'callback' => '::calculatePricePerUnit',
            'event' => 'change',
            'disable-refocus' => TRUE,
            'progress' => [
                'type' => 'fade',
                'message' => NULL,
            ],
        ],
    ];

after choosing a number I calculate price using AJAX callback function and using
public function calculatePricePerUnit(array &$form, FormStateInterface $form_state)
{
    // ... price calculation for specific product
    // $new_price = (amount * price_per_unit);

    $total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
    $response = new AjaxResponse();
    $response->addCommand(
        new InvokeCommand(
            '#total-price',
            'html', [$form_state->get('total_price_with_vat') . ' €']
        )
    );
}

The problem is that when used add amount to second product the $form_state->get('total_price_with_vat') is 0 again. It means that I cant store $total_price variable in $form_state, because it's not persistent (I've already read this somewhere, that I can't store variables to $form_state in AJAX callback function). So I tried to store it to $form_state->setStorage($my_values) but it didn't work either.
Please note that all AjaxResponse commands are working and I only need to find best approach how to store data, not how to re-render form's elements.
My next step is to store data in PrivateTempStore, but question is, if it's good approach?
I don't need data on any other Wizard page, neither in Controller or any further step. I just need to calculate $total_price and some other data that I need to use multiple times in AJAX callback function, and at the end use webform API to send webform submission results via email.
Comment: Don't do form logic in an ajax callback. Move the code to form build and check $form_state->getTriggeringElement(). About storing values, $form_state works, but is a bit tricky to get started because the initial value isn't stored in the form cache.
Comment: Thanks for your reply. I'll redesign my form functionality and post answer, when it's done.
Answer: PrivateTempStore is not the right fit for this. You want to store the value in the $form_state, but you do not store it in the AJAX callback, you store it in the submit handler, then set the form to rebuild (which will persist the values in the storage. You can set a custom #submit handler on your ajax submit button that is only called when that button is clicked:
$form['wrapper_amount']['value'] = [
  '#type' => 'number',
  '#prefix' => '
',
  '#suffix' => 'pcs
',
  // note - #name is commented out, as you should never
  // need to change it in Drupal, and doing so will have
  // unexpected consequences.
  // '#name' => "amount--product-1",
  '#ajax' => [
    'callback' => '::calculatePricePerUnit',
    'event' => 'change',
    'disable-refocus' => TRUE,
    'progress' => [
      'type' => 'fade',
      'message' => NULL,
    ],
  ],
  '#submit' => ['::customSubmit'],
];

Then your custom submit will look like this:
public function customSubmit(array &$form, FormStateInterface $form_state) {
  $total_price = (float)$form_state->get('total_price_with_vat') + $new_price;
  $form_state->set('total_price', total_price);
  $form_state->setRebuild(TRUE);
}

After playing around with this a little, I can see that a submit button is required to be able to call a submit handler where rebuildForm() can be recalled. If you set the #ajax on a non-submit button, ajax is called, but rebuildForm() is not able to be called.
As such, I'd say the hack for this is to create an #ajax submit button as I've shown above, but hide it. Then add some custom JS on the number field, that on blur triggers a click of the hidden submit button.
Comment: I do not have a button. I want to change $total_price on ['#ajax']['event'] = 'change'. If possible. As far as I know, I cant use ['#submit'] attribute on ['#type'] = 'number'.
Comment: You can put this in the 'submitForm()' method of the form then, instead of a custom submit handler.
Comment: is there any way how to calculate price and display it to user without any need to click some kind of button?
Comment: Is what you've done above not doing that?
Comment: No properly. I can calculate partial prices for each product but therefore I cant sum & store partial prices to one $total_price I cant reach wanted functionality.
Comment: Please refine your original question, as it's now unclear what you're asking.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/105343/discussion-between-patrick-star-and-jaypan).
Comment: Based on your answers my question is if I can implement functionality that I change form_state variables via AJAX that is triggered by form element of type 'number' / 'checkbox' (not submit button).
Comment: I've updated my comment after playing with this a little.
Comment: Yes, thanks. I realised after our discussion that only way to do this is call JS function in ajax callback using $response->addCommand(new InvokeCommand(...)) to trigger (hidden) button submit handler. I'll post my solution once I've done it.
Answer: Ok, according to answers, I updated my question. Can I update $form_state values when triggering AJAX event on form element that is not type of 'submit' / 'button'?
$form['wrapper_amount']['value'] = [
    '#type' => 'number',
    '#title' => $this->t('Enter amount of product'),
    '#ajax' => [
        'callback' => '::calculatePricePerUnit',
        'event' => 'change',
        'disable-refocus' => TRUE,
        'progress' => [
        'type' => 'fade',
        'message' => NULL,
        ],
    ],
];

This is code for my input type="number" and every time user changes amount of product I want to call AJAX and update $total_price. I'm summing up $total_price each time user updates amount of product in form (there are multiple product in form). But I can't update $total_price correctly, because I need to store it somewhere to obtain it next time, when user changes amount of product, so I can sum another price to it.
Is this possible somehow without having user to click every time on button to submit form to calculate price?
Comment: Whatever happened to store it inside `$form` ?


Why not mapper/reducer for hadoop TeraSort

Question: I am planning to insert some code into the mapper of the TeraSort class in Hadoop 0.20.2. However, after reviewing the source code, I cannot locate the segment that mapper is implemented.
Normally, we will see a method called job.setMapperClass() which indicates the mapper class. However, for the TeraSort, I can only see thing like setInputformat, setOutputFormat. I canno t find where the mapper and reduce methods are called?
can any one please give some hints about this? Thanks,
The source code is something like this,
public int run(String[] args) throws Exception {
   LOG.info("starting");
   JobConf job = (JobConf) getConf();
   Path inputDir = new Path(args[0]);
   inputDir = inputDir.makeQualified(inputDir.getFileSystem(job));
   Path partitionFile = new Path(inputDir, TeraInputFormat.PARTITION_FILENAME);
   URI partitionUri = new URI(partitionFile.toString() +
                           "#" + TeraInputFormat.PARTITION_FILENAME);
   TeraInputFormat.setInputPaths(job, new Path(args[0]));
   FileOutputFormat.setOutputPath(job, new Path(args[1]));
   job.setJobName("TeraSort");
   job.setJarByClass(TeraSort.class);
   job.setOutputKeyClass(Text.class);
   job.setOutputValueClass(Text.class);
   job.setInputFormat(TeraInputFormat.class);
   job.setOutputFormat(TeraOutputFormat.class);
   job.setPartitionerClass(TotalOrderPartitioner.class);
   TeraInputFormat.writePartitionFile(job, partitionFile);
   DistributedCache.addCacheFile(partitionUri, job);
   DistributedCache.createSymlink(job);
   job.setInt("dfs.replication", 1);
   // TeraOutputFormat.setFinalSync(job, true);
   job.setNumReduceTasks(0);
   JobClient.runJob(job);
   LOG.info("done");
   return 0;
 }

For other classes, like TeraValidate, we can find the code like,
job.setMapperClass(ValidateMapper.class);
job.setReducerClass(ValidateReducer.class);

I cannot see such methods for TeraSort.
Thanks,
Answer: Why should a sort need to set the Mapper and Reducer class for it?
The default value is the standard Mapper (former identity Mapper) and standard Reducer.
These are the classes you usually inherit from.
You can basically say, that you're just emitting everything from the input and let Hadoop do its own sorting stuff. So sorting is working by "default".
Answer: Thomas answer is right i.e mapper and reducers are identity since shuffled data is sorted before applying your reduce function . Whats special about terasort is its custom partitioner (which is not default hash function). You should read more about it from here Hadoop's implementation for Terasort. It states
"TeraSort is a standard map/reduce sort, except for a custom partitioner that uses a sorted list of N − 1 sampled keys that define the key range for each reduce. In particular, all keys such that sample[i − 1] <= key < sample[i] are sent to reduce i. This guarantees that the output of reduce i are all less than the output of reduce i+1."


Eigenvalues of a $3\times3$ orthogonal matrix

Question: Can anyone give me an example of 3x3 orthogonal matrix with complex eigenvalue.
Comment: $i\cdot\mathcal I_3$ ?
Comment: It's actually rather German :)
Comment: The English terms are eigenvalue (http://en.wikipedia.org/wiki/Eigenvalues_and_eigenvectors) and characteristic polynomial (http://en.wikipedia.org/wiki/Characteristic_polynomial).
Comment: thank you, i will correct my post :)
Answer: Example. Let
$$
U=\left(\begin{matrix}1&0&0\\ 0&0&1\\0&-1&0 \end{matrix}\right).
$$
Then, $U$ is orthogonal and its characteristic polynomial is
$$
p(\lambda)=\det\,\left(\begin{matrix}1-\lambda&0&0\\ 0&-\lambda&1\\0&-1&-\lambda \end{matrix}\right)
=-(\lambda-1)(\lambda^2+1).
$$


How to cancel multiple user accounts and keep their content without using built-in admin GUI?

Question: How do I cancel/delete multiple user accounts without deleting content created by those users and without using the built-in admin GUI?
Ideally if there was a way via VBO or rules or any related modules that would be awesome.
Comment: why wouldn't you want to use the gui?
Comment: Be careful using VBO to delete users. If you use 'Delete item' on a user based view, it will delete those users and _all_ their content by default ( see https://drupal.org/node/1885294 ).
Comment: use admin gui, not VBO, and just block users, do not delete them, you willl keep all data and users won't  have access.
Comment: https://gist.github.com/hannesl/3864416
Answer: You can check out some of these things.
Please test this before using it on your real build.
Delete All module

This module is used to delete all content and/or users from a site. This is mainly a developer tool, which can come in handy in several
    cases, listed below.

The usual way to do this is to go to Administer -> Content then select
  all the nodes and delete them. This works if you have a handful of
  nodes only. If you have hundreds or thousands of nodes, then it is not
  a practical solution.
Another option is to directly delete the nodes from the node table in
  the database. This does not work properly, since there are also
  comments, and many tables for add on modules that needs to be cleaned.
This is a test site that the client was using for a period of time,
  and they must clean it up before starting with real data. You are
  testing something that creates a lot of nodes (e.g. aggregator), and
  want to do it over and over again. You created a site in the past and
  want to replicate it again, but with new content. Note that for nodes,
  comments and all additions to nodes that contributed modules may have
  added. For users, any additional module data will also be deleted.

but you can also use Drush and this command drush delete-all users


dotnet pack (.NET 5) creates extra folder for files with no extension when packing staticwebassets

Question: dotnet pack creates extra folder for files with no extension when packing staticwebassets.
Example:
if there is a file in wwwroot/myfolder/myfile it packs it as wwwroot/myfolder/myfile/myfile
The package .props however contains the correct original path and structure. This effective prevents publishing projects what have package reference to this package, because during the publish the msbuild task mislead by the .props file list and gives for example:

Error MSB3025: The source file "C:\Program Files\dotnet\sdk\5.0.101\Sdks\Microsoft.NET.Sdk\targets\Microsoft.NET.Publish.targets(237,5): C:\Users\myname.nuget\packages\thepackage\1.0.0\staticwebassets\assets\libs\flot-charts\Makefile" is actually a directory. The "Copy" task does not support copying directories.

Can anyone suggest a workaround (besides of deleting or renaming the files)?
Comment: Any update about this issue?
Answer: It seems that there is something wrong with Copy Task from your <packages_id>.props file,
Copy task should work with files rather than a folder, so you should use this:
    <ItemGroup>
           <File Include="$(MSBuildThisFileDirectory)xxx\staticwebassets\assets\libs\flot-charts\Makefile\*.*"></File>
    </ItemGroup>

<Target Name="xxx" AfterTargets="xxx">
     <Copy SourceFiles="@(File)" DestinationFolder="xxx"></Copy>

</Target>

Comment: Perry the .props file is auto generated, if there is an error in it, that is the issue itself. If have no artifacts in my projects related to how to create packages, only the csproj files. The whole process uses all defaults,  and the pure dotnet pack command
Comment: Did you use a razor class library project? Not sure that what your project type is and your detailed situation. You should provide more steps about your situation to help us troubleshoot the issue. Maybe you could share a small sample with github. Besides, you should set `Build Action` of the files under `wwwroot` folder from your project to `Content`.


Show that $A_n= {\{x \in [a,b] : \exists y \in [a,b]\, |x−y| < \frac{1}{n} \ \text{and} \ F(y)−F(x) < p(y−x)}\}$ is open.

Question: In the proof of Lemma 7.17 from Bruckner's Real Analysis, it is claimed without a proof the following :

Let $F$ be continuous on $[a,b]$. For $n \in \mathbb{N}$ and $p \in \mathbb{R}$, let
$$A_n= {\{x \in [a,b] : \exists y \in [a,b]\, |x−y| < \frac{1}{n} \text{ and } F(y)−F(x) < p(y−x)}\}.$$
Since $F$ is continuous, each of the sets $A_n$ is open.

How $A_n$ is open?
Answer: Given any $y \in [a, b]$, let $F_y : [a,b] \setminus  \{y\} \rightarrow \Bbb R $ be defined by $F_y(x) = \frac{F(y) - F(x)} { y-x}$. Note that $F_y$ is a continuous  function.
Now, let $x \in [a,b]$ and suppose $\exists y \in [a,b]\ \text{s.t.} |x−y| < \frac{1}{n} \ \text{and} \ F(y)−F(x) < p(y−x)$. Clearly $y \ne x$, otherwise
$$ 0= F(x)−F(x)<p(x-x)=0$$ Contradiction. So
\begin{align*} A_n&= \{x \in [a,b] : \exists y \in [a,b]\ \text{s.t.} |x−y| < \frac{1}{n} \ \text{and} \ F(y)−F(x) < p(y−x) \} = \\
& = \{x \in [a,b] : \exists y \in [a,b] \ \text{s.t.} |x−y| < \frac{1}{n} \ \text{and} \ F_y(x)< p \} = \\
&=  \{x \in [a,b] : \exists y \in [a,b] \ \text{s.t.} x \in B\left (y,\frac{1}{n} \right) \ \text{and} \ x\in  F_y^{-1}((-\infty, p ))\} = \\
&=\bigcup_{y \in [a,b]} \left (  B\left (y,\frac{1}{n} \right) \cap F_y^{-1}((-\infty, p ))  \right )
\end{align*}
Since $ B\left (y,\frac{1}{n} \right)$  is open in $[a,b]$ and $F_y^{-1}((-\infty, p ))$ is open in $[a,b] \setminus \{x\}$ which is open in $[a,b]$, we have that $ B\left (y,\frac{1}{n} \right)$  and $F_y^{-1}((-\infty, p ))$  are open in  $[a,b]$. So, $A_n$ is open in $[a,b]$.
Comment: Thanks a lot, Ramiro :)


How do I show that if $f$ is bounded and integrable on $\mathbb{R}$, then $g(t) = \int_t^{t+1} f(x) dx$ is continuous?

Question: Usually functions of the form of $g(t)$ tell me I should use the fundamental theorem of calculus, but I don't think that applies here because I'm not given that $f$ is continuous.
I know from the definition of continuity that I need to show for some $\epsilon$ and some $x \in \mathbb{R}$, there exists a $\delta$ such that if $|x - y| < \delta$, then $|g(x) - g(y)| < \epsilon$.
$f$ is bounded, so there is some $M$ so that $f(t) < M$ for all real numbers $t$. Also, since $f$ is integrable, I can find two sequences of partitions $P_{x,k}$ and $P_{y,k}$ so that

$\lim_{k \to \infty} |P_{x,k}| = 0$ and $\lim_{k \to \infty} |P_{y,k}| = 0$, and
$\int_x^{x+1} f = \lim_{k \to \infty} U(f, P_{x,k})$ and $\int_y^{y+1} f = \lim_{k \to \infty} U(f, P_{y,k})$.

For any $k \in \mathbb{N}$, the sequences $P_{x,k}$ and $P_{y,k}$ may have different numbers of points, so I used $N_x$ and $N_y$ for these numbers of points, for some arbitrary $k$.
Ploughing onwards, I tried to work out what my $\delta$ should be be working backwards from the definition of continuity, but that gave me this:
\begin{align}
|g(x) - g(y)|
&= \left| \int_x^{x+1} f(u)du - \int_y^{y+1} f(u)du \right| \\
&= \left| \lim_{k \to \infty} (U(f, P_{x,k} - L(f, P_{x,k}) - \lim_{k \to \infty} (U(f, P_{y,k} - L(f, P_{y,k}) \right| \\
&= \left| \lim_{k \to \infty} \sum_{i=0}^{N_x - 1} (M_{x,i} - m_{x,i})(x_{i+1} - x_i) - \lim_{k \to \infty} \sum_{i=0}^{N_y - 1} (M_{y,i} - m_{y,i})(y_{i+1} - y_o) \right| \\
&< \left| 2M \lim_{k \to \infty} \sum_{i=0}^{N_x - 1} (x_{i+1} - x_i) - 2M \lim_{k \to \infty} \sum_{i=0}^{N_y - 1} (y_{i+1} - y_i) \right| \\
&= \left| 2M \lim_{k \to \infty} (x_{N_x} - x_0) - 2M \lim_{k \to \infty}  (y_{N_y - 1} - y_0) \right| \\
&= \left| 2M \lim_{k \to \infty} (1) - 2M \lim_{k \to \infty}  (1) \right| \\
&= 0
\end{align}
Sadly this didn't give me a $\delta$, and I'm not sure where I used the assumption that $|x - y| < \delta$, whatever that $\delta$ might be.
Did I take a wrong turn somewhere?
Comment: You don't need the Riemann sum to do it, only need to estimate variation of integral around $t, t+\Delta t$ and.$t+1, t+1+\Delta t$. See the answer below.
Answer: I think you're making it more difficult than it has to be. We have $$|g(x)-g(y)|=\left|\int_x^{x+1}f(t)dt -\int_y^{y+1}f(t)dt\right|\\=\left|\int_x^yf(t)dt-\int_{x+1}^{y+1}f(t)dt\right|$$ Now use that $f$ is bounded.
Answer: Let $M\ge 0$ such that
$$
|f(x)|\le M \quad \forall x\in \mathbb{R}.
$$
For every $t,s \in \mathbb{R}$ we have:
\begin{eqnarray}
|g(s)-g(t)|&=&\left|\int_t^{t+1}f(x)\,dx-\int_s^{s+1}f(x)\,dx\right|\\
&=&\left|\int_t^0f(x)\,dx+\int_0^{t+1}f(x)\,dx-\int_s^0f(x)\,dx-\int_0^{s+1}f(x)\,dx\right|\\
&=&\left|\int_t^sf(x)\,dx+\int_{s+1}^{t+1}f(x)\,dx\right|\\
&\le&\int_{\min\{t,s\}}^{\max\{t,s\}}|f(x)|\,dx+\int_{1+\min\{t,s\}}^{1+\max\{t,s\}}|f(x)|\,dx\\
&\le&\int_{\min\{t,s\}}^{\max\{t,s\}}M\,dx+\int_{1+\min\{t,s\}}^{1+\max\{t,s\}}M\,dx\\
&=&M(\max\{t,s\}-\min\{t,s\})+M(1+\max\{t,s\}-1-\min\{t,s\})\\
&=&M|t-s|+M|t-s|=2M|t-s|
\end{eqnarray}
Hence $g$ is Lipschitz-continuous on $\mathbb{R}$.
Answer: Suppose $\Delta t<1, |f(x)|<M$
\begin{align}
|g(t+\Delta t)-g(t)|&=\left|\int_{t+\Delta t}^{t+\Delta t+1}f(x)dx-\int_{t}^{t+1}f(x)dx\right|
\\
&=\left|\int_{t+\Delta t}^{t+1}f(x)dx+\int_{t+1}^{t+\Delta t+1}f(x)dx-\int_{t}^{t+\Delta t}f(x)dx-\int_{t+\Delta t}^{t+1}f(x)dx\right|
\\
&=\left|\int_{t+1}^{t+\Delta t+1}f(x)dx-\int_{t}^{t+\Delta t}f(x)dx\right|
\\
&\leqslant |M|\left(\left|\int_{t+1}^{t+\Delta t+1}dx\right|+\left|\int_{t}^{t+\Delta t}dx\right|\right)
\\
&=2M|\Delta t|
\\
&\to0 \hspace{3 mm} \text{as } t\to0
\end{align}
So $g(t)$ is continuous.


File write operations through java on a mounted location keeps on failing on Yosemite

Question: My web project development and debugging setup requires mounting a file location on CentOS VM running on my development system and writing files to that mounted location. Everything used to work fine till few days back when I was on maverick. Recently I upgraded to Yosemite(10.10.3) and now file write operations on the mounted location keeps on failing randomly. Failure is not consistent but occurs with a very high frequency and my development setup is almost rendered useless. The same file operation which times out once or twice may succeed on the second or third try so the problem is not that mounted location gets unmounted because I do not mount the location even in the later attempts and file write succeeds automatically on its own.
I keep on getting following stack trace( I am only pasting few relevant calls from top of the call stack)
<code>Caused by: java.io.IOException: Operation timed out
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:345)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1489)
at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1465)
at org.apache.commons.io.IOUtils.copy(IOUtils.java:1440)
</code>
Could anyone help me with what is wrong with Yosemite or something wrong that I am doing. Any help, ideas, thoughts will be highly appreciated otherwise I need to go back to maverick which would mean loosing all my data and development setup and doing it again on maverick.
Answer: Can you simply create a file in that location?
Try this:
File f=new File("the location");
Comment: Please check out the section of the site [on how to answer](https://stackoverflow.com/help/how-to-answer.) Is this a good one? Can you explain *why*?
Comment: `new File(...)` does not create a physical file, but only an abstract representation of a file path, which may not even exist on disk. Read the related Javadoc for a full understanding. To create a file, you use `new FileOutputStream(...)` or `new FileWriter(...)`.
Comment: Oops, sorry about that. How about f.createNewFile(); ?


Get the current activity to handle NFC TAG discovered

Question: I've got an android app with several activities. I want the current activity to handle the nfc discovered event, as the state of the app determines what i want to do with the tag
As can be seen in the attached code i've set up the intents on each activity and implemented the onResume, onPause and onNewIntent methods in each activty.
Yet, for some reason the MainActivty is the only one which gets called even though one of the other activities is the active one. Eg. it is the one with the current GUI.
You guys have any idea how to get the active activity to handle the NFC discovered?
Any help greatly appreciated :)
Here is the ApplicationManifest
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <activity
        android:name=".ConfigureStableNamesActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED " />
            <category android:name="android.intent.category.DEFAULT" />
            <data
                android:host="www.nxp.com"
                android:pathPrefix="/products/identification_and_security/smart_label_and_tag_ics/ntag/series/NT3H1101_NT3H1201.html"
                android:scheme="http" />
        </intent-filter>
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />

            <action android:name="android.nfc.action.NDEF_DISCOVERED " />
            <category android:name="android.intent.category.DEFAULT" />
            <data
                android:host="www.nxp.com"
                android:pathPrefix="/products/identification_and_security/smart_label_and_tag_ics/ntag/series/NT3H1101_NT3H1201.html"
                android:scheme="http" />
        </intent-filter>
    </activity>

In each of my activities i have this code to handle the NFC discovered intent
@Override
protected void onResume() {
    super.onResume();
    ntagHandler.start();
}

@Override
protected void onPause() {
    super.onPause();
    ntagHandler.stop();
}

@Override
protected void onNewIntent(Intent intent) {
    try {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        nfcHandler = new NearFieldCommunicationHandler(tag);
        nfcHandler.connect();

        // DO SOMETHING HERE
        // dataModel.readStableNames(nfcHandler);
    } catch(IOException e) {
        Toast.makeText(this, "Caught exception: " + e.toString(), Toast.LENGTH_LONG).show();
    }
}

Answer: You need to implement "The foreground dispatch system". it allows an activity to intercept an intent and claim priority over other activities. Please refer: https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc#java

First create pendingIntent globally in your each activities as below:

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

then take IntentFilter globally and init with null as below:

IntentFilter[] intentFiltersArray = null;

Write below code in onCreate() method:

IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");    /* YOU CAN TYPE HERE EITHER android.nfc.action.NDEF_DISCOVERED or
            android.nfc.action.ACTION_TAG_DISCOVERED */
        }
        catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        IntentFilter[] intentFiltersArray = new IntentFilter[] {ndef, };

then take techListsArray globally as below:

String[][] techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

Finally write below code to enable and disable the foreground dispatch when the activity loses (onPause()) and regains (onResume()) focus. enableForegroundDispatch() must be called from the main thread and only when the activity is in the foreground (calling in onResume() guarantees this)
public void onPause() {
    super.onPause();
    nfcadapter.disableForegroundDispatch(this);
}

public void onResume() {
    super.onResume();
    nfcadapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
}

public void onNewIntent(Intent intent) {
    Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //do something with tagFromIntent
}


Migrating from IPv4 to IPv6 with three WAN, 1 LAN

Question: I'm in a bind right now. Here I got this wonderful thing called Google, but I am stumped for resources that will allow me to better develop my basic desire.
I run the internet for a local special interest group - one where we have three business class WAN connections that are passed through PacketFilter on FreeBSD (blocking all incoming connections except previously established ones and a select few services for remote administration - I've got priority queues set up to ensure speedy HTTP/IMAP) and load balanced to 27 bandwidth hungry users.
I want to simplify and preserve end to end-ianness but I am hesitant on how to set things up so that my users can do exactly the same thing, except with the hope of reducing the headache of NAT. Is there a resource that can bring me up to speed on what I want to do?
Comment: It's not clear to me what it is that you want to do. You want to simplify - what? Apparently, there is some involvement of IPv6 here - what is it that you want to do?
Comment: **For now**, IPv6, Internet and simplify do not belong in the same statement.
Answer: It sounds like you're using IPv4 NAT for multihoming across the three WAN connections at the moment. This is one of the less well-supported use cases for IPv6 at the moment, though there are some draft standards in process that will improve the situation somewhat. There are going to be some tradeoffs, though.
I'll assume all three connections are through different providers, and each has assigned you a /48 from their own address space. Probably the best way to do this with technology available today is to advertise all three prefixes into the LAN, so each host has an address from each ISP. For automatic failover, you can monitor each link and set the appropriate prefix's preferred lifetime to zero when the corresponding link goes down. You'll have to use source routing on the router so that the appropriate source addresses go out the right links.
You'll still be able to apply priority queues on each ISP link, but it will move the ISP selection (equivalent to source-address selection here) from the router to the end-host. You can influence this with the RFC3484 table, kept in /etc/gai.conf on Linux systems; not sure what the equivalent is other OSes, but it should be configurable. There's an IETF draft (draft-fujisaki-6man-addr-select-opt-00) to distribute this information through DHCPv6.
If you also run internal servers, you might want to use a Unique Local Addressing (ULA) prefix internally as well, and use the ULA addresses in internal DNS. That way ISP failures won't affect internal communications.
If having control of ISP selection at the router is important to you, take a look at the NAT66 drafts. I'm not sure if there's running code for them yet, but it provides the same sort of ISP independence as NAT44. It breaks end-to-end addressing, but because it only swaps prefixes it's stateless and can support end-to-end connectivity, so it's a bit less harmful than v4 NAT.


use variable in postgresql's stored procedure to for adding a partition

Question: i need to add a new partition in stored procedure, and a varialbe need to be used, the code is as follows:
create or replace procedure modifyPartition()
as
declare
 nextDate date;
begin
 nextDate :=date_trunc('hour',sysdate);
 alter table TB_MOVIL_CDR add partition ***** values less than (nextDate);
end;
/

but i get the following error:
ERROR: column "nextDate" does not exists, what's the reason ? can we use varialbe in "alter table" command ?
Comment: Are you sure you are using Postgres? Neither the procedure definition nor the ALTER TABLE statement are valid for Postgres - that code will result in a completely different error message (plus: Postgres has no `sysdate`)
Answer: You need dynamic SQL for that.
But there is a lot more that is wrong with your procedure.
There is no sysdate in Postgres, you have to use current_date and there is no need to remove "hours" from it, because a date in Postgres does not contain any time part.
alter table is not the way to create a new partition in Postgres. As documented in the manual you need to create a table that is a partition.
values less than is also not valid to define a (range) partition in Postgres. A range partitioned table needs a start and end date for the partition values. So you need to calculate two dates, not just one. Assuming you want to create a partition for the current month, you could do something like this:
create or replace procedure modify_partition()
as
$$
declare
  l_partname text;
  l_part_start date;
  l_part_end date;
  l_sql text;
begin
  l_part_start = date_trunc('month', current_date)::date;
  l_part_end = (date_trunc('month', current_date) + interval '1 month')::date;
  l_partname := 'movil_cdr_part_'||to_char(current_date, 'yyyy_mm');

  l_sql := format('CREATE TABLE %I PARTITION OF tb_movil_cdr
    FOR VALUES FROM (%L) TO (%L)', l_partname, l_part_start, l_part_end);

  execute l_sql;
end;
$$
language plpgsql;

format() is the preferred way to create SQL for dynamic SQL. The placeholder %I will properly deal with identifiers. And %L will properly deal with literals.


CSS custom properties (variables) in   sizes

Question: I'm trying to best describe to the browser which image to pick from a srcset list using the sizes attribute.
Basic is:
<picture>
  <source
    type="image/jpeg"
    media="(min-width: 1024px)"
    srcset="a.jpg 1024w, b.jpg 1200w, c.jpg 2048w, d.jpg 2400w"
    sizes="100vw"
  >

</picture>

Now you might have a "max viewport" at which point your webpage "stops growing", so you add a media query in your sizes:
<source
  ...
  sizes="(min-width: 1200px) 1200px, 100vw"
>

Your image might also have some padding, so you might be tempted to use 98vw instead of 100vw but that's not always accurate if the paddings are in pixels for example, so what you can do instead it use calc:
<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(100vw - 20px)"
>

So far we've only been using absolute units, but I've read you can also use context-dependent units like em:
<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(100vw - 2em)"
>

Interestingly, that means the browser must be aware of the styles being applied to the image (since em can change based on CSS). So if this is true, could you use CSS custom properties (or "CSS variables") in your sizes?
<source
  ...
  sizes="(min-width: 1200px) 1200px, calc(var(--six-columns) - var(--image-padding))"
>

Thanks!

As a bonus question: any idea where I could find the browser support for such a thing?
Answer: The answer to this is NO!
When using em as a unit inside the sizes attribute, the browser will use a fixed predetermined size (14px in chrome apparently, determined experimentally).
In the end, no information actually comes from CSS, and CSS custom properties aren't actually usable that way.
Comment: use em there is like using em inside media query: https://stackoverflow.com/a/23614634/8620333
Comment: Here's a reduced test case to prove that this doesn't work: https://output.jsbin.com/katigokoja/1


Trouble with loop and storing data in variables

Question: The program I am trying to finish needs to read in three numbers from the user and then store them in the variables num1, num2 and num3 so that they can be used in steps 2 and 3.  The problem I am having is that when the program loops through after the user inputs their numbers and tries to move on to step 2 or 3, it says must complete step 1 first.
This is my code as of right now:
    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int num1;
        int num2;
        int num3;
        int input;

        do {
            boolean opt1Done = false;
            System.out.println("Select your next step");
            System.out.println("1: Enter three numbers between 1 and 100.");
            System.out.println("2: Order your number in ascending order");
            System.out.println("3: Determine if the three inputs form a triangle");
            System.out.println("4: Exit");

            int answer = console.nextInt();
            num1 = console.nextInt();
            num2 = console.nextInt();
            num3 = console.nextInt();
            input = console.nextInt();

            if (answer == 1) {
                //do whatever for option 1
                System.out.println("Enter a value for num1 between 1 and 100.");
                System.out.println("Enter a value for num2 between 1 and 100.");
                System.out.println("Enter a value for num3 between 1 and 100.");

                opt1Done = true;
            } else if (answer == 2) {
                if (opt1Done) {
                    //...... do whatever to order the numbers
                    int[] arraynum;
                    arraynum = new int[3];

                    arraynum[0] = num1;
                    arraynum[1] = num2;
                    arraynum[2] = num3;

                    Arrays.sort(arraynum);

                    int i;

                    for (i = 0; i < arraynum.length; i++) {
                        System.out.println("num:" + arraynum[i]);
                    }

                } else {
                    System.out.println("you must complete Step 1 before Step 2");
                }
            } else if (answer == 3) {
                if (opt1Done) {
                    //... do whatever to determine if triangle or not
                    if (num1 + num2 > num3 && num1 + num3 > num2 && num2 + num3 > num1) {
                        System.out.print("TRIANGLE");
                    } else {
                        System.out.print("NO TRIANGLE");
                    }
                } else {
                    System.out.println("you must complete Step 1 before Step 3");
                }
                if (answer == 4) {
                    System.exit(0);

                }
            }
        } while (input != 4);
    }
}

Do I need to add another loop or change the one already have?
Comment: seems like its homework. is it?
Comment: you broke the code again! Watch out when you edit your question ;)
Comment: its for a project for a programming class yea @MuhammadSuleman
Comment: `opt1Done` is being set to false after every iteration, Move `boolean opt1Done = false;` before  you begin do ..while loop
Answer: You don't loop over the instructions. Every time you have a step completed, the program then ends and the next time you run it, nothing you've done before is saved.
You need an outer loop to iterate over commands:
public static void main(String[] args) {

    int num1;
    int num2;
    int num3;

    boolean opt1Done = false;

    while (true) {

        System.out.println("Select your next step");
        System.out.println("1: Enter three numbers between 1 and 100.");
        System.out.println("2: Order your number in ascending order");
        System.out.println("3: Determine if the three inputs form a triangle");
        System.out.println("4: Exit");

        //rest of your code here
    }
}

Answer: It seems that you must loop until the user choose the option 4. I don't see any loops that encompass the options asking questions.
Answer: you are putting condition in wrong place.
as i am thinking first check answer from user then take those 3 numbers inside first condition as
int answer = console.nextInt();
    if (answer == 1) {
        //do whatever for option 1
        System.out.println("Enter a value for num1 between 1 and 100.");
        num1 = console.nextInt();
        System.out.println("Enter a value for num2 between 1 and 100.");
        num2 = console.nextInt();
        System.out.println("Enter a value for num3 between 1 and 100.");
        num3 = console.nextInt();
        opt1Done = true;
   }

and move this line outside of loop
 boolean opt1Done = false;

Answer: Move the boolean declaration opt1Done and the numbers outside the loop and read input after every user prompt.
 import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;

public class ReadChar {

    public ReadChar() {
        // TODO Auto-generated constructor stub
    }

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        boolean opt1Done = false;

        while (true) {

            System.out.println("Select your next step");
            System.out.println("1: Enter three numbers between 1 and 100.");
            System.out.println("2: Order your number in ascending order");
            System.out
                    .println("3: Determine if the three inputs form a triangle");
            System.out.println("4: Exit");

            int answer = console.nextInt();

            if (answer == 1) {
                // do whatever for option 1
                System.out.println("Enter a value for num1 between 1 and 100.");
                num1 = console.nextInt();

                System.out.println("Enter a value for num2 between 1 and 100.");
                num2 = console.nextInt();
                System.out.println("Enter a value for num3 between 1 and 100.");
                num3 = console.nextInt();

                opt1Done = true;
            } else if (answer == 2) {
                if (opt1Done) {
                    // ...... do whatever to order the numbers
                    int[] arraynum;
                    arraynum = new int[3];

                    arraynum[0] = num1;
                    arraynum[1] = num2;
                    arraynum[2] = num3;

                    Arrays.sort(arraynum);

                    int i;

                    for (i = 0; i < arraynum.length; i++) {
                        System.out.println("num:" + arraynum[i]);
                    }

                } else {
                    System.out
                            .println("you must complete Step 1 before Step 2");
                }
            } else if (answer == 3) {
                if (opt1Done) {
                    // ... do whatever to determine if triangle or not
                    if (num1 + num2 > num3 && num1 + num3 > num2
                            && num2 + num3 > num1) {
                        System.out.print("TRIANGLE");
                    } else {
                        System.out.print("NO TRIANGLE");
                    }

                } else {
                    System.out
                            .println("you must complete Step 1 before Step 3");
                }

            }
            if (answer == 4) {
                System.exit(0);

            }
        }
    }
}

Answer: Hope this helps

Introduced a while loop and opt1True should outside of the loop
check for is answer 4 is inside answer 3. So moved that in else if to be same level with other answer checks
static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int num1 = 0;
        int num2 = 0;
        int num3 = 0;
        boolean opt1Done = false;
        while(true) {
        System.out.println("Select your next step");
        System.out.println("1: Enter three numbers between 1 and 100.");
        System.out.println("2: Order your number in ascending order");
        System.out.println("3: Determine if the three inputs form a triangle");
        System.out.println("4: Exit");

        int answer = console.nextInt();
        if (answer == 1) {
            // do whatever for option 1
            System.out.println("Enter a value for num1 between 1 and 100.");
            num1 = console.nextInt();

            System.out.println("Enter a value for num2 between 1 and 100.");
            num2 = console.nextInt();

            System.out.println("Enter a value for num3 between 1 and 100.");
            num3 = console.nextInt();

            opt1Done = true;
        } else if (answer == 2) {
            if (opt1Done) {
                // ...... do whatever to order the numbers
                int[] arraynum;
                arraynum = new int[3];

                arraynum[0] = num1;
                arraynum[1] = num2;
                arraynum[2] = num3;

                Arrays.sort(arraynum);

                int i;

                for (i = 0; i < arraynum.length; i++) {
                    System.out.println("num:" + arraynum[i]);
                }

            } else {
                System.out.println("you must complete Step 1 before Step 2");
            }
        } else if (answer == 3) {
            if (opt1Done) {
                // ... do whatever to determine if triangle or not
                if (num1 + num2 > num3 && num1 + num3 > num2
                        && num2 + num3 > num1) {
                    System.out.print("TRIANGLE");
                } else {
                    System.out.print("NO TRIANGLE");
                }
            } else {
                System.out.println("you must complete Step 1 before Step 3");
            }

        } else if (answer == 4) {
            System.exit(0);

        }

        }

    }

Answer: All you had to do was add a while loop to your logic and reorder it.
    boolean opt1Done = false;
    int num1, num2, num3;
  while(answer != 4){

  System.out.println("Select your next step");
    System.out.println("1: Enter three numbers between 1 and 100.");
    System.out.println("2: Order your number in ascending order");
    System.out.println("3: Determine if the three inputs form a triangle");
    System.out.println("4: Exit");

    int answer = console.nextInt();

    if (answer == 1) {
        //do whatever for option 1
        System.out.println("Enter a value for num1 between 1 and 100.");
        num1 = console.nextInt();
        System.out.println("Enter a value for num2 between 1 and 100.");
        num2 = console.nextInt();
        System.out.println("Enter a value for num3 between 1 and 100.");
        num3 = console.nextInt();
    opt1Done = true;
  }

                                    ...

       if (answer == 4) {
                    System.exit(0);

                }
            }
         }
     }

Your problem was every time you were looping you were re-declaring and setting the boolean variable to false. Plus your console.nextInts() were in the wrong spot. Also do while is not necessary in this case because the starting value of answer is null and therefore is not equal to four.


Pivot Parcela (Linha em coluna)

Question: Senhores, bom dia !
Eu estou tentando fazer um PIVOT simples de parcela sob mesmo numero do cliente (330162210001), porem nao estou conseguindo...
A ideia é que a cada resultado de parcela encontrado seja uma coluna.
Ja tentamos diversos aggregation function sql, porem sem êxito.
Esta dando este erro :

Já tentamos converter todos os tipos de type possivel para que ele consiga fazer a leitura. Mas sem êxito.
Type da Tabela que estamos trabalhando:

Resultado da Subquery:

Code utilizado:
SELECT * FROM (
              SELECT dup.cliente, dup.VR_LIQ_ATU,dup.NUMERO, DUP.VALOR
              FROM DUPLICATAS_ABERTAS DUP WHERE dup.CLIENTE = 330162210001) as Q
PIVOT(
       MAX (cliente)
       FOR VR_LIQ_ATU IN ([VALOR_C]))AS PVT

Se alguem conseguir dar uma luz, Agradecemos a compreensão.
Comment: O que seria esse "VALOR_C"? Não vi ele presente/declarado na SQL. Outra dúvida é, se tiver 1000 linhas, ele transformará essas 1000 linhas em 1000 colunas? Ou há um limite de retornos por cliente, por exemplo, terá no máximo 12 parcelas.
Comment: pedro o valor_c é só a coluna que ele tem que retornar o dado da parcela. Nessa tabela no entra até 3 parcelas. Entao não preciso me preocupar com isso sabe? rs
Comment: na verdade o PIVOT, pelo menos no SQL Server não funciona assim, o campo que fica ali no IN é o identificador da coluna pivotada. Vou colocar como resposta pra você entender melhor.
Answer: Maguim,
conforme mencionei no comentário, o que fica dentro do IN é o identificador da coluna pivotada, pra você entender melhor, ele deve ser o elemento que consta na linha. Pelos dados fornecidos, daria para montar assim (pode haver outras formas, mas não sei como está a arquitetura do seu banco em relação aos campos):
SELECT *
FROM
(SELECT
    ROW_NUMBER() OVER(PARTITION BY CLIENTE ORDER BY CLIENTE) AS ORDEM,
    DUP.CLIENTE,
    DUP.VR_LIQ_ATU,
    DUP.NUMERO
    --DUP.VALOR
    FROM TESTE DUP
    --WHERE DUP.CLIENTE = 3301
) AS Q
PIVOT(SUM(VR_LIQ_ATU) FOR ORDEM IN ([1], [2], [3]) )AS PVT

outros scripts:
--CREATE TABLE TESTE (
--CLIENTE VARCHAR(100),
--VR_LIQ_ATU NUMERIC(10,4),
--NUMERO VARCHAR(100),
--VALOR VARCHAR(100)
--);

--INSERT INTO TESTE VALUES (3301, 173.55, 62, 'R$ 177,59' )
--INSERT INTO TESTE VALUES (3301, 1395.55, 62, 'R$ 1395,59' )
--INSERT INTO TESTE VALUES (3301, 1455.55, 62, 'R$ 1455,59' )
--INSERT INTO TESTE VALUES (3302, 152.55, 62, 'R$ 152,59' )
--INSERT INTO TESTE VALUES (3302, 11.55, 62, 'R$ 11,59' )
--INSERT INTO TESTE VALUES (3303, 1365.55, 62, 'R$ 1365,59' )
--INSERT INTO TESTE VALUES (3303, 188.55, 62, 'R$ 188,59' )

Comment: pedro ! obg meu amigo, ficou mais claro agr. abraços.
Comment: Se a resposta te ajudou ou resolveu o seu problema, não esqueça de dar um voto ou selecionar como resposta para a pergunta, assim ajudará outros que tiverem o mesmo problema.

Pivot Parcela (Linha em coluna)


Kappa and downsampling, selection of data set

Question: I have a unbalanced data set and use Cohen's kappa and AUC as performance measure.
Without down sampling the Kappa value is around 0.85, with random down sampling it is 0.95. and with a house-made focused down sampling it is approx 0.75.
Which data would you use to train the classifier? The AUC for the three cases are 0.998 without downsampling, 0.998 with random downsampling and 0.921 with house-made downsampling
I'm suspicious that the random down sampling increases the kappa value.
The full data set looks like this

When I randomly downsampl it looks like this

And with a house made sort of focused downsampling it looks like this
Answer: Cohen's kappa coefficient is a chance-adjusted index of agreement. It estimates the likelihood of chance agreement using Bayes' Rule: it assumes that the likelihood of raters randomly assigning an item to the same category is based on the product of raters' individual distributions for each category. In your case, the "raters" are the trusted labels and the classification predictions. By using downsampling, you are artificially modifying one of the rater's (i.e., the trusted labels') distributions. Unfortunately, this undermines the logic of the coefficient. So I would base my decision on other metrics (AUC or just accuracy) and use random or no downsampling.
Comment: Thank you for your answer! Yes I think random or no downsampling is the best option here. The focused undersampling is somehow biased.


Sharing SSL Certificate

Question: I want to buy a wildcard SSL certificate to be used by multiple web servers. Is this possible? If so, what is the configuration?
DNS design for [www/nas].example.com:
A Record   | @   | Shared Web Host
A Record   | www | Shared Web Host
DNS Record | nas | Local NAS Server
1. Is it possible for two external servers to share separate sub-domains (i.e. nas.example.com for my NAS Server and *.example.com for my Shared Web Host)?
2. SSL providers give me a CA bundle. Do I install this CA to both servers?
3. Will Whoisguard protect both servers?
Answer:

Is it possible for two external servers to share separate sub-domain...

There is no technical reason against installing the same certificate on multiple systems if the domains on the system are covered by the certificate. There might be usage restrictions by the CA which you need to check. And since all systems with the same certificate need to use the same private key the change of compromising the key gets larger.

SSL providers give me a CA bundle. Do I install this CA to both servers?

Of course.

Will Whoisguard protect both servers?

Whoisguard is about hiding the real owner of a domain from the publicly accessible whois information and has nothing to do with SSL certificates or on how many servers you use the domain.

Sharing SSL Certificate


Existe alguma maneira de traduzir as mensagens de erro produzidas pelo PHP?

Question: Existe alguma maneira de traduzir as mensagens de erro no PHP?
Exemplo:
Inglês

Use of undefined constant X

Português

Uso de constante indefinida X
Answer: O Tim S. já fez o trabalho de pesquisar isto e postar no SO. Ele acha que não compensa fazer mas pode editar um arquivo .po com as strings do PHP traduzidas. Ele indica até um editor para isto. Precisa do Gettext e analisar o arquivo.
Ele apresenta uma outra forma que captura o erro e trata para apresentar o texto como você quiser:
set_error_handler('error_handler');

function error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
    // Get the correct string for the error type
    switch($errno){
        case E_ERROR:
            $type = 'Error';
            break;
        case E_WARNING:
            $type = 'Warning';
            break;
        case E_PARSE:
            $type = 'Parse Error';
            break;
        case E_NOTICE:
            $type = 'Notice';
            break;
        case E_CORE_ERROR:
            $type = 'Core Error';
            break;
        case E_CORE_WARNING:
            $type = 'Core Warning';
            break;
        case E_COMPILE_ERROR:
            $type = 'Compile Error';
            break;
        case E_COMPILE_WARNING:
            $type = 'Compile Warning';
            break;
        case E_USER_ERROR:
            $type = 'User Error';
            break;
        case E_USER_WARNING:
            $type = 'User Warning';
            break;
        case E_USER_NOTICE:
            $type = 'User Notice';
            break;
        case E_STRICT:
            $type = 'Strict Notice';
            break;
        case E_RECOVERABLE_ERROR:
            $type = 'Recoverable Error';
            break;
        default:
            $type = 'Unknown error (' . $errno . ')';
            break;
    }

    // translate text
    $type = error_handler_translate($type);
    $str = error_handler_translate($errstr);
    $in = error_handler_translate('in');
    $line = error_handler_translate('on line');

    // echo the error in "default" PHP format
    echo '
'. $type .': ' . $str . ' '. $in .' ' . $errfile . ' '. $line .' ' . $errline . '
';

    // ignore the original PHP error handling
    return true;
}

function error_handler_translate($str) {
    // translate $str here

    return $str;
}

Coloquei no GitHub para referência futura.
Não tenho experiência com isto e é a melhor resposta que consigo dar.
Comment: A pergunta era no intuito de algo como "instalar uma extensão e tudo certo!", mas pelo visto essa solulção é o que temos de melhor :\


Crop out ggplot2 whitespace around plot

Question: Is there a way to remove the white space surrounding a ggplot2 plot when the shape has been changed using coord_fixed()? I would like the white space above and below to be cropped away so that only the plotting area and axis labels remain. I am rendering the plot output in an R markdown file without saving.
 p <- ggplot(mtcars, aes(mpg, wt)) + geom_point()
 p + coord_fixed(ratio = 1)

The code below produces the following plot:
Comment: do you want something like this? `p + coord_equal() + theme(aspect.ratio = 1)`
Answer: When you use:
ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  coord_fixed(ratio = 1) +
  ggsave('plot.jpg', width = 6, height = 1.5, dpi = 300)

You get a plot with less white space:

Another option could be to use the png or jpeg device:
p <- ggplot(mtcars, aes(mpg, wt)) +
  geom_point() +
  coord_fixed(ratio = 1)

jpeg('plot.jpg', width = 600, height = 150)
p
dev.off()

Comment: This solution doesn't work for me. Is this still working on your computer?
Comment: is this about rmarkdown or creating a image output? This seems like a hack if it works?
Answer: If you are looking for a solution which also works in R markdown (i.e. output as PDF/HTML), this solved it for me: first set the aspect ratio and then remove the additional margin on the top via the theme() settings.
library(ggplot2)
ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, shape = Species, color = Species)) +
  geom_point(size = 5) +
  coord_fixed(ratio = 1/2) +
  theme(plot.margin=unit(c(-0.30,0,0,0), "null")) # remove margin around plot

See also this blog post for more details.
Session info:
MacOs 10.13.6, R 3.6.3, ggplot2_3.3.1
Comment: may also be necessary to set the crop options: https://stackoverflow.com/a/57059235/7941188

Crop out ggplot2 whitespace around plot