Block config not saved apparently due to an enforced 303 status

Question: After upgrading from 10.0 to 10.1.7, changes to block configuration were no longer saved.
I cannot reproduce this in an out-of-the-box instance. I've turned off all custom modules and as many of the contrib modules in use that I can without utterly breaking the site due to interdependencies between modules and content structures, etc. Nothing changed with this behavior.
I've since moved on to attempting to locate where the behavior is explained in xdebug.
When I click the submit button in the block config form, stepping through in xdebug, I reach ::submitConfigurationForm() in BlockPluginTrait.
At this point $form_state contains the changed block title in $form_state->decoratedFormState->values[settings][label].
::blockSubmit() is then called.
It progresses to FormBuilder::buildForm() where ::processForm() is called and returns an EnforcedResponseException code of 303 (Other).
No error message is given on the screen, nothing logged, but the result is a return to the block layout screen with the config change not having been saved.
What does the 393 enforced response exception signify and what can cause it in the context of saving a block config?
Comment: I added the question at the bottom. It is not a big report, it is the detail of how I found where the normal behavior changes.
Answer:
What does the 30x enforced response exception signify and what can
cause it in the context of saving a block config?

You are debugging low-level code on how Form API handles redirects. Drupal forms use this exception to transport redirect responses to the Symfony stack because they didn't find a way to return it from the form controller. This is an internal issue for core developers. You need to debug Form API level code returning a redirect response from a form class or setting the redirect in <code>$form_state</code> in places where you don't want to do that.
In Form API the default for any form is set to redirect to itself after a successful submit to display a new empty form. Even a very simple form would show this exception in xdebug. Additonally, a destination query parameter can override any redirect URL. Where the user is sent after a form is submitted is not necessarily determined by the form.
Comment: Thanks for that. So, hmm, if the config save has gotten to that point already, with the config change still in the form state object, it gets more curious why it's not saved.


Near real time sync from mysql to Hbase

Question: Currently I am facing a issue during sync the data from mysql to hbase, I need a near real time data sync from mysql to hbase, and I need to merge multiple mysql tables into one hbase table during the data sync.
I tried sqoop looks like it can not fit our requirements.
So are there any existing tools/libs can be used for my case, or any other solutions I can try with spark.
Comment: Thanks for your time,  e.g First: I have a table A and table B, which has a relation of one to many, and I want to merge them into one table C in the hbase table(Should be the joined records).   Second: Sqoop is batch based which is not a near real time solution,  We want any new records in table A and B, we want this record sync to Hbase Table C right away.
Comment: Can you provide some details as to why sqoop will not fit your requirements?
Answer: Consider using Apache Phoenix on HBase. It will give you low-latency SQL queries (so it is suitable for OLTP and easy to use for OLAP) on data stored in HBase so you don't have to worry about syncing. It also has NoSQL features such as the ability to dynamically add columns during query-time.
To satisfy your use case, you could run Phoenix for OLTP, and a second instance of Phoenix on a read replica to run table joins for OLAP.
http://www.cloudera.com/documentation/enterprise/5-4-x/topics/admin_hbase_read_replicas.html
Secondary replicas are refreshed at intervals controlled by a timer (hbase.regionserver.storefile.refresh.period), and so are guaranteed to be at most that interval of milliseconds behind the primary RegionServer.
This solution satisfies your requirements for OLTP, OLAP, and near real-time syncing while giving your transactional database scalability that you would not easily have with MySQL. Apache Phoenix also offers full integration with the Hadoop ecosystem so it will integrate well with your current analytics stack.
Comment: Do you have experience on the phoenix join, looks like for multiple table join, phoenix performs not good?
Comment: By default, Phoenix uses hash-joins, requiring the data to fit in memory. If you run into problems (with very large tables), you can increase the amount of memory allocated to Phoenix (config setting) or set a query "hint" (ie. `SELECT /*+ USE_SORT_MERGE_JOIN*/ FROM ...`) to use sort-merge joins which do not have the same requirement. They plan to auto-detect the ideal join algorithm in the future. Additionally, Phoenix supports only a subset of join operations.

Near real time sync from mysql to Hbase


Which Olympic sport was the first to have a women's counterpart?

Question: The original Olympics, in Greece, were male-only insofar as the participants, per my research. Modern Olympics, obviously, have men's and women's competitions. However, given that most Western nations (whose cultural norms drive the Olympics) didn't view women as competent until well into the 20th century, I'm curious: which Olympic sport was the first to have a female counterpart?
Alternatively, which was the first co-ed Olympics and which sports featured a women's division?
Comment: http://en.wikipedia.org/wiki/Women_at_the_Olympics has some indication that there were women participants as early as 1900 (the second modern games), but I'm still looking into who and what sports
Comment: http://www.london2012.com/mm/Document/local-leaders/General/01/24/59/88/gold-quiz-questions_English.pdf Same info as @waxeagle and looking...
Comment: @waxeagle She's asking which Olympic *sport* was the first. I believe the answer is sewing.
Answer: Women first appeared in the modern Olympics in Croquet at the 1900 Olympics.
22 women competed in this the second modern Olympics in the sports of Croquet, equestrian, Golf, Sailing and Tennis,
Hélène de Pourtalès (Sailing), Charlotte Cooper (Tennis, one in singles and one in mixed doubles) and Margaret Ives Abbot (golf) won the first gold medals as female participants in these Olympics. As Ed mentions golf and tennis were the only competitions where women competed separately.
While lacking in a great deal of detail Wikipedia has a graph of the percentage of total participants that were female by year for the Summer Olympics:
Comment: Saying that women started out at Chochet is sexist and wrong. But yes, I believe they did do equestrian. Sidesaddle.
Answer: In 1900, the second modern Olympic games, 22 women competed in 5 events: tennis, sailing, croquet, equestrian, and golf.  Furthermore, only golf and tennis had exclusive events for women only. (1)


How to find user in Azure AD B2C with regex using Graph Api?

Question: Is it possible to find users in Azure AD using a regex with microsoft Graph api. Like I want to fetch all the users with email address like 'test[0-9]*@somedomain.com'.
Can we do that?
Thanks!
Answer: At present, the Microsoft API supports the OData Query Parameters to help customize the responses.

Is it possible to find users in Azure AD using a regex with microsoft Graph api.

No, it doesn't have this feature currently. You may submit the feedback to azure team.


How to turn off the screen from a docker container?

Question: I have a docker container running with a GUI app on it. All is working well except when the app try to turn off the screen by pushing the following command to the system : xset -display :0.0 dpms force off
When this command reach the system, the docker container fail.
Here is the docker-compose.yml content for this container:
version: "3"

volumes:
  kiosk_vol:

services:
  func:
    image: docker.alatimier.fr/kiosk/func:snapshot
    restart: always
    environment:
      KIOSK_ID: ${KIOSK_ID}
      ADDR: ${ADDR}
      # For Linux host
      DISPLAY:
      # For OSX host, install socat and xquarts and create TCP bridge between the docker container and X11 window server :
      # socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"
      #DISPLAY: docker.for.mac.localhost:0
    volumes:
    - kiosk_vol:/working_directory
    - /tmp/.X11-unix:/tmp/.X11-unix:rw
    depends_on:
    - conf
    ipc: "host"

Would you have any idea why I can't turn off the host screen from the docker container ?
The host is on lubuntu 18.04, and I tested the command line to shut down the screen and it works fine.
Thanks.
Answer: So I found out:
First thing is to edit the dockerfile to install the X utilities (without it, xset is not known in the docker container):
RUN apt-get install --no-install-recommends -y x11-xserver-utils

Then edit the docker-compose.yml in order to give access to the .Xauthority file and pass the display name:
version: "4"

volumes:
  kiosk_vol:

services:
  func:
    image: docker.alatimier.fr/kiosk/func:snapshot
    restart: always
    environment:
      KIOSK_ID: ${KIOSK_ID}
      ADDR: ${ADDR}
      # For Linux host
      DISPLAY: $DISPLAY
      # For OSX host, install socat and xquarts and create TCP bridge between the docker container and X11 window server :
      # socat TCP-LISTEN:6000,reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\"
      #DISPLAY: docker.for.mac.localhost:0
    volumes:
    - kiosk_vol:/working_directory
    - /tmp/.X11-unix:/tmp/.X11-unix:rw
    - $HOME/.Xauthority:/root/.Xauthority:rw
    depends_on:
    - conf
    ipc: "host"

Hope this help if someone have the same issue.


How to delete columns of dynamic array in C++

Question: I need help tring to delete columns of 2D array in C++. I've tried the operation by making a copy of the array. It succeeded only from the start to middle or the middle to the end of array. witch algorithm to jump unwanted columns in the array when making copy.
Comment: What is this 2D array made up of? How do you define it?
Comment: You tried to delete something by copying it? Something seems rather off here... In any event, you'll need to provide more details about what you have so far, since there are many ways to define a 2D array (some of which remove the need to explicitly delete columns).
Comment: you're right but the 2D if define using pointers, the solutions will be easy If I use vector
Answer: Because of dynamic arrays so the varable of the array is pointer for the first value so you can't get the size or even use sizeof to get the size , but there's no case where you use dynamic arrays witout knowing the size , either fixed or in runtime throw varable
Answer: This probably isn't the best way to do this but its' a potential solution
<code>int removeColumn(int a){
vector<vector<int>> ret(M);
int i = 0;
for(vector<int> temp : Arr){
        vector<int> tempp(N-1);
        copy(temp.begin(), temp.begin()+a, tempp.begin());
        copy(temp.begin()+a+1,temp.end(),tempp.begin()+a);
        ret[i] = tempp;
        i++;
}
Arr = ret;
return 0;
</code>
}
Essentially you iterate over each row and use two copy statements to copy from the beginning to an index and from said index + 1 to the end. I'm sure there's a way to do this more elegantly, you could try looking at for_each loops however I doubt you could do it exclusively with copy. Tested it with this code.
https://repl.it/repls/PrettyTerrificOmnipage
Hope this helps


Timestamp sem utilizar os.time()

Question: Como converter uma data e tempo no seu timestamp, mas sem utilizar o os.time() em Lua? Qual a expressão para calcular? Será que é possível?
Exemplo:
data = "01/01/2015"
hora = "10:00:00"

Comment: timestamp desde que origem?
Comment: Veja [luatz](https://github.com/daurnimator/luatz).
Answer: Bom, de acordo com [ https://en.wikipedia.org/wiki/Timestamp ] existem vários formatos de TimeStamp, se você já possui as informações de data e hora, como na pergunta, você pode procurar um formato que se encaixa nessa descrição.
Por exemplo, a ISO 8601 [ https://en.wikipedia.org/wiki/ISO_8601 ] define que uma data (dia/mes/ano) deve ser representada na forma ano-mes-dia, você poderia usar as funções de string do lua para separar as informações digitadas e gerar esse Time Stamp. Por exemplo, vamos supor que você implemente uma função de split como descrito em [ http://lua-users.org/wiki/SplitJoin ], você poderia gerar seu TimeStamp assim:
data = "04/02/2016" --Quatro de Janeiro de 2016
dataTable = split(data,"/")
--timeStamp = 2016-02-04 (Conforme ISO 8601)
timeStamp = dataTable[1] .. "-" ..dataTable[2] .. "-" ..dataTable[3]

A Mesma ideia pode ser aplicada para adicionar as horas, minutos e segundos.
Entretanto, se você quer um time stamp como o retorna por os.time() (Segundos desde uma determinada data), é fortemente recomendado o uso de uma biblioteca, embora seja sim possível calcular, de uma forma bem grosseira ficaria assim:
anoZero=1960
ano=2016
mes = 2 + ((ano-anoZero)*12)
dias = 4 + (mes * 30) --Simplificação, o ideal seria calcular o numero de dias para cada mês
horas = 1 + (dias * 24)
minutos=29 + (horas*60)
segundos=minutos * 60 -- Numero de segundos desde 1960-01-01 00:00:00

Comment: só um detalhe: "split" não é método nativo da linguagem Lua, tem que ser escrito ou então usado de algum módulo exteno (Penlight, Microlight, etc)

Timestamp sem utilizar os.time()


How to solve $T(n) = 5T(\frac{n}{2}) + n^3 \log n$ using master method?

Question: I'm trying to solve the recurrence $T(n) = 5T(\frac{n}{2}) + n^3 \log n$ using master method.
$$
a = 5, b = 2
$$
$$
n^{\log_b a} = n^{\log_2 5} = n^{2.32} \in Θ(n^{2.32})
$$
How can I continue? Because $n^3 \log n$ is not $\in Θ(n^{2.32})$.
Comment: It's been a bit since I looked at this, but doesn't that mean that the $n^3\log n$ term just dominates?
Comment: I'm not sure, i tried in different ways and I can't solve it
Comment: Your $f(n) = n^3log n = n^{3+\alpha}$ and $3+\alpha > 2.32$. So, $f(n)$ dominates and $T(n) = Θ(f(n))$
Answer: $$ \bbox[7px,border:2px solid red] {\text{MASTER THEOREM}}: $$
$$T(n)=aT(n/b)+f(n).$$
$$\bbox[1px,border:1px solid black] {a\ge 1,b>1,f(n)=Θ\big( n^k\cdot \log^p(n)\big)}$$
$$\text{CASE 1}:$$
$$ \text{if } \log_b(a)>k\text{ then: }\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^{\log_b(a)}\big)}   $$

$$\text{CASE 2}:$$
$$\text{if } \log_b(a)=k:\begin{cases}
\text{if $p>-1:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot \log^{p+1}(n)\big)}$} \\
\text{if $p=-1:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot \log\big( \log(n)\big)\big)}
$ }\\
\text{if $p<-1:\quad \bbox[1px,border:1.5px solid black] {T(n)=Θ\big( n^k\big)}$ }\\
\end{cases} $$

$$\text{CASE 3}:$$
$$\text{if $\log_b(a)<k:\begin{cases}
\text{if $p\ge 0:\quad \bbox[1px,border:1px solid black] {T(n)=Θ\big( n^k\cdot\log^p(n)\big)}
$} \\
\text{if $p<0:\quad \bbox[0.5px,border:1px solid black] {T(n)=\mathcal O \big( n^k\big)}
$}
\end{cases}$}$$

Note that $a=5,b=2,\log_2(5)<k ,k=3,p=1$, hence
$$T(n)=\Theta\big(n^3\cdot \log(n)\big).$$


Image of a linear combination by a continuous function

Question: Let $f:\mathbb{R}^{n} \rightarrow \mathbb{R}$ be a continuous function. Take $x,y \in \mathbb{R}^{n}$ with $f(x) < f(y)$ and let $L = \{\alpha x + (1-\alpha)y$ : $\alpha \in [0,1]\}$ be the straight line between $x$ and $y$. Is it true that the continuity of $f$ implies that $f(L) \subset [f(x), f(y)]$?
Answer: No this is not true. Take $f = x^2-1$, $x = -1$ and $y = 1$. Then $[f(x),f(y)] = \{0 \}$ but $f(L)$ is not contained in this.
Answer: No.
Take $f(x)=x^2$, $x=-1$ and $y=2$.
We have that $f(x)=1<4=f(y)$, $L=[-1,2]$ and $[f(x),f(y)]=[1,4]$.
Now, $0\in L$ but $f(0)=0\notin [f(x),f(y)]$.


Como fazer um CountDown com jQuery que reinicia semanalmente

Question: Tenho que fazer um contador regressivo para uma promoção.
Eu preciso que esse contador reinicie toda terça-feira às 00:00 horas para que fique mais ou menos assim:

"Restam apenas 6 dias 12 horas 42 minutos e 37 segundos para o fim da promoção"
Comment: Você precisa pegar a diferença entre o momento atual e a próxima terça...
Comment: Ideia interessante, porém não tenho experiência em jQuery, há uma forma de sempre pegar o timestamp da próxima "terça"?
Comment: Veja como marcar uma resposta como aceita em http://i.stack.imgur.com/jx7Ts.png e porque em https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079
Comment: Porque em jquery?
Answer:
Tenho que fazer um contador regressivo para uma promoção.

// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML = days + "d " + hours + "h " +
    minutes + "m " + seconds + "s ";

  // If the count down is finished, write some text
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);

Eu preciso que esse contador reinicie toda terça-feira às 00:00 horas

Aqui você vai definir o limite do contador:
// Set the date we're counting down to
var countDownDate = new Date("Jan 5, 2019 15:37:25").getTime();

Lembrando que isso é só o lado do cliente (front-end). Deve validar a data/hora do lado do servidor (back-end).

W3Schools: How TO - JavaScript Countdown Timer
Answer:

//função para definir o dia destino e horário desejado para o final da promoção de cada semana
function dataDiaDaSemana(diaRef){
    var dias = {
        segunda: 1,
        terca: 2,
        quarta: 3,
        quinta: 4,
        sexta: 5,
        sabado: 6,
        domingo: 0
    };

    var dataAtual = new Date();
    var timestampAtual = dataAtual.getTime();
    var diaGatilho = dias[diaRef];
    var diaMilisegDif=0;
    var diaEmMiliseg = 1000*60*60*24;
    // adiciona um dia a diaMilisegDif enquanto o diaRef desejado (terca por exemplo) não for atingido
    while(dataAtual.getDay()!=diaGatilho){
        diaMilisegDif += diaEmMiliseg;
        dataAtual = new Date(dataAtual.getTime()+diaEmMiliseg);
    }
    return new Date(timestampAtual + diaMilisegDif);
}

//defina o dia destino da semana
var dia = dataDiaDaSemana("terca");
//defina o horario
dia.setHours(0,0,0,0); //(hora, min, seg, miliseg)

//fonte https://www.w3schools.com/howto/howto_js_countdown.asp

//define a data para contagem regressiva
var countDownDate = new Date(dia).getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get todays date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);

   if (distance < 1) { // você chegou ao seu destino :-)
  document.getElementById("demo").innerHTML = "";
  /*** redefine a data para próximo dia destino da semana *****/
  countDownDate = new Date(countDownDate.valueOf() + 604800000);
   }else if (days>0){
  document.getElementById("demo").innerHTML = "Restam apenas " + days + "d " + hours + "h "
  + minutes + "m " + seconds + "s para o fim da promoção";
 }else if (hours==0 && minutes==0){
  document.getElementById("demo").innerHTML ="Restam apenas " + seconds + "s para o fim da promoção";
 }else if (hours==0){
  document.getElementById("demo").innerHTML ="Restam apenas " + minutes + "m " + seconds + "s para o fim da promoção";
 }else{
  document.getElementById("demo").innerHTML ="Restam apenas " + hours + "h "+ minutes + "m " + seconds + "s para o fim da promoção";
 }

}, 1000);

Para um teste rápido coloque var dia = dataDiaDaSemana("...."); sendo .... o dia de hoje e em dia.setHours(0,0,0,0); hora atual e um minuto após o minuto atual exemplo, se são 12:25 coloque dia.setHours(12,26,0,0);
Comment: Perfeito, era isso mesmo que eu precisava, muito obrigado, de verdade, salvou meu dia kk
Comment: @DanielHirt para um teste rápido coloque `var dia = dataDiaDaSemana("sabado");` e em `dia.setHours(0,0,0,0);` hora atual um minuto apos o minuto atual exemplo, se são 12:25 coloque `dia.setHours(12,26,0,0);`


Why Should I always follow the rules of functional harmony?

Question: I have used functional harmony many times in my compositions to write chord progressions with success, however there are times when using functional harmony doesn't sound good to me and others when I have written chord progressions that don't follow the rules of functional harmony and still sound good, at least to my untrained ears.
So, why should I try to always follow the rules for functional harmony when writing chord progressions?
Comment: Maybe the question should be prefaced by the word WHY.
Comment: You'd be shocked how many chord progressions follow functional harmony, let alone common practice period harmony, even if they don't sound like they do at first blush. For example, the chord progression G-B-C-Cm-G can be explained with common practice period harmony as I-V/vi-VI/vi = IV-iv-I.
Answer: Those rules are more like guidelines. If all music had to stick to the 'rules', it would have run out of new ideas years ago!
You can do whatever you like with music, chord progressions, etc., and have people give their opinions on the results. In the past, composers have 'thrown out the rule book' (whatever that may be!), and produced weird and wonderful compositions. Some just weird, some wonderful! It will depend on the genre used, and your targetted audience, as to whether it is accepted, but the old adage - if it sounds good, it probably is - usually rings true. Some may question your motives, but by 'breaking the rules', you're going to be pushing the boundaries of an art in the right direction.
Comment: I'm so glad to see the word "art" in your answer, +1. Too many people get hung up on what is "right and wrong" once they start reading their first music theory or harmony book.
Answer: No.  Functional harmony is great.  So is non-functional harmony.  It's good to trek the mountains heading for a destination, it's good to sit by the lake watching the colours of the light on the water.   And it's good to mix the two.
When you find something that sounds interesting it can be productive to analyse WHY it sounds interesting, and that won't always lead to a functional explanation (so stop knocking yourselves out, guys!).  Or just give it a name, so you can find it again next time.
'Why' can be a very tricky question.  Why does G7 want to resolve (functionally) to C?  Because it contains the tritone, F-B, which wants to resolve to E-C. Yes, but WHY does a tritone want to...
I wonder if you'll manage to do without the basic functional concept of a tonic?   It can be done...
Answer: Your question is, as the scientists like to say, not even wrong. And that is remarkably good news!
It is incredibly important to remember that above all else, music is subjective, not objective. Music theory is descriptive, not prescriptive - it attempts to explain post-hoc why music sounds good but cannot predict with certainty whether certain effects will be effective. It is very tempting to treat music theory the same way we treat math or physics, where it has firmly-established rules and a rigorous nature, that following those rules will produce good music, and that breaking those rules will produce music that lacks artistic merit or sounds cacophonous. But this is a serious mistake to make.
Artistic taste and a good ear are the true judges of music. Music theory is just a tool.
Treating music theory as more rigorous than it truly is is an easy mistake to make. There's actually a surprising and frankly dark history to it. It's not a mistake one comes to because of laziness or lack of imagination, but because highly-respected people who really should have known better have pushed absurd ideas for decades. In the twentieth century, when the United States saw communism as an existential threat and was mired in profound systematic racism, some musicians tried to create a music theory that could predict with mathematical power whether music would sound good. This seemed like a good-faith experiment at the time, but in retrospect, there was a subtext, intended or not, of finding a way to claim that non-western music was objectively bad and harmful.
This video essay from YouTube bassist Adam Neely goes into some of this history:

 (Content warning: discussions of racial topics)
From this embarrassing history, we have the unfortunate legacy of well-meaning musicians like yourself feeling afraid of experimenting with the boundaries of music theory. Your question indicates that you are genuinely nervous that using non-functional harmony will ruin the artistic value of your music, but the fact that you're still asking the question is proof that it's something your heart and your ear are urging you to try anyway. I encourage you to reject the unfortunate parts of your music heritage that trap you in a straightjacket. Embrace the much longer and much richer tradition of music being about self-expression and the joyful exploration of sound. Feel free to push boundaries, experiment with the rules, and develop your own personal palette of musical ideas that resonate with you. And when you use music theory, use it as a tool to expand your horizons, not to limit yourself to what others have decreed acceptable.
Comment: I think I've read about a more modern version that tries to predict with mathematical power how *catchy* a piece is instead. I also think I've read that the modern version is shockingly accurate.
Comment: @Dekkadeci I am very skeptical. Call Me Crazy, Hey Jude, It Don't Mean a Thing (If It Ain't Got That Swing), and Sandstorm by Darude are all catchy songs, but they come from completely different musical traditions and use completely different music theory. If you mean that chart toppers use music theory, well, yes, they do. But they are also produced with teams of highly experienced musicians being given millions of dollars to come up with music for the explicit purpose of selling well. Of _course_ the music they make is going to be catchy!


How to approach making a GAN where row order does not matter

Question: I am working on a project that has the aim of generating "recipes" which are the summation of "ingredients" (1-dimentional length N tensors, where each index is a value that represents how much of a characteristic this ingredient has).
My current plan for each recipe is to have a 2d tensor made from the 1d ingredients:
[[ ingredient 1 ],
[ ingredient 2 ],
<code>   ...
</code>
[ ingredient K ]]
An issue is that each recipe has a variable number of ingredients. My planned solution was to add empty ingredients to fill out the length of the recipes so they are all the same, but feedback on this would be appreciated.
The goal is to have the generator learn which combinations of characteristics go together and in what amounts. The thing is that the order of these ingredients does not matter. If I did not need the ingredients themselves I would be training this on the summation of all ingredients per recipe.
What is the best way to approach this? My first instinct is to randomize the order of the ingredients and train with every possible combination, but I do not know enough of how GANs function to tell if this would be a bad approach.
Any feedback/links to related work would be appreciated, thanks
Comment: Please edit the question to limit it to a specific problem with enough detail to identify an adequate answer.
Comment: Why not do something similar to dummy encoding, where the universe of possible ingredients is enumerated as a vector and then you fill in each element with the amount of the ingredient (or zero, which is also an amount)?
Comment: My reasoning for this approach was that ideally the GAN would be able to make connections with the attributes within each ingredient, though the dummy encoding approach could possibly end up with the same result just by how the ingredients are combined.
I will probably end up going with that if other options do not seem to be working.
Answer: Variable length with permutation invariance for generative networks is very hard and no method that I know of currently tackles both at the same time with good success rate.
If you only need variable length outputs RNNs are used for the time dimension and CNNs are used for the spatial dimension.
However for your case, is there anything preventing you from just outputting a single very large vector, with each index corresponding to one ingredient? That would take care of the permutation problem.
For example, if you have 32 ingredients with 3 attributes each, you could output 3 vectors of size 32. Missing ingredients can be set as 0 in all attributes.
Comment: Thank you for the feedback. That is an interesting idea.

Do you think that would perform better than a recipe with the maximum number of ingredient vectors, but the "slots" that are not involved are all empty?

Something like this?
[[ att0, att1, att2 ],

 [ att0, att1, att2 ],

 [ 0, 0, , ],

 [ 0, 0, , ]].

I guess your suggestion method would address the ordering of ingredients issue better.


Drupal Ajax Form Add More error - Buttons duplicate and outside of fieldset

Question: I have added an add field button to a module form.  The fieldset displays properly and the callback works one time - I click the add more button, and my fields add properly.
The issue is when I click it a second time...the fields add to the form, but outside of the fieldset, and the add/remove buttons start to duplicate.
Here is my form and callback functions...basically copied directly from the example module.  I'm leaving the entire form...the top part is a bunch of other fields, the AJAX fields and function are at the bottom.  I've spent 2 days fiddling...so I'd very much appreciate some direction!
    function _nnreport_shipping_new($form, &$form_state) {
    $jobId = $_GET['id'];
    $job = new stdClass();
    $job = _nnjob_retrieve_jobid($jobId);

    $form['jobId'] = array(
           '#type'=>'hidden',
           '#value'=>$jobId, );
    $form['rigId'] = array(
        '#type'=>'hidden',
        '#value'=>$job->rigId,);
    $form['clientId'] = array(
        '#type'=>'hidden',
        '#value'=>$job->clientId, );
    $form['clientsName'] = array(
            '#type'=>'hidden',
            '#value'=>$job->clientName, );
    $form['wellsName'] = array(
            '#type'=>'hidden',
            '#value'=>$job->wellName, );
    $form['rigCo'] = array(
            '#type'=>'hidden',
            '#value'=>$job->rigCoId, );
    $form['fullRig'] = array(
            '#type'=>'hidden',
        '#value'=>$job->rigCompanyName.' '.$job->rigName, );
    $form['jobIdTitle'] = array(
            '#markup' => '
For:  ' .$job->clientName. ' | '.$job->rigCompanyName.' '.$job->rigName. ' | '.$job->wellName. ' | ' ._nnjob_format_job_id($jobId).'
', );
    $form['date'] = array(
            '#markup' => '
Date<input type="date" data-clear-btn="true" name="date" id="date" value="">
',

        );

     $form['carrier'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Carrier:'),
        '#required' => FALSE,);
    $form['carrierPhone'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Carrier Phone:'),
        '#required' => FALSE,
        //'#suffix' => '

',
        );

    $form['origin'] = array(
        '#type' => 'textarea',
        '#cols' => 30,
        '#rows' => 5,
        '#title' => t('Origination:'),
        '#prefix' => '

',
        );

    $form['fromContact'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Contact:'),
        '#required' => FALSE,);

    $form['destination'] = array(
        '#type' => 'textarea',
        '#cols' => 30,
        '#rows' => 5,
        '#title' => t('Destination:'),
        '#required' => FALSE,
        '#prefix' => '

',

        );

    $form['destContact'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Contact:'),
        '#required' => TRUE,
        '#suffix' => '

',
        );

    $form['#tree'] = TRUE;

    $form['items_fieldset'] = array(
    '#type' => 'fieldset',
    '#title' => t('Shippment Inventory Items:'),
    '#prefix' => '
',
    '#suffix' => '
',
    );

     if (empty($form_state['num_items'])) {
    $form_state['num_items'] = 1;
    }

     for ($i = 0; $i < $form_state['num_items']; $i++) {

    $form['items_fieldset'][$i] = array(
    '#prefix' => '
',
    '#suffix' => '
'
    );

    $form['items_fieldset'][$i]['amount'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Amount:'),
        '#required' => TRUE,
        '#prefix' => '

',

    );

    $form['items_fieldset'][$i]['description'] = array(
        '#type' => 'textfield',
        '#size' => 50,
        '#title' => t('Description:'),
        '#required' => TRUE,
        '#prefix' => '

',
        );

    $form['items_fieldset'][$i]['serial'] = array(
        '#type' => 'textfield',
        '#size' => 30,
        '#title' => t('Serial Number:'),
        '#required' => TRUE,
        '#prefix' => '

',
        '#suffix' => '

',

            );
    }

    $form['items_fieldset']['add_items'] = array(
    '#type' => 'submit',
    '#value' => t('Add more'),
    '#submit' => array('_nnreport_shipping_new_add_one'),
    '#ajax' => array(
        'callback' => '_nnreport_shipping_new_callback',
        'wrapper' => 'items-fieldset-wrapper',
        //'method' => 'after',
    ),
    );

    if ($form_state['num_items'] > 1) {
    $form['items_fieldset']['remove_items'] = array(
    '#type' => 'submit',
    '#value' => t('Remove one'),
    '#ajax' => array(
        'callback' => '_nnreport_shipping_new_callback',
        'wrapper' => 'items-fieldset-wrapper',

//added this prevent  and limit validation error as another attempt...didn't change anything

'prevent' => 'submit click mousedown',
        ),
    '#limit_validation_errors' => array(),
    '#submit' => array('_nnreport_shipping_new_remove_one'),
    );
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
      );

    return $form;

    }

    function _nnreport_shipping_new_add_one($form, &$form_state) {
      $form_state['num_items']++;
      $form_state['rebuild'] = TRUE;
    }

    function _nnreport_shipping_new_callback($form, $form_state) {
    return $form['items_fieldset'];
    }

    function _nnreport_shipping_new_remove_one($form, &$form_state) {
      if ($form_state['num_items'] > 1) {
        $form_state['num_items']--;
      }
      $form_state['rebuild'] = TRUE;
    }

Answer: There are some errors with opening and closing divs that you declare in the #prefix.
See the code below where I simply removed your #prefix and #suffix definitions. If there are unclosed divs in the markup it will create problems such as the one you mention with the new markup ending up outside the fieldset.
So simply replace the definition of
$form['items_fieldset'][$i], $form['items_fieldset'][$i]['amount'], $form['items_fieldset'][$i]['description'] and $form['items_fieldset'][$i]['serial'] with the code below.
$form['items_fieldset'][$i] = array(
  '#prefix' => '
',
  '#suffix' => '
'
);

$form['items_fieldset'][$i]['amount'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Amount:'),
  '#required' => TRUE,
);

$form['items_fieldset'][$i]['description'] = array(
  '#type' => 'textfield',
  '#size' => 50,
  '#title' => t('Description:'),
  '#required' => TRUE,
);

$form['items_fieldset'][$i]['serial'] = array(
  '#type' => 'textfield',
  '#size' => 30,
  '#title' => t('Serial Number:'),
  '#required' => TRUE,
);

Comment: That did it! Got to love that it came down to the markup, I didn't even consider that by the nature of the buttons glitching.  Thanks again.


Is there a hidden triplet here, as the notes seem to indicate 9/8 but the time signature is 4/4?

Question: I found this strumming in a book which confused me a lot:

It seems it has 9/8 but states clearly that it should have 4/4. I tried to figure it out and stumbled over triplets. So my guess is it has a hidden triplet?
I would appreciate a pointer in the right direction to figure out how to play this strumming.
Answer: It is a 4/4 measure. Below I marked the quarter-note groups.
Perhaps you're confused by the dots below two of the notes. They indicate staccato articulation, rather than dotted note (1.5 duration) where dot would be placed right from the note, as the dot next to one of the eight-note rests below.
Comment: @Arsak To me it's clearly staccato. The dot is below the note head. It looks fine to me. I think people sometimes confuse dotted notes and staccato because if they are unfamiliar with staccato marks.
Comment: Do you know whether it's common to indicate *staccato* like this (in rhythmic notation)? I understand OP's confusion and would have expected the *staccato* dots further to the left, below the lower left part of the note heads.


UITableViewCell no being dequeued properly

Question: enter code hereI know, there are a ton of posts like this, but my cell's are not being dequeued properly. Anything I might be missing? I always do it like this, and world! I'm not sure what I might be getting wrong in this case.
static NSString *FSStandardFormCellIdentifier = @"FSStandardFormCell";
FSStandardFormCell *cell = [tableView dequeueReusableCellWithIdentifier:FSStandardFormCellIdentifier];

if (cell == nil) {
    NSLog(@"cell was not dequeued");
    cell = [[FSStandardFormCell alloc] initWithReuseIdentifier:FSStandardFormCellIdentifier];
}

Here's my custom initializer:
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self) {
        self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([FSStandardFormCell class]) owner:self options:nil][0];
    }
    return self;
}

Thank you!
Comment: Voted to close, problem caused by a typo.
Comment: What do you mean by my cell's are not being dequeued properly?
Comment: I do some english mistakes now and then. They were not being dequeued at all. Fixed now.
Comment: so when you enter initWithReuseIdentifier you get nil for self?ž
Answer: My Cell Identifier, defined in interface builder did not match the cell identifier in:
static NSString *FSStandardFormCellIdentifier = @"FSStandardFormCellIdentifier";

After that, all was good.
Answer: This:
- (id)initWithReuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    if (self) {
        self = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([FSStandardFormCell class]) owner:self options:nil][0];
    }
    return self;
}

Is so wrong. On so many different levels.
Look, I'm not going to go in detail on why this code will make most people's eyes bleed, but in your particular case just use this code to solve your problem:
static NSString *FSStandardFormCellIdentifier = @"FSStandardFormCell";
FSStandardFormCell *cell = [tableView dequeueReusableCellWithIdentifier:FSStandardFormCellIdentifier];

if (cell == nil) {
    NSLog(@"cell was not dequeued");
    cell = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([FSStandardFormCell class]) owner:nil options:nil][0];
}

Comment: I changed to your suggestion, and then changed back, because I need to do some custom initialisation that is not explicit here. Is it because I'm calling super on the custom initialiser, without needing to?
Comment: No, you should call super. What you're doing is overriding your call to super by this line `self = [[NSBundle mainBundle]...`. If you want to do the custom initialization, still do the same approach I've suggested for you, but define a new method inside your table cell `- (void)awakeFromNib` and perform your initialization in it.
Comment: It feels strange to call super, if we're calling loadNibNamed: anyways. Would this be more appropriate? a custom method. -(id)loadFromNib { return [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([FSStandardFormCell class]) owner:self options:nil][0]; }
Comment: It seems like you don't understand how subclassing works. In initialization methods you HAVE to call super. And `-awakeFromNib` is called automatically when you load your view via loadNibNamed method so you could perform additional customization on it.
Comment: I do understand how subclassing works. But if loadFromNib returns an object, then a constructor must have been called somehow?


URISyntaxError when I called request.setURI(new URI(url)) while url is working fine on all browsers

Question: I have a problem that when I call a url with many parameters for JSON response, then it shows an URISyntaxError but the same url is working fine on all browsers. I unable to understand what is going wrong?
The URL is: http://apibeta.highgearmedia.com/v1/vehicles/get-make-models.json?sort=mpg&filter=category&client-id=10030812&from=convertible&signature=QOwiWhG2T47KaQoyUztbag==

Code:
HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(api_url));

            HttpResponse response = client.execute(request);
            InputStream ips = response.getEntity().getContent();
            BufferedReader buf = new BufferedReader(new InputStreamReader(ips,
                    "UTF-8"));

            StringBuilder sb = new StringBuilder();
            String s;
            while (true) {
                s = buf.readLine();
                if (s == null || s.length() == 0)
                    break;
                sb.append(s);

            }
            buf.close();
            ips.close();
            return sb.toString();

Error:
05-10 23:03:45.326: W/System.err(2227): java.net.URISyntaxException: Illegal character in query at index 161: http://apibeta.highgearmedia.com/v1/vehicles/get-make-models.json?sort=mpg&filter=category&client-id=10030812&from=convertible&signature=QOwiWhG2T47KaQoyUztbag==
05-10 23:03:45.326: W/System.err(2227):     at java.net.URI.validateQuery(URI.java:434)
05-10 23:03:45.326: W/System.err(2227):     at java.net.URI.parseURI(URI.java:340)
05-10 23:03:45.335: W/System.err(2227):     at java.net.URI.<init>(URI.java:72)
05-10 23:03:45.335: W/System.err(2227):     at com.TCC.android.ResearchList.getJsonSring(ResearchList.java:3892)
05-10 23:03:45.335: W/System.err(2227):     at com.TCC.android.ResearchList$67.run(ResearchList.java:4077)

Answer: Here is solution if your problem, a function that will remove all invalid characters from the url .Pass your url in this function and you will get a new url with encoded strings.
public static String convertURL(String str) {

    url = null;
    try{
    url = new String(str.trim().replace(" ", "%20").replace("&", "%26")
            .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
            .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
            .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
            .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
            .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
            .replace(";", "%3B").replace("?", "%3F").replace("@", "%40")
            .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
            .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
            .replace("|", "%7C").replace("}", "%7D"));
    }catch(Exception e){
        e.printStackTrace();
    }
    return url;
}

Answer: According to java URI javadoc, and to the underlying RFC (§2.2 and 3.4), = is a reserved char and should be escaped (%3D for =)
By the way, you should use android.net.URI
Comment: Problem remains same, android.net.Uri is not supported with request.setURI(new Uri(api_url)); and %3D not works instead of =


Duvida Passando Array Laravel Routes

Question: A duvida é o seguinte, no meu gerador de PDF, quando clico em gerar, ele gera um pdf com todas as informações que estão contidaa nas tabelas do banco de dados, então estou na dúvida dom como passar apenas o array, que é achado quando é feito uma pesquisa.
Exemplo:

Esta é minha tela com todas as informações, se eu clicar em Download pdf, o pdf gerado terá todas essas informações.
Abaixo é a tela de pesquisa onde me veio apenas uma informação:

Agora se eu clicar no Download PDF, ele irá gerar um pdf com todas as informações e não apenas com o que foi buscado.
Uma modificação que pensei para ele gerar o pdf apenas com as informações pesquisadas, é passar o array que contém as informações das tabelas como parâmetro para a geração do URL:
HTML, botão que gera o pdf:

Download em PDF

Minha Rota:
Route::any('/listar/pdf/{$catraca}', 'CatracaControler@metodopdf')->name('Relatorio');

A função da Requisição da Pesquisa, é a que me retorna o array de pesquisa:
public function lista(Request $request){

    $aux = $request->texto;

    $catraca = Catraca::where('MATRICULA', 'like', '%'.$aux.'%')->orWhere('NOME', 'like', '%'.$aux.'%')->orWhere('NUM_CARTAO', 'like', '%'.$aux.'%')->orWhere('MATRICULA', 'like', '%'.$aux.'%')->get();

    return view('catraca.listagem')->with('catraca', $catraca);
}

E a função de gerar o pdf que recebe como parâmetro o array que foi gerado na função acima.
public function metodopdf($catraca){

    return \PDF::loadView('catraca.layoutpdf', compact('catraca'))->setPaper('a4', 'landscape')->stream('relatorio.pdf');
}

Mas isso me gera o seguinte erro na rota:

A mensagem de erro diz que a rota está errada pela falta de parâmetros.
Minha dúvida é: É possível passar um array como parâmetro para rotas? Para ser capturado pela função Gerar pdf?
Answer: A função (helper) permite que passe um array como segundo parâmetro tal e qual como nos parâmetros das rotas, veja o helper route veja: https://laravel.com/docs/5.6/helpers#method-route
No seu está a passar uma collection resultante da seguinte linha de código
 $catraca = Catraca::where('MATRICULA', 'like', '%'.$aux.'%')->orWhere('NOME', 'like', '%'.$aux.'%')->orWhere('NUM_CARTAO', 'like', '%'.$aux.'%')->orWhere('MATRICULA', 'like', '%'.$aux.'%')->get();

Possível solução
No action passa a chave de pesquisa que usou para listar

Download em PDF

Ao gerar a listagem também passa para a view a chave de pesquisa usada para listagem (em alternativa pode criar uma método private para devolver o query para os dois métodos)
public function lista(Request $request){

    $aux = $request->texto;

    $catraca = Catraca::where('MATRICULA', 'like', '%'.$aux.'%')->orWhere('NOME', 'like', '%'.$aux.'%')->orWhere('NUM_CARTAO', 'like', '%'.$aux.'%')->orWhere('MATRICULA', 'like', '%'.$aux.'%')->get();

    return view('catraca.listagem')->with(['catraca'=> $catraca, 'chavepesquisa'=> $aux]);
}

Para gerar o pdf recebe a chave de listagem e repete o query
public function metodopdf($chavedepesquisa){

//repete a consulta à base de dados
$catraca = Catraca::where('MATRICULA', 'like', '%'.$aux.'%')->orWhere('NOME', 'like', '%'.$aux.'%')->orWhere('NUM_CARTAO', 'like', '%'.$aux.'%')->orWhere('MATRICULA', 'like', '%'.$aux.'%')->get();

return \PDF::loadView('catraca.layoutpdf', compact('catraca'))->setPaper('a4', 'landscape')->stream('relatorio.pdf');

}
Comment: apareceu isso aqui:

"Too few arguments to function App\Http\Controllers\CatracaControler::metodopdf(), 0 passed and exactly 1 expected"
Comment: O action espera um array action('CatracaControler@metodopdf', [$chavepesquisa]), já corrigi no exemplo
Answer: Eu sugiro a você, ao invés de passar um array com os valores, passar novamente a variável usada na pesquisa, e refazer essa pesquisa antes de gerar o pdf. Assim não precisa fazer a mesma coisa de duas maneiras diferentes!
Crie uma função na sua model Catraca:
function pesquisa($aux){
    return Catraca::where('MATRICULA', 'like', '%'.$aux.'%')->orWhere('NOME', 'like', '%'.$aux.'%')->orWhere('NUM_CARTAO', 'like', '%'.$aux.'%')->orWhere('MATRICULA', 'like', '%'.$aux.'%')->get();
}

Isso feito, você chama o método Catraca::pesquisa($aux) onde quiser, inclusive nas funções de geração de pdf, e na pesquisa em si, e pode continuar usando apenas um parâmetro. Fica mais limpo e fácil de entender para outros.
Espero ter ajudado!
Comment: Não entendi muito bem como vc quis fazer :x
Comment: O que você não entendeu exatamente? Mas, o fato é que você quer passar um array de resultados da sua pesquisa, certo? Então que tal, ao invés de passar o array do resultado da pesquisa, fazer a pesquisa novamente? Mais prático pois, veja bem: Você enviou o termo de pesquisa ao servidor, recebeu o resultado, e agora quer enviar o resultado de volta pro próprio servidor! O que eu disse foi basicamente, fazer a pesquisa de novo!
Answer: Cara, você pode passar um Json na sua rota, utilize as funções json_encode() e json_decode() e boa sorte!

Duvida Passando Array Laravel Routes


Programatically save comma-separated string as value of taxonomy field

Question: I have a comma-separated string $string of the form "term1,term2,term3" and I would like to save it as the value of a taxonomy term field that is attached to my node. I have tried
$node->field_taxonomy[LANGUAGE_NONE][0]['value'] = $string;
node_save($node); but this throws me an error "Warning: Illegal string offset 'tid' in taxonomy_field_presave()" coming from Taxonomy module.
What is the correct way to set the value of $node->field_taxonomy?
I also need that when node_save($node); is executed, taxonomy terms that had not been taxonomy terms before are created, just like it would happen when I set the value of $node->field_taxonomy via the user interface. I was expecting this to happen automatically when I set and save the taxonomy field value.

Edit: Actually, I am trying to attach taxonomy terms to files, but I thought that the analogous setup of nodes would be more familiar to most people.
I have attached a description field (field_description) and a taxonomy field (field_hashtags) to files via the user interface, using File Entity Module. I now want to upload files and fill in their attached fields using a custom file upload form, but on the custom file upload form there is only

a field for the file itself ($form['file'] of type managed_file) and
a field for the description that the file should be given ($form['description'] of type textarea).

My CUSTOMMODDULE_form_submit() function now defines $submitted_file = file_load($form_state['values']['file']);, i.e. as the submitted file, and $submitted_description = $form_state['values']['description'];, i.e. as the submitted description.
It then sets $submitted_file->field_description[LANGUAGE_NONE][0]['value'] = $submitted_description; and, as expected, when saving the file via file_save($submitted_file); the description field of the file is saved being populated with the submitted values.
However, before saving the file I run a custom function that returns a comma-separated string of hashtags (all words from the submitted description that start with '#') that were used in the description. I now want to set $submitted_file->field_hashtags as exactly those terms from the string that my custom function returns, just like I would enter a comma-separated string into a taxonomy field by hand from the user interface.
Edit 2: I further tried the following code from taxonomy.module
$terms = explode(',', $string);
$voc = taxonomy_vocabulary_machine_name_load('vocabulary_name');
$vid = $voc->vid;

foreach ($terms as $key => $term) {
  if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($term), 'vid' => $vid))) {
            $term = array_pop($possibilities);
        }
        else {
        $term = array(
          'tid' => 'autocreate',
          'vid' => $vid,
          'name' => $term,
          'vocabulary_machine_name' => 'vocabulary_name',
        );
        }

        $term_array = (array) $term;
        $node->field_taxonomy[LANGUAGE_NONE]['$key'] = $term_array;
    }
but this gives me "Error
Error message
PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '$key' for column 'delta' at row 1:"
Comment: Remove the single quotes around `$key` when you store the value in the node array (`$node->field_taxonomy[LANGUAGE_NONE][$key] = $term_array;`). PHP doesn't expand variable names for single quoted strings, and besides, it's superfluous. Right now you're literally trying to store the string "$key" to an integer-type column, thus the error.
Comment: I can't believe this solved the whole issue. Thank you so much. I will now do some testing and get back to everyone.
Answer: try that:
$terms = explode(',', $string);
foreach ($terms as $key => $term) {
  $node->field_taxonomy[LANGUAGE_NONE][$key]['value'] = $term;
}

Comment: It gives me the following error: `Notice: Undefined index: tid in taxonomy_field_presave() (line 1889 of modules\taxonomy\taxonomy.module).`
Comment: Can you provide more information, for example in which function you use this code block etc.
Comment: Please see my edit in the original post.
Answer: This function worked for me:
/**
 * Return the term id for a given term name.
 */
function _get_tid_from_term_name($term_name) {
  $vocabulary = 'tags';
  $arr_terms = taxonomy_get_term_by_name($term_name, $vocabulary);
  if (!empty($arr_terms)) {
    $arr_terms = array_values($arr_terms);
    $tid = $arr_terms[0]->tid;
  }
  else {
    $vobj = taxonomy_vocabulary_machine_name_load($vocabulary);
    $term = new stdClass();
    $term->name = $term_name;
    $term->vid = $vobj->vid;
    taxonomy_term_save($term);
    $tid = $term->tid;
  }
  return $tid;
}

In your case it can be called like this:
$terms = explode(',', $string);
foreach ($terms as $term_name) {
  $tid = _get_tid_from_term_name($term_name);
  $node->field_taxonomy[LANGUAGE_NONE][] = array('tid' => $tid);
}

I just tested it for myself and it worked.
If you are using another vocabulary (different from Tags), then modify in the code above the line:
$vocabulary = 'tags';


Even polynomials on $[0,1]$ instead of $[a,b]$

Question: This question is 'part' of another question that I asked here days ago.(Althoug this is a new question)
I've the following exercise:
Prove that every continuous function f:[a,b]$\rightarrow \mathbb R$ is the uniform limit of a sequence of even polynomials if and only if (a,b) doesn't contain the origin.
Proof:
Suppose (a,b) doesn't contain the origin.
And for simplicity consider $[0,1]$ instead of [a,b].
It's equivalent to work with $[0,1]$ because of this proof by @zhw at From [a,b] to [$0$,$1$]:
Suppose we have the result for $[0,1].$ If now $f\in C([0,b]),$ define $g:[0,1] \to [0,b]$ by setting $g(x) = bx.$ Then $f\circ g \in C([0,1]).$ So there exists a sequence $P_n$ of even polynomials such that $ P_n \to f\circ g$ uniformly on $[0,1].$ This implies $P_n\circ g^{-1} \to f$ uniformly on $[0,b].$ Since each $P_n\circ g^{-1}$ is an even polynomial, we have the result for $[0,b].$
If now $0<a<b$ and $f\in C([a,b]),$ we can extend $f$ to a continuous function $F$ on $[0,b],$ simply by setting $F(x) = f(a)$ for $x\in [0,a).$ By the above, there is a sequence $P_n$ of even polynomials such that $ P_n \to F$ uniformly on $[0,b].$ This of course implies $ P_n \to F$ uniformly on $[a,b].$ Since $F=f$ on $[a,b],$ we have the desired result for $[a,b].$
But, I don't know how the result for intervals $[a,b]$ with $a<b\le 0$ will be?
Can somebody help me?
Comment: When you copy a proof verbatim from another poster, as you did with my proof above, you should give a link to it. I've edited you post to include the link.
Comment: Once you have a proof for the case $0\leq a'<b',$ then for the case $a<b\leq 0$ let $b'=-a$ and $a'=-b.$  And let $g(x)=f(-x).$ And apply the case $0\leq a'<b'$ to $g$.
Comment: ok and to give you credits too @zhw.
Comment: @DanielWainfleet If I let $g(x)=f(-x)$, how will I apply the case $0 \leq a'<b'$ to $g$ .Because I think in the case $0 \leq a'<b'$  we didn't use $g$, we just expand f to F and then we obtain the result
Answer: If $0\not \in (a,b)$, extend $f$ to a continuous even function on $[-c,c]=[-\max(|a|,|b|),\max (|a|,|b|)]$ and let $(g_n)_n$ be a sequence of polynomials  converging  uniformly to $f$ on $[-c,c]$.  Let $h_n(x)=(g_n(x)+g_n(-x))/2.$ Then $(h_n)_n$ converges uniformly to $f$ on $[-c,c]$ and, a fortiori, on $[a,b]$.
If $0\in (a,b)$ consider the case $f(x)=x-a$ which is not an even function.  A point-wise limit, and a fortiori, a uniform limit, of a sequence of even functions is even.
Comment: seems like you didn't follow your hint from before (this answers looks more difficult)
Comment: I didn't follow my hint. It seemed you had 3/4 of an answer already. My hint was about the rest. But I didn't understand your difficulty so I put up a general A.


What is a monotonic increasing function $[0,1] \to [0,1]$?

Question: I am looking for a monotonic increasing function in $[0,1]$ , with the following specification:

$f(0) = 0$
$f(1) = 1$
should contain one parameter
for a given choice of this parameter should give the identity function $f(x) = x$
for other values of the parameter the shape shall be skewed, like $f(0.25) = 0.5$ , $f(0.75) = 0.9$ or something.
should be continuous
should be strong monotonic increasing, i.e. $f(a)>f(b)$ if $a>b$.
should be in closed form.

I am not sure how to describe it better, so please ask if something is unclear.
Comment: There are many choices, for example $x^\alpha$ for suitable $\alpha$,  which could be constant but need not be.
Comment: Linearly interpolate between the points $(0,0), (a, 1-a), (1,1)$.
Comment: The obvious choice is $f(x) = 0$ on $[0, a]$, and $f(x) = 1$ on $(a, 1]$. If you want a continuous function, you could instead linearly interpolate between points $(a, 0)$ and $(1,1)$. If you want a differentiable one, you could do the usual smoothing-out trick at point $(a, 0)$ using a multiple of $e^{-x^2}$.
Comment: Thanks. I have updated my question. Function should be continuous...
Comment: Of course the power function, thats what I was looking for!! Thanks a lot André, that is the function I was looking for!
Comment: You are welcome.  For your example, $\alpha=1/2$ will give a sort of OK fit.
Answer: As André Nicolas wrote in the comments:

There are many choices, for example $x^\alpha$ for suitable $\alpha$, which could be constant but need not be. For your example, $\alpha=1/2$ will give a sort of OK fit.


How to Combine Univariate GARCH Models?

Question: We fitted univariate GARCH models to several time series. We would like to make sure that the forecasts also consider the correlation structure between the time series.
The literature presents some multivariate GARCH models which can be directly fitted to multivariate time series. However, we would prefer to combine the univariate GARCH models by somewhat imposing the correlations on top of the forecasts.
Do you have some ideas? Thanks.
Comment: Two good reviews of multivariate GARCH models are Bauwens et al. ["Multivariate GARCH models: A survey"](http://www.city.ac.uk/__data/assets/pdf_file/0004/78952/BauwensLaurentRomboutsJAE2006.pdf) (2006) and Silvennoinen & Teräsvirta ["Multivariate GARCH models"](http://www.econstor.eu/bitstream/10419/56218/1/538862637.pdf) 2009.
Comment: Thanks, @RichardHardy. I had found Bauwens but I think it is a bit too theoretical. I'll have a look at Silvennoinen. Thanks again.
Comment: Personally, I found Bauwens et al. easier than S. & T., but it was a while ago, so I don't really remember well.
Answer: A few options:

Fit a correlation matrix to the standardized residuals. GARCH gives you time-varying volatility, so divide the input to the GARCH model by the time-varying standard deviation. This gives standardized residuals that you can fit a correlation matrix to.
Use a copula. This approach is similar to the above, but provides a little bit more freedom. For instance, you could more easily handle GARCH models with $t$ distributions.
Model the time-varying correlation. There are multivariate versions of GARCH, e.g. DCC GARCH, that could handle the univariate and multivariate time-varying volatility jointly.
Comment: Very solid answer. Thanks @John. I think the 2. approach will be followed.

How to Combine Univariate GARCH Models?


why is message.channel.awaitMessages() not working? | Discord.js V13

Question: I'm trying to collect a message after a certain message a user has sent in a specific channel. So the user would send say hello world then await messages would wait for a response from a specific user and grab that message's ID. However, it doesn't work.
Here is my code:
let filter = message => {
    return message.author.id == 'ID OF USER';
}

if(message.channel.id == 'channel id of sent message') {
            console.log('here');
            if(message.content.valueOf("hello world")) {
                console.log('here');
                message.channel.awaitMessages(bumpFilter, { max: 1, time: 5000, errors: ['time']})
                .then(c => {
                    console.log('here');
                    console.log(c);
                });
            }
        }

In the console, here is logged 2 times. However, the 3rd time is not logged, even after the 5 seconds has passed from this message. The console logs nothing, not even an error, which got me to speculate that maybe it's an discord intents issue, but i don't think that was it either. So i don't understand what's the issue and why I won't get any results. Also, if i assigned message.channel.awaitMessages(...) to a var then logged the var it would output Promise { <pending> } and I read that a .then statement has to be added to avoid that. And now that it is added, it still does not output anything.
Answer: First, if (message.content.valueOf("hello world")) will always return true as the valueOf method returns the primitive value of the specified object. Even if message.content is not "hello world", it's still truthy. You should check if the value of message.content itself is equal to "hello world".
Second, you declare a filter variable but you use bumpFilter in your awaitMessages
And third, in discord.js v13, awaitMessages accepts a single parameter, an options object. (In v12 the first parameter was a filter and the second one is the options).
let filter = (message) => {
  return message.author.id === 'ID OF USER';
};

if (message.channel.id === 'channel id of sent message') {
  console.log('channel matches');

  if (message.content === 'hello world') {
    console.log('message is hello world');

    message.channel
      .awaitMessages({ filter, max: 1, time: 5000, errors: ['time'] })
      .then((c) => {
        console.log('New message collected');
        console.log(c);
      })
      .catch((c) =>
        console.log(`After five seconds, ${c.size} messages are collected.`),
      );
  }
}

Comment: That's great it works :) However, is there a way to get the message ID through c? `c.id` doesn't seem to work just returns `undefined`, What would be the best way to get the ID?
Comment: That's great to hear. `c` is a [collection](https://discord.js.org/#/docs/collection/stable/class/Collection), not a single message. If you only collect one message, you can use `c.first().id` to grab the message ID.
Comment: Thank you very much :D
Comment: You're welcome :)


Implement Google Analytics for Angular1.5 App

Question: I want to implement Google analytics for an Angular SPA which is currently running in my localhost. I tried to copy the google tracking Js code to each of my view in the Angular SPA. But i don't think it actually worked.
Is this the correct way to implement Google Analytics or whats the correct way?

{{'contact-name' | translate}}

Answer: Don't insert the script in each of your views, instead paste it within your main HTML page.
In addition to Google Analytics you might want to consider using Autotrack and the urlChangeTracker in your SPA
Comment: I've found this post to help you getting started: http://stackoverflow.com/questions/30581916/test-google-analytics-on-localhost
Comment: Thanks, i'll try that. I'm currently running my application on my local machine and running at localhost:3000. Will i get any results in GA if i use the URL while setting up as other than localhost:3000, because localhost is invalid at the URL.
Comment: Hey, that helped, thanks. If you have any small code snippet on how Autotrack is being used for Single Page App, can you share that. I'm really confused on where to implement the tracking snippet code.
Comment: Insert the script at the bottom of your body tag just like you did with your Google Analytics script: ` More infos in the docs: https://github.com/googleanalytics/autotrack#installation-and-usage
Comment: hey, could you please refer to this post and help me solve my problem.   http://stackoverflow.com/questions/39731697/google-analytics-on-spa-cant-get-url-changes


Why are ICMP packets not captured on the target interface?

Question: I have a network setup as in the picture:

The central box is a gateway (Ubuntu 15.10) which relays the packets betwen the various networks (only one is shown on the picture - lan0) and Internet.

gateway: I can ping all interfaces and hosts on Internet
laptop: I can ping all interfaces and hosts on Internet except 192.168.0.254

I do not know yet why I cannot ping it, and this is why I am capturing the traffic. This is not my question, though if someone has an idea it is welcome. All interfaces accept all traffic and there is forwarding in place between all interfaces
When capturing packets to understand why the ping fails, I did three tests

ping from laptop to 192.168.0.10

The ping goes through, but tcpdump -i int0 icmp does not show any packets captured

ping from laptop to 192.168.0.254

The ping does not go through and tcpdump -i int0 icmp shows
13:26:28.032635 IP 10.10.10.93 > 192.168.0.254: ICMP echo request, id 1, seq 671, length 40
13:26:32.604606 IP 10.10.10.93 > 192.168.0.254: ICMP echo request, id 1, seq 672, length 40

ping from laptop to 126.96.36.199

The ping goes through and tcpdump -i int0 icmp shows
14:02:52.016081 IP 192.168.0.10 > google-public-dns-a.google.com: ICMP echo request, id 1, seq 749, length 40
14:02:52.029388 IP google-public-dns-a.google.com > 192.168.0.10: ICMP echo reply, id 1, seq 749, length 40

I understand the second case (at least the fact that the echo request is captured).
Why in the first case no packets are captured while the ping goes through?
Why in the third case the capture only shows a request from 192.168.0.10? Where is the one from laptop? (I guess that the reason is the same as above)
Comment: have you enabled IP Forwarding on ubuntu?
`echo 1 > /proc/sys/net/ipv4/ip_forward`
Comment: @tokozedg: yes - this is why (among others) I can ping hosts on Internet
Comment: Is the Ubuntu box configured to do any [NAT](https://en.wikipedia.org/wiki/Network_address_translation) operations?
Comment: @GuyHarris: yes, `int0` masquerades traffic from `lan0`to internet. There is also DNAT to redirect a port on `192.168.0.10` to an internal host.
Answer:
Why in the first case no packets are captured while the ping goes through?

Because you're capturing on int0 but the packet doesn't get sent on int0.  The laptop sends it to the gateway over lan0, and the gateway says "192.168.0.10 - hey, that's me!" and sends a response back on lan0.  It doesn't need to forward the packet to another host on the 192.168.0 network, and therefore doesn't need to send it out on int0.

yes, int0 masquerades traffic from lan0 to internet. There is also DNAT to redirect a port on 192.168.0.10 to an internal host.

Then that might explain "Why in the third case the capture only shows a request from 192.168.0.10?" - the request from the laptop may have had its source IP address modified to be 192.168.0.10 before being sent on int0.
Comment: Thank you. *and the gateway says "192.168.0.10 - hey, that's me!"* - is this exactly "192.168.0.10 - hey, that's me *on another interface*!"? In that case how does this work for the third case?
Comment: "is this exactly "192.168.0.10 - hey, that's me on another interface!""  Yes.  "In that case how does this work for the third case?" Because 220.127.116.11 *isn't* one of the gateway's IP addresses, so it has to forward the packet.


Header e Footer com ASP. Net C#

Question: Estou com duvida para separar meu codigo,fiz alguns testes de ter separado o header e footer mas no visual studio fiz que só pode ter somente uma <% Page, como posso separar o header e o footer e juntar em um só
Comment: Não pode usar as tags do `html5`,  `header` e `footer`?
Comment: posso,mas eu quero dividir em arquivos diferentes e depois chamar eles para todas pages que eu quero usar
Answer: Em ASP .Net você não inclui páginas, como se faz em PHP, você tem q criar uma Layout page, que é uma página completa, tanto com o Helder como o footer, e sua página vai ser um fragmento dentro dessa Layout page.

Header e Footer com ASP. Net C#


Fermat's Little Theorem and prime divisors

Question: Let $a,b\in\Bbb N$ and $a+b$ be an even number.
Assume $a^2 - b^2 - a$ is an exact square, say $c^2$.
Let $m = \frac {a+b}2$ and $n = \frac {a-b}2$.
Then,
$$(4m-1)(4n-1) = 4(4mn-m-n) + 1 = 4(a^2-b^2-a)+1=(2c)^2+1^2 $$
My 2 questions are:

Why does $(2c)^2+1$ have a prime divisor of the form $4k-1$?
Why does it follow from the Fermat's Little Theorem that $4k-1$ divides $2c$ and $1$(thus contradiction)?
Comment: How do you get question part (2) from FMT?
Comment: what do you mean by FMT?
Comment: Oh sorry! I mean FLT (Fermat's Little Theorem).
Comment: Actually, that is the question, how does it follow. I am told that if follows but can't see why.
Answer: Part (1) can be done by a descent type argument.
If a number $N$ has a factor $4k-1$ then either this is prime and we're done or it factorises into two factors $p$ and $q$ with $1 \lt (p, q)\lt N$.
Consider multiplication modulo 4 to get to $4k-1$, which is $3 \mbox{ mod } 4$ we need one of $p, q$ is $3 \mbox{ mod } 4$ and the other is $1 \mbox{ mod } 4$.
WLOG take $p = 3 \mbox{ mod } 4 = 4j-1$ and we are back where we started but with a smaller integer. This process must terminate as the smallest positive integer of this form is $3$ itself.
Thus $2c^2+1$ has a prime divisor of the form $4k-1$.


Change apache (PHP) $PATH environment variable on CentOS with cPanel

Question: I need to add a path to $PATH environment variable for PHP scripts on CentOS linux server with cPanel Pro 1.0 and Apache 2.2.27.
For Ubuntu or SuSE it just means adding the row export PATH=$PATH:/path to /etc/sysconfig/apache2, but this file is missing in sysconfig on CentOS with cPanel (and, of course, script /etc/init.d/httpd is not looking for it). Is it anywhere else (as that would be the solution)?
The answer published here uses PHP itself to change PATH variable, but I'd like to use more robust solution on the Apache level... Any help will be highly appreciated!
Comment: It is important to mention how are you running PHP, is it suPHP, or mod_php?
Comment: The default installation, suPHP
Answer: Edit /opt/suphp/etc/suphp.conf and set env_path to the path string that you want.
Comment: Invalid command 'env_path'...
Comment: What if I change Apache to mod_php? Would that help? It is VPS with only one website, so it is actually even logical choice...
Comment: It is not. suPHP has many advantages over mod_php. Maybe update the suPHP version? It should definitely support that command, see [here](http://www.suphp.org/DocumentationView.html?file=suphp.conf-example).
Answer: It actually was combination of 3 things:

Installation must be mod_php
Then the config file on CentOS with cPanel is /usr/local/apache/bin/envvars; and usual export PATH=$PATH:/path works just fine here
You need to stop/start httpd service, simple restart will not change the environmental variables

Thanks for help!


slideshow images for one specific view, with alot of fields

Question: I have a product content type which has like 10 fields, so I want to show it in my main page with view, the problem is, I want to show it's multiple images as a slideshow, It's not only images that I can use views_slideshow or nivo_slider or any other slideshow modules, I only want the images to be shown as slideshow, along other text-fields of my node.
I would really appreciate any help, thanks
Answer: you can use Field Slideshow. If it's not a good solution, another one would be to create 2 views (one slideshow with only the images, one normal with all the other fields) and, with CSS, position one over the other.
Have fun !
Comment: Then I guess you have to create the two views as I described it :-)
Comment: Thanks Greg, Field slideshow would do the trick, just need to test it, thanks again
Comment: I just saw that your post was in Drupal 6 ; but the module is only Drupal 7... :(
Comment: oh crap, yea i didnt notice that


Select Distinct formatted dates in SQL

Question: I have a table with a large number of datetime entries. I want to select a list of distinct MONTH YEAR strings ordered in descending date order. For example I want to see
October 2012
September 2012
June 2012
July 2011

The query needs to be a distinct because there are multiple entries for each month/day.
This is what I have
SELECT  DISTINCT YEAR(DateRequested), datename(MONTH,[DateRequested])
FROM    [dbo].[MyDateData]
ORDER BY YEAR(DateRequested), MONTH([DateRequested])

but I get this error:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

It feels like I'm almost there but can't get this syntax correct. I am using SQL server 2012 - thanks
Answer: Try;
SELECT monthYear FROM (
SELECT DISTINCT DATENAME(month,dateCol) + ' ' +
                CONVERT(VARCHAR, DATEPART(year,dateCol)) monthYear,
                CONVERT(varchar(6),dateCol, 112) orderCol
FROM yourTable ) A
ORDER BY CONVERT(INT,orderCol) desc

Answer: You just need to ensure that everything in your ORDER BY line is also in your SELECT.
Answer: Try this instead:
;WITH CTE
AS
(
  SELECT  DISTINCT
     YEAR(DateRequested) "Year",
     DATENAME(MONTH,[DateRequested]) "Month"
  FROM YourDateTable
)
SELECT *
FROM CTE
ORDER BY "Year", "Month"

SQL Fiddle Demo

Select Distinct formatted dates in SQL


Angular4 invalid pipe argument

Question: I'm trying to convert in angular a date from this format
'2017-12-13T03:00:00Z[UTC]', to this format 'yyyy/MM/dd'.
I got this code:
this.datepipe.transform(d.hour, 'yyyy-MM-dd HH:mm a z')
this.datepipe.transform(d.initDate, 'yyyy/MM/dd')
this.datepipe.transform(d.endDate, 'yyyy/MM/dd')

And in the browser i got this error:
ERROR Error: InvalidPipeArgument: '2017-12-13T03:00:00Z[UTC]' for pipe 'DatePipe'
at invalidPipeArgumentError (common.es5.js:2610)
at DatePipe.webpackJsonp.../../../common/@angular/common.es5.js.DatePipe.transform (common.es5.js:3506)
at discipinscripcion.component.ts:31
at Array.forEach (<anonymous>)
at DiscipinscripcionComponent.webpackJsonp.../../../../../src/app/components/discipinscripcion/discipinscripcion.component.ts.DiscipinscripcionComponent.inscribir (discipinscripcion.component.ts:29)
at Object.eval [as handleEvent] (DiscipinscripcionComponent.html:21)
at handleEvent (core.es5.js:11998)
at callWithDebugContext (core.es5.js:13467)
at Object.debugHandleEvent [as handleEvent] (core.es5.js:13055)
at dispatchEvent (core.es5.js:8614)

any tips on converting that kind of date format to yyyy/MM/dd?
Thanks a lot!
Answer: You can try this :
datepipe = new DatePipe(en-US);
or to any other locale. Then return it as string
this.datepipe.transform(new Date(), 'yyyy/MM/dd');
Don't forget to import DatePipe from @angular/common and provide it in providers array in your module (supposedly app.module.ts.

Angular4 invalid pipe argument


typo3 viewhelper date delivers empty string for every date in march

Question: TYPO3 v11, PHP 8.0.8.
The following line in a fluid template:
<f:format.date format="%d. %B %y">{newsItem.datetime}</f:format.date>

delivers an empty string for every date in march.
I got the following debug outputs for a date in february:
DateTimeprototypeobject (2023-02-06T13:15:46+01:00, 1675685746)
' 06. Februar 23 ' (28 chars)

So the locale is correct and i get local dates in german.
But for dates in march i get the following debug output:
DateTimeprototypeobject (2023-03-07T16:00:08+01:00, 1678201208)
'' (25 chars)

The Datetime-Object is correct but the formatted string is empty.
Any ideas whats going on here?
Thanks!
Comment: Seems to be a locale issue. As the German "March" has an umlaut, the system can't output due to locale or even utf-8 settings.
Answer: two possible solutions are already registered at SO:
German Umlauts in strftime date-formatting - correct utf-8 encoding?
Character encoding within German date created with strftime()

make sure your locale is set with UTF8 encoding:
setlocale(LC_TIME, "de_DE.UTF-8");
(make sure the the name is written correct and compare it with the list of available locals with this shell command: locale -a | grep -i "de_de")

regarding TYPO3: set $GLOBALS['TYPO3_CONF_VARS']['SYS']['systemLocale']

encode the result for further usage:

$date_german = strftime("%e. %B %Y", $timestamp_start);
$date_german = utf8_encode($date_german);

maybe with an additional ViewHelper???
Comment: the problem was indeed a wrong locale - which i not realized because it was only a typo: de_DE.utf-8 instead of de_DE.utf8 ... both exists and only one is correct.
Comment: the name of the current locale can vary from system to system. I added a hint to get the currently active locals on a system.


Redisearch on Redis instead of Redis-Stack?

Question: I want to use Redisearch. But problem is there is no Redis-stack docker image in my Organization's private registry. There is Redis version 5 and 6 though.
Can I use Rediserach directly on Redis instead of Redis-stack or is there any other way to solve this problem.
I tried going through Redis and Redis-stack documentation. But There is nowhere mentioned if Redisearch will be compatible on Redis directly.
Answer: You can compile your own RediSearch module and load it into a Redis server through the configuration file. See the repository on GitHub: https://github.com/RediSearch/RediSearch/releases
Once you have built it, you'd amend your redis.conf to include something like this.  The user that redis-server runs as will need permission to see and execute this file:
loadmodule /full/path/to/redisearch.so

Note that if you also want to use the JSON document type with Search, you'll need the RedisJSON module: https://github.com/RedisJSON/RedisJSON/releases


Harris corner detection vs. PCA

Question: A lot of classes shows that Harris corner detector is actually PCA (example, page 5), but I'm having trouble with that since Harris doesn't have mean subtraction in the algorithm (not in the paper and not in the OpenCV implementation).
This means that if, for example, there is a part of the image which is a slanted plane in both $x$ and $y$ directions, then Harris can recognize it as a corner since $\Sigma I_x^2$, $\Sigma I_y^2$ and $\Sigma I_xI_y$ are all large.
However, with PCA, since we do mean subtraction, the covariance matrix would be small in all elements.
So what don't I get in this nuance of Harris?
Comment: @JavierTG: There is no reason for the gradient to average zero in a small patch, though it likely does across a full natural image. Still, I guess people could make this assumption to link structure tensor analysis to PCA. Though they are not the same thing, they certainly have similarities that could be exploited to aid understanding.
Comment: I would guess it's because the mean of the derivatives $I_x=\frac{\partial I}{\partial x}$ and $I_y=\frac{\partial I}{\partial y}$ are assumed to be zero. Intuitively we can think that when an edge is present inside the window we are using, then there will be an increment (or decrement) in the gradient followed by a decrement (or increment) $\to$ making the mean of the gradients present in the window *roughly* zero in both axes. But note that this won't happen always.
Comment: @CrisLuengo I agree. My point was just a rough intuition. I hope the question get answered.
Answer: The structure tensor is the locally averaged outer product of the gradient with itself:
$$\sum \nabla I \nabla^T I =
\left[\begin{array}{r}
             \sum {I_x}^2 & \sum I_xI_y\\
             \sum I_xI_y & \sum{I_y}^2
        \end{array}\right]$$
When averaging the gradient directly, the opposing vectors at each side of a line will cancel out. One approach to avoid this cancelling is doubling the angle (such that vectors pointing in opposing directions become identical). This is a mapping of $\mathbb{R}^2 \to \mathbb{R}^2$. After applying this mapping, however, vectors originally at 90 degrees will cancel out when averaged. The structure tensor is a different mapping $\mathbb{R}^2 \to \mathbb{R}^3$, namely $(I_x,I_y) \to (I_x^2,I_y^2,I_xI_y)$, which also allows averaging vectors. The first two components of the mapping accomplish approximately the same thing as doubling the angle. The third component, $I_xI_y$, preserves the information about the spread in angles within the set of averaged vectors.
In short, the structure tensor is not the covariance matrix of the gradient in a neighborhood, though it has similarities to it. And so the eigen analysis of the structure tensor is not a PCA of the gradient. However, I do understand why some people like to bring up PCA when explaining Harris. I just wish they didn't claim equality.

Harris corner detection vs. PCA


brctl bridge forwarding packets to promiscuous interfaces

Question: I have two promiscuous sniffing interfaces on my linux box:
eth0 is connected to an external vlan bridge
eth1 is connected to an internal vlan bridge

with eth0 I can sniff all traffic on my "external network"
with eth1 I can sniff all traffic on my "internal network"

I then created a bridge with brctl (br0) and added both interfaces to this bridge.
Now I can sniff all packets showing up on eth1 and eth2 directly from br0 saving me having to launch two instances of snort.

My problem is that now arp and multicast packets that are showing up on eth0 are copied on to br0 and forwarded to eth1.

Is there any way to make both these interfaces copy all packets on to br0 but never allow br0 to forward any packets nor eth0 or eth1 to respond to them?
Answer: According to it's design, the Linux bridge acts exactly like a plain NWay Ethernet Switch. It keeps it's own ARP/MAC Address Table, and forwards packets according to this table. So Multicast and ARP, as in a plain network switch, go out to every port regardless what their origin is.
In order to prevent this behavior, you should set up a firewall, not using iptables, which takes care of Layer 3+ in OSI Model, but ebtables which takes care of Layer 2 traffic.
Assuming you are on a Debian/Debian based distro you could execute:
apt-get install ebtables
apt-get install arptables
For aditional documentation execute:
man 8 ebtables
Here is a short example of using ebtables for multicast:
ebtables -A FORWARD -o eth0 --pkttype-type multicast -j DROP
ebtables -A OUTPUT -o eth0 --pkttype-type multicast -j DROP
ebtables -A FORWARD -o eth1 --pkttype-type multicast -j DROP
ebtables -A OUTPUT -o eth1 --pkttype-type multicast -j DROP

As a good starting point for learnig ebtables, which actually copies iptables syntax, here is the official documentation: http://ebtables.sourceforge.net/documentation/docs.html
Comment: Thank you very much for this. Good read.Worked like a charm and learnt something new


In R: How to make dataframe index as column?

Question: I am new in R and trying to convert VIF results into dataframe to feed it to ggplot:
vif_values <- car::vif(model_vif_check_aliased$finalModel)
vif_values

############ output ###############
       duration       nr.employed         euribor3m             pdays
         1.016706         75.587546         80.930134         10.216410
     emp.var.rate  poutcome.success         month.mar     cons.conf.idx
        64.542469          9.190354          1.077018          3.972748
contact.telephone          previous               age    cons.price.idx
         2.091533          1.850089          1.185461         28.614339
        month.jun       job.retired
         3.936681          1.198350

ISSUE: When I convert this into data frame then name of variables comes into index rather than as a separate column:
as.data.frame(vif_values)

############ output ###############

               vif_values
               <dbl>
duration       1.016706
nr.employed    75.587546
euribor3m      80.930134
pdays          10.216410
emp.var.rate    64.542469
poutcome.success    9.190354
month.mar      1.077018
cons.conf.idx   3.972748
contact.telephone   2.091533
previous       1.850089

How do I make this as data frame of two column so that I can use this in ggplot to create a barplot of variable names with their values ?
ggplot(aes(x=var_name, y=vif_values)+
 geom_col(col="blue")+
 coord_flip()

Comment: `df <- cbind(var_name = rownames(df), df)` and then `rownames(df) <- NULL`
Answer: This should work: df$var_name = rownames(df), where df is your data frame
Comment: thanks @Ricardo Semião e Castro I was trying with `index`, `set index` etc. and your code worked. I will accept the answer as soon as it let me .


How to estimate potential power savings

Question: If I have some servers set to static high performance mode, is there a way to generate a report on what power savings mode would have done, if it were enabled? I am looking to generate reports of the form, on this day we used this many kWh that we didn't really need to, summed across the estate. Or an alternate method to do this?
Comment: This is interesting. Let me think about it.
Comment: Can you provide more information on your servers? Model(s), operating systems, workload, etc.
Comment: We don't generally ask for idle curiosity, but because the information has a bearing on the question (and answer). It's to your benefit to provide as much information as possible.
Comment: Can you also explain how you're being billed for power? Is it per-server, per-circuit, are there thresholds you need to match, is this a co-location facility/data center, or are you trying to meter your utility power utilization??
Comment: Bear in mind that for most virtualisation products "Static High Performance" or the vendor equivalent (I.e., disabling C States etc) is recommended best practice so your "didn't need to" may well be a questionable statement in these, and other, instances.
Comment: @dan I know that this recommendation has been made in the past because Linux's power management is so flaky, I wonder if it's any better now
Answer: I'm unaware of any current server that holds this data and provides estimates based on it's history, nor any upcoming servers that do so. The only way to get close to a real answer would be to test it yourself with a power meter over a period of time with both settings. That said I buy HP servers and their 'balanced' power profile is expected to save at least 15% of power draw over their 'maximum performance' option.
Comment: The ILO keeps a bit of history. This is easy to test. Run a server in both modes for a day and compare the graphs. I would have posted examples had the OP provided server model and generation information... *pulling teeth*
Comment: @ewwhite thanks, we have everything from G2s to G9s. I'll have a look at the ILO graphs and see if they are useful, but what I really want is the "what if" scenario
Answer: Measure it on typical servers and calculate that on this base. And/or ask your hardware manufactorer.
Recent servers should be equipped with online power consumption measurement means and even statistics. (e.g. Dell PowerEdge x9xx or Rxxx models)

How to estimate potential power savings


IMO 2013, Problem C8

Question: Going through the official solution of problem C8 from the IMO 2013 shortlist. Here's the whole pdf, in case someone needs it: https://www.imo-official.org/problems/IMO2013SL.pdf

Could someone please explain the very last paragraph on this page, the one that starts with words "Next, any interval blackened by B..."? What I struggle with is exactly the first sentence in this paragraph, namely -- why do all "such intervals" have lengths not exceeding $1/2^m$?
Here's the scenario... Before round 1 begins,  we have $x_1=0$. Now A plays $m=2$, and B responds with blackening the interval $I_1^1=\left[\frac{1}{4},\frac{1}{2}\right]$. At the start of round 2 we still have $x_2=0$. Now A plays $m=3$, and B blackens $I_1^2=\left[\frac{1}{8},\frac{1}{4}\right]$. Now, at the start of round $r=3$ we still have $x_r=x_3=0$. If A were to play $m=3$ again, B would blacken $I_0^3=\left[0,\frac{1}{8}\right]$. This would make the whole interval $\left[0,\frac{1}{2}\right]$ blackened, so that $x_{r+1}=x_4=1/2$.
Now, let's apply the logic from the sentence that I struggle with. According to it, all intervals that were blackened before the 3rd round have different lengths not exceeding $1/2^3=1/8$, since in the 3rd round A uses $m=3$. Which is obviously wrong, since in the very first round B blackens the interval of length $1/4$.
How come?
Answer: I think you are right, but the induction claim still holds because the respective part of the solution can be corrected to
"...all such intervals have different lengths not exceeding $\alpha$, so the total amount of ink used for them is less than $2\alpha$. Thus, the amount of ink used for the segment $[0, x_{r+1}]$ does not exceed the sum of $2\alpha$, $3x_r$ (used for $[0, x_r]$), and $1/2^m$ used for the segment $I^r_0$. In total it gives at most $3x_r+2\alpha+1/2^{m}<3(x_r+\alpha)=3x_{r+1}$".

IMO 2013, Problem C8


Tem como abrir o outllok através do php, sem ser mailto?

Question: Tenho um sistema de pedido que envia email automático para os representantes com anexo de um arquivo pdf feito em fpdf, mas agora a empresa solicitou que ao invés de enviar automático gostaria de usar o outlook como alternativa de envio, pois assim receberia aviso de recebimento e confirmação e manteria um histórico no outllok até que o pedido seja efetuado, falo outlook pois todos os usuários que utilizam o sistema tem ele instalado nas maquinas. Sei que no C# asp.net isto é possível, mas em PHP não encontrei nada relacionado ao assunto.
Ou existe uma biblioteca em php que poderia utilizar de forma semelhante ao webmail que poderia ser chamada toda vez que concluímos um pedido?
Estou utilizando este link para envio ele até preenche o email do destinatário e o assunto, mas não anexa o pdf gerado automaticamente.

Enviar
Comment: Ele já é o cliente padrão, o problema esta em anexar o pdf de forma dinâmica, sem fazer o download do arquivo e anexar de forma manual, no `aspx` eu utilizo uma dll que integra o outlook ao sistema e envio e-mail interno com ele, sei que dessa forma não é possível em `php` por isso criei um link para chamar o programa padrão.
Comment: Configurar o outlook como cliente de email padrão na maquina, resolveria o problema?
Comment: `gostaria de usar o outlook como alternativa de envio, pois assim receberia aviso de recebimento` -> o ideal é descobrir como o Outlook consegue fazer isso, e replicar a funcionalidade nos emails gerados através de PHP.
Answer: Respondendo o cerne da sua pergunta, infelizmente o PHP não irá conseguir fazer o que deseja, pois, como ele roda no servidor, ele não irá conseguir fazer esse intercâmbio entre o servidor e a máquina cliente da forma que está propondo.

Entretanto...
Fiz uma breve pesquisa sobre bibliotecas de webmail em PHP e encontrei algo que pode ser interessante ao seu sistema, que pode ser integrado a ele: https://afterlogic.org/webmail-lite
Segundo a documentação ele é "livre e de código aberto". Talvez com ele seja possível fazer uma integração ao seu sistema, chamá-lo quando finalizado o pedido e já inserir todas as informações de envio, inclusive o anexo (talvez um bom desenvolvedor seja necessário para fazer isso).
Caso consiga uma solução em PHP (como um webmail), seria interessante deixar depois um feedback para que possamos saber se deu certo afim de ajudar outros com a mesma demanda.
Comment: Esse webmail lite parece ser a interface de email propriamente dita, certo? O front-end para você como usuário final usar feliz e contente?
Comment: @JeffersonQuesado Se quiser abrir um vinho tb, não faz mal. :)
Answer: Existe como usando exec, mas isso exige que o PHP esteja sendo utilizado no lado do cliente, o que não é comum.
Segundo a documentação do Outlook CLI:
outlook.exe /c ipm.note /m email@example.com

Existem outros comandos/parâmetros disponíveis.

Portanto, poderia utilizar:
exec('outlook.exe /c ipm.note /m email@example.com');

Talvez seja necessário especificar o caminho, então:
exec('"C:\Program Files (x86)\Microsoft Office\root\Office16\outlook.exe" /c ipm.note /m email@example.com');

Apenas cuidado com o e-mail inserido, porque ele pode ser um texto malicioso, no qual seria possível executar um código definido pelo atacante, afinal você está inserindo ele num exec. Se o email for firstname.lastname@example.com & notepad.exe iria abrir o notepad.exe, por exemplo.

Novamente, é preciso que o cliente esteja executando o PHP, o que com certeza não é aplicável a maior parte dos casos!