Different ways of treating vector calculus?

Question: I learned that there are different ways of treating vector calculus: vector fields and differential forms, if I understand correctly. The former is used in calculus, and the latter is in differential geometry. My memory of calculus is vague on the vector calculus part and I have limit knowledge about differential geometry, so I was wondering how these two ways are different and related in a brief? There is no need to refrain from using some terminology in reply, and I can look them up if I am not familiar.
A side question: is multivariate calculus synonym of vector calculus?
Thanks for your input!
PS: The book description of Differential Forms: Integration on Manifolds and Stokes's Theorem by Steven H. Weintraub is from which I learned the above:

Book Description:
This text is one of the first to treat vector calculus using
  differential forms in place of vector fields and other outdated
  techniques. Geared towards students taking courses in multivariable
  calculus, this innovative book aims to make the subject more readily
  understandable. Differential forms unify and simplify the subject of
  multivariable calculus, and students who learn the subject as it is
  presented in this book should come away with a better conceptual
  understanding of it than those who learn using conventional methods.

Treats vector calculus using differential forms
Presents a very concrete introduction to differential forms
Develops Stokess theorem in an easily understandable way
Gives well-supported, carefully stated, and thoroughly explained definitions and theorems.
Provides glimpses of further topics to entice the interested student
Comment: MV Calculus and "Vector Calculus" generally both mean the same thing: Analysis performed in $\mathbb{R}^n$. In either case, differential forms and the associated abstract machinery (manifolds, exterior algebra, etc) is a (vast?) generalization of "Vector Calculus". The results in vector calculus can be obtained by using $\mathbb{R}^3$ as the manifold and there is a very famous set of isomorphisms that relate the exterior derivative to the classical vector calculus operations DIV/GRAD/CURL. See the first pages of Bott and Tu's Differential Forms in Algebraic topology for details on this.
Answer: Trying to put it simply, I'll look at n - dimensional Euclidean space first. Then, differential forms (1 forms to be more precise) are dual to vector fields, that is, a 1 - form $\omega$ is nothing but a linear function on the space of tangent vectors in p.
For differential forms the notion of exterior product or wedge product is rather important, n-forms in n-dimensional space corrsponding to a multiple of the determinant function $\det$. This makes them volume forms and gives rise to a an integral (as are one forms when restricted to the tangent space of curves) for which particularly nice theorems (like Stokes theorem) are rather elegantly to formulate. k - forms are then natural candidates for volume form on k-dimensional submanifolds
This notion may be extended to vector bundles on manifolds, the precise defnitions are a bit involved, though. In differential geometry, both approaches (vector fields and forms) are used, and often combined. You can do tensor analysis and look at exterior algebras on these objects by first doing it locally on the product of an open set and a vector space and then gluing thing together using an atlas. The term used in that general case is 'tensor analysis'. A detailed discussion of several approaches to work with these concepts is found in Michael Spivaks 'Comprehensive Introduction to differential geometry', the first and second volume focus on these topics. In particular it explains how to 'translate' between the various concepts. (There may be newer books, I worked on that about 20 years ago, and I still love the humor in Spivaks books. :-)
In lectures or even books on differential geometry you will usually see a focus one of these approaches. This is due to the fact that very often the linear algebra involved is often no longer taught in basics lectures and has to be presented, too. Then there is no time left to cover the dual view and to show how the concepts relate to each other.


How can I use audio slices as samples?

Question: I'm trying to remix a song, and I've cut an audio event (referencing its own clip) into slices. Is there a way to use these slices to make a rhythmic beat, as if each slice were a drum pad (other than manually copying and pasting events)?
Comment: Well, yes - this is one of the core functions of a DAW, or various other tools which let you add repeats etc.
Comment: @DrMayhem Maybe he doesn't know how to use them as samples. That's kinda his question.
Comment: @DrMayhem That's not what I meant; rather than duplicating each syllable every time I wanted to use it again, I'd use them as...er...samples.
Comment: I was hoping that was what you meant:-) Yes, why not just use them as samples :-)
Answer: I figured it out! While using Groove Agent SE, you can just drag the audio parts or slices you want onto the pad you want them on; then you can just "Create Drum Map From Instrument" and then edit the drum part in the drum editor thing like normal.

How can I use audio slices as samples?


How to stop connecting to www.download.windowsupdate.com

Question: I work with Windows Client and Server systems on a private network that cannot reach the internet.  Problem is, many programs (like Subversion) cause Windows to attempt connections to www.download.windowsupdate.com to download a file called "authrootstl.cab" file.  The direct result is that many programs that use SSL, like Subversion, block for five or ten seconds trying to resolve this host (which it never does).
I've tried putting this host to 127.0.0.1 or some other IP address in my C:\Windows\System32\Drivers\Etc\hosts file, but it still tries to look this up in DNS, and I assume it is bypassing the hosts file for security reasons.
Besides putting a dummy entry into a DNS server, which I cannot do, what other things can I try to stop or block this?
Answer: Well, if you cannot touch the official DNS, perhaps you install a proxy DNS (on your workstation) that has a fake entry (pointing e.g. to 127.0.0.1) for www.download.windowsupdate.com, and that redirects all the other requests to the true DNS.
Answer: To make sure the problem is really a problem of resolution, you can enable the DNS client log (the DNS client is a service on Windows).
To do so, go to:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DNS\Parameters\LogFilePath

and optionally
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\DNS\Parameters\LogFileMaxSize

Then have a look at what the subversion client does in that log.  To make sure it really bypasses the hosts file, compare to the result of a manual:
nslookup -d2 www.download.windowsupdate.com

Comment: Alain, I don't have the registry path for DNS in the registry.  Also, when I "ping" the host it does use 127.0.0.1.  I think there is something internal that is disallowing us to locally remap that host name.
Comment: You must create the Registry Path and Key.  You might be right for the way the resolution is performed inside the subversion client, but I see no reason for this.  The log should actually tell you how the resolution is performed.  The other two solutions proposed in that thread are not bad and I would eventually resort to one of them (and actually did in the past), but I believe you first have to trace what's happening and that would involve creating/declaring and reading that log.
Comment: Well, I tried those keys and even tried replacing "DNS" with "dnscache" which does exist, but I never get any information in the log file I set.  Still, I don't get why it's using DNS when that hostname is in the hosts file.  I suspect there is an internal security setting that never uses the local hosts file for that host name.
Answer: A clever solution I've used in the past is to push out a GPO or registry setting for a WSUS server that does not exist. The machines will then stop asking Microsoft for updates and instead fail to query for your missing server. Not exactly a clean solution, but it gets the job done.
You really should have a WSUS server, by the way.
Comment: +1 - I thought about this as well. I did not mention it because my understanding was that the OP had turned the windows update service off. Otherwise, yes that might be a way.  But then setting a WSUS is not a common maintenance task.


Como garantir a finalização de um processo angular.js

Question: Quero pedir uma ajuda nesse processo, tenho uma aplicação no angular.js que preciso emitir todas as etiquetas de um processo, e depois todas etiquetas de um segundo processo.
O problema é que está ocorrendo de imprimir uma etiqueta do processo um depois uma etiqueta do processo 2 e assim sucessivamente.
Isso provavelmente está ocorrendo porque o processo executa o segundo processo antes que o primeiro seja finalizado.
Dessa forma preciso garantir que o primeiro processo fosse finalizado antes de executar o segundo, alguma idéia?
<code>    enviaImpressao = function (impressor) {

        // Imprime etiquetas de Caixa
        ImprimeEtiquetaService.enviaParaImprsessao ( numeroCaixa, "BOX" ).then(function (result) {

        // Imprime etiquetas de Picking
        ImprimeEtiquetaService.enviaParaImprsessao ( numeroPedido, "PICKING" ).then(function (result) {
    }

</code>
Desde já obrigado.
Comment: Coloque mais detalhes do seu código, se possivel. Com o que tem ai, acredito que se vc encadear a execução do "picking", seu código irá funcionar: ImprimeEtiquetaService.enviaParaImprsessao ( numeroCaixa, "BOX" ).then(function (result) {         ImprimeEtiquetaService.enviaParaImprsessao ( numeroPedido, "PICKING" ).then(function (result) {});
  });
Comment: Cezar obrigado pelo retorno, funcionou mas ficou mais lento. Desculpe a ignorância mas esse processo que vc indicou é similar a um processo recursivo ?. Desde já obrigado.
Comment: Não é sobre recursividade mas sim promisses, vc pode obter mais informações aqui: https://pt.stackoverflow.com/a/119913/2318
Answer: Conforme o comentário, seu problema pode ser resolvido da seguinte forma:
<code>    enviaImpressao = function (impressor) {

        // Imprime etiquetas de Caixa
        ImprimeEtiquetaService.enviaParaImprsessao ( numeroCaixa, "BOX" ).then(function (result) {
            // Imprime etiquetas de Picking
            ImprimeEtiquetaService.enviaParaImprsessao ( numeroPedido, "PICKING" ).then(function (result) {});

        });
    }
</code>
O que acontece é que as duas chamadas são encadeadas, ou seja: primeiro será feito uma requisição passando o parâmetro BOX, após o fim dela ( o que tende ao infinito), é executada a próxima chamada com o parâmetro PICKING.
Mais informações podem ser obtidas aqui:
https://pt.stackoverflow.com/a/119913/2318
Comment: ok. obrigado. Um abraço.


Information Bottleneck principle of Deep Learning model implementation

Question: I am trying to implement Information Bottleneck principle. In which one of the observation is Mutual Information between Input data X and Hidden layer's out H keeps reducing as we go deeper. In other words, Information about X (synergistic) is high in shallow layer and become unique & redundant in deeper layers. Hence I(X,H) from the first layer to the last layer looks like,

Source: mentioned in  this post
Now, when I try to implement, I am having trouble in estimating MI with the basic problem of dimensionality inequality.
<code>   # when a sample in X is given as input to the first layer
   #out.shape = [ no_of_neurons_in_first_layer x 1]
   # to get amount of X's Information mi[j] provided by a single neuron(jth)
   loop all X: i -> 1 to N:
      out = activation(X[i])
      mi[j] += MI(out[j] , X[i]) #estimate MI of out[j](single Random Variable
                                 #and X[i] (a sequence of RVs)
</code>
How can I calculate MI between sequence of RVs and single RV? Is it correct to quantize them and do the histogram method (in spite only one member from one group)?
Any insight and help would be appreciated. Thanks in advance :)
Answer: The information bottleneck conclusions are known to be sensitive to implementation choices, cf. for example https://openreview.net/forum?id=ry_WPG-A-.
If you want a starting point, you can look at the official github for a later paper from that group.
This gist had some simple and as far as I can tell correct and efficient code for estimating mutual information.
Comment: It would be helpful if you could summarize the main content of the materials that you link to. The purpose of this website is to build a durable repository of information. As it stands, if the links go dead, your answer will have relatively little information.
Comment: This is a matter of some controvery, I don't want to hamhandedly attempt a summary. My pointers are durable-by-construction.
Comment: Yes, I agree with the fact that the principle is sensitive to implementation. However, that is mainly involved with other factors like selection of activation function, an unclear connection between compression and generalization phase etc. The estimation method for Mutual Information remains robust and gives the same result irrespective of the method employed                             (Even mentioned in one of the replies by the Authors), So it would be great if you help to provide insight to estimate MI using simple binning procedure, which is the exact thing the question demands. Thanks:)


ADC converter to Audio interface makes noise crackle

Question: In short, the sound card I have is behringer fca610. Then I have an Analog to digital converter. when I connect the ADC to the sound card, even if I do not turn on the audio, there is still noise, crackling. I connect via ODT Toslink.
Audio goes through the chain, but still a lot of noise.
Maybe you need to configure the asio buffer or sample rate. Or where there is so much noise, or you can't insert the converter into the sound card. And you need to insert into the amplifier or av reviser?
By the way, the sample rate of the ADC is 48,000 hertz. And the output audio is LPCM
Comment: Is the Behringer set to sync to external audio clock? It has to use the clock pulse coming from external ADC, or otherwise you'll get crackling. Even if both the ADC and the Behringer are set to the same clock rate, if there are multiple clocks, they're bound to run at slightly different speeds, and inevitably at some point in time, clock A has produced one more sample than clock B, and what do you do then. Throw away a sample? Insert an extra sample?
Comment: The Behringer should be set to sync to External Clock. If there is an external device sending digital audio that cannot sync to the Behringer's clock, then the Behringer must be "slave". There can only be exactly 1 master word clock in a digital audio network. When you connect two digital audio devices together, it creates a network. By the way, why are using such a cheap external ADC - is there some reason why you can't use the Behringer's analog inputs? Is the sound so bad that using an external ADC is worth the trouble?
Comment: Why are you chaining DACs? I don't see the point. If your second un-named DAC is causing cracking, then it's probably the DAC. s/pdif doesn't have a clock, it's carried in the actual samples themselves so has to be re-clocked by the receiver. Your receiver is glitching.
Comment: Is this even possible? I have the cheapest converter. Like you can see on this page https://www.amazon.co.uk/slp/analogue-to-digital-converter/4xqnt9yxgacn65r
Comment: When I change the synchronisation settings (or sample  rate) of the fca 610 then I connect the converter, the sound does not pass. As if the converter freezes. And if I just turn on the audio card and connect the converter, the sound goes, but with a noise and not at 48khz but at 41,000. Attached a screenshot of the settings. What is there to choose?
Comment: I strangely think that the converter adds depth to the mix(incoming audio). All this routing. Thanks you.
Answer: The Behringer should be set to sync to External Clock. If there is an external device sending digital audio that cannot sync to the Behringer's clock, then the Behringer must be "slave". There can only be exactly 1 master word clock in a digital audio network. When you connect two digital audio devices together, it creates a network.
If clocks are not synchronized, you get crackles in the audio.
Here are a few randomly selected web articles that explain word clocks and synchronization in digital audio connections
https://en.wikipedia.org/wiki/Word_clock
https://www.soundonsound.com/techniques/does-your-studio-need-digital-master-clock
https://www.sweetwater.com/sweetcare/articles/what-digital-audio-synchronization-differ-time-code-synchronization/


Were short-sleeved jerseys used in-game during the 2022-2023 season?

Question: As a fashion statement, Golden state sported short-sleeved jerseys a decade ago.
Game 7 of the 2016 NBA Finals consisted of the Cavaliers wearing short-sleeved jerseys.
However, I haven't seen much in the way of short-sleeved jerseys as of late.
Were short-sleeved jerseys used in-game during the 2022-2023 NBA season?
Answer: Not sure if there are any one-offs that it's missing, but basketballjerseyarchive.com shows all the jerseys for 2022-2023 are sleeveless.   They do show the short-sleeved jersey for both the Warriors and the Cavaliers that you mention in previous years.
Just scanning by eye (so I could have missed something), I don't see any short-sleeves after the 2016-2017 season.  Many of the teams that year had a short-sleeve version.


Deduction fails

Question: I declared a global shift operator but for some reason the compiler cannot deduct the type.
template<class T, size_t N>
std::istream& operator >>(std::istream& stream, std::array<T, N>& array);

Instead it tries to use a overload with std::istream&& as the first argument.
EDIT: I invoke via
void myns::subns::Object::Func(std::istream& stream) {
  stream >> array;
}

where array is std::array<size_t, 2>.
Indeed, when I try it isolated it compiles - but in my code gcc (4.7) complains error: cannot bind 'std::istream {aka std::basic_istream<char>}' lvalue to 'std::basic_istream<char>&&'
Could someone explain to me why the deduction does not work or how I can force to call the function overload?
Comment: How do you _try_ to invoke it?
Comment: Works for me: http://ideone.com/n2D5o
Comment: @mfontanini Thanks. I do not understand why it works isolated.
Comment: What namespace are you declaring the `operator>>` in and in what namespace are you invoking it?
Comment: @DaveS `operator>>` has no namespace (global) and I invoke it from `mynamespace::subnamespace` where `Object` is declared in.
Comment: OMG it works using `::operator>>(stream, array);`! Ok, I obviously do NOT understand C++ anymore.
Comment: @LCIDFire: ADL doesn't work on templates, so it won't find it when its cross namespace.
Comment: @Dani - ADL works for templates, but the global namespace isn't searched here.
Comment: Adding additional operators to objects you do not own is always tricky (read impossible). The standard way of declaring free operators is to declare them in the namespace of the arguments and in the case of `std` this is explicitly forbidden by the standard. The lesson here is, that you better just not do it. Think of the users of your code and the implications if someone else tries to do the same thing.
Answer: If it doesn't find the operator>> in the namespace it is called from, the compiler looks for the operator in namespaces associated with the parameters you use. In this case they all come from namespace std, and not from the global namespace. Therefore the global namespace is not searched.
When you explicitly call ::operator>>(istream, array), it does look in the global namespace (as you specifically asked it to).
Comment: So the correct thing to do here is to derive a wrapper class from the `std` Collection and then write a namespace specific operator?
Comment: Probably, yes. Printing standard containers is tricky, as they don't have any `operator>>` overloads. Making them members and print the enclosing type is a possible solution.

Deduction fails


Javascript get value in attribute

Question: I am using jquery .attr in an input type so when I run this
console.log('name: '+$(this).attr('name'));

output is: name: user_project_category[65][skill][9]
How can I get the 65 and 9?
Comment: Show your jquery code.
Comment: Hi this is my code in jquery
Comment: $('.tagTeam').each(function(index){
    console.log('member id:' + $(this).val());
    console.log('name: '+$(this).attr('name'));
   });
Comment: and this is my input type attribute '';'
Comment: you are getting the client id
Answer: You can use Regular Expressions to extract text from between the brackets into an array and then you can access the array to get the values you want, you can either extract all text between brackets or just the numbers:

var yourInput = "user_project_category[65][skill][9]";
var allMatches = yourInput.match(/\[(.*?)\]/g);
console.log(allMatches[0]);
console.log(allMatches[2]);

var numberMatches = yourInput.match(/\[([0-9]*?)\]/g);
console.log(numberMatches[0]);
console.log(numberMatches[1]);
Answer: Use regular expression or split function in JavaScript
var output= 'user_project_category[65][skill][9]';
output.split(/(\d+)/)[1];
output.split(/(\d+)/)[3];

Comment: this is not an answer to the OP this is just a suggestion better put into comment
Comment: Below 50 reputation cannot comment.
Comment: sorry for my format this what Im trying for split                                           var dataaa = $(this).attr('name');
  var info = dataaa.split("[ ]");
  alert(info);
Answer:

var data = "name: user_project_category[65][skill][9]";

console.log(data.split("[")[1].slice(0,-1))//use split to get 65] use slice to remove ]
console.log(data.split("[")[3].slice(0,-1))//use split to get 9] use slice to remove ]

You can use split with slice

Assuming this is not dynamic and format is the same.
for dynamic use regex
Comment: Hi! this is dynamic but still thank ypu for your answer
Answer: Use regex.
var output = 'user_project_category[65][skill][9]';
var numbers = output.match(/\d+/g).map(Number);
alert(numbers);

output: 65,9
Do whatever you want to do with number.
working fiddle
Comment: Thanks everyone for your comment really helpful!

Javascript get value in attribute


Vectors & Tetrahedrons: Show that $P^2 = B^2 + R^2 + G^2 + 2BR \cos ∠(b, r) + 2RG \cos ∠(r, g) + 2GB \cos ∠(g, b).$

Question: Show that
$$P^2 = B^2 + R^2 + G^2 - 2BR \cos ∠(B, R) - 2RG \cos ∠(R, G) - 2GB \cos ∠(G, B).$$
Here, ∠(B, R) denotes the angle between the two faces coloured blue and red, and similarly for the
other two angles in this formula. This formula is a three-dimensional counterpart of a very famous
trigonometric identity for triangles. Which identity is that?
I don't know how to go about this question, this is a part of a long answer question, can anyone please help me through this please!
Comment: Please define all letters that appear (and then submit). There is no color that can be seen in the post. Please give a first try, own thoughts, so that a potential answerer can fit to the level either a full proof or a hint.
Answer: This is  Al-Kashi theorem (or the law of cosines) in the euclidean space.
You can check  p. 133 of this book :

Casey, John (1889). A Treatise on Spherical Trigonometry: And Its Application to Geodesy and Astronomy with Numerous Examples. London: Longmans, Green, & Company.


Change body font size with JavaScript

Question: I am trying to change my font-size with JavaScript when the scroll-y is greater than 20, but changing the font-size is not working for me.
Can anyone tell me what I am doing wrong? I don't understand what I am doing wrong...
<!doctype html>

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<meta charset="UTF-8" />

<title>Reken op je toekomst!</title>

Reken op je Toekomst

Iphone

Ipad

Blog

About

            Iphone

Ipad

Comment: [**document.body**](https://developer.mozilla.org/en-US/docs/Web/API/Document/body)
Answer: document.getElementsByTagName('body') will return a list. To change the style of the body returned you will need to access the first member of the list:
var body = document.getElementsByTagName('body')[0]

Answer: When you use getElementsByTagName to get the body, it returns a NodeList of elements. This NodeList is not a DOM node, so it doesn't have the style attribute on it.
You should change this:
body = document.getElementsByTagName('body');

to
body = document.getElementsByTagName('body')[0];

Answer: Use a shortcut for body:
var body = document.body;   // or just use it directly

Notice the plural form of getElementsByTagName which means it returns an HTMLCollection, so you need to use an index with it:
var body = document.getElementsByTagName('body')[0]; // first item in collection

Answer: You changing the font size on the body element, but classes on nested elements are overriding this, such as #nav

Change body font size with JavaScript


Não preciso preocupar com o frontend?

Question: Eu precisaria me preocupar com a vulnerabilidade do frontend ou apenas com o backend?
Comment: Oi mineiro, sim, a sua resposta foi útil para mim, obrigado!
Comment: Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Não é que não precisa se preocupar, só que você nunca poderá garantir segurança do seu código porque ele pode até mesmo ser jogado de lado e se comunicar com o backend sem ele, então qualquer coisa que faça ali pode ser burlado se a pessoa quiser, por isso o maior controle deve ser no servidor.
O que não quer dizer que não deva fazer códigos adequados no cliente para evitar uma interceptação no meio do caminho, quando tanto o servidor quanto o cliente querem trabalhar direito e tem algo no meio que não quer, por isso é importante a criptografia, manter controles de comunicação e autenticação se for o caso.
Também importa fazer um código para dar uma melhor experiência ao usuário, mas não que isso seja por causa da segurança.
Também pode ser útil manter alguma proteção para evitar um ataque ingênuo, mas não por segurança mesmo, não considere isso como medida eficaz. Lembre-se que tudo que está em um computador que você não tem controle não pode confiar sequer no que está executando. E no computador que pode confiar, normalmente o servidor, é confiável até ele ser invadido.
Answer: Eu sugiro que você faça validações tanto no backend quanto no frontend. A validação feita no frondend evita que mensagens de erro que o usuário não entenda apareçam para ele e a validação feita no backend impede que usuários espertinhos burlem o sistema, utilizando ferramentas de desenvolvedor do próprio navegador.

Não preciso preocupar com o frontend?


JavaScript constructor function returns values as undefined

Question: I'm trying to make a script that creates an object on submit from form values but on each submit it returns values as undefined .
This is HTML:

        <input type="text" class="title">
        <input type="text" class="image">
        <textarea class="text"></textarea>
        <button id="submit">+</button>

This is my script:
(function(){
    function Post(title, image, text) {
        this.title = title;
        this.image = image;
        this.text = text;
        this.date = new Date();
    }

    var post = new Post();

    function Dashboard() {
        var main = document.querySelector("main");
        var article = document.createElement("div");
        article.classList.add("post");
        var title = document.createElement("h1");
        var image = document.createElement("div");
        image.classList.add("img");
        var text = document.createElement("p");
        var date = document.createElement("p");
        var postTitle = post.title;
        var postImage = post.image;
        var postText = post.text;
        var postDate = post.date;
        title.innerText=postTitle;
        image.style.backgroundImage="url("+postImage+")";
        text.innerText=postText;
        date.innerText=postDate;
        article.appendChild(title);
        article.appendChild(image);
        article.appendChild(text);
        article.appendChild(date);
        main.appendChild(article);
    }

    var submit = document.getElementById("submit");

    submit.addEventListener("click", function(){
        var inputTitle = document.querySelector(".title").value;
        var inputImage = document.querySelector(".image").value;
        var inputText = document.querySelector(".text").value;
        var post = new Post(inputTitle, inputImage, inputText);
        Dashboard();
    });

})();

Answer: You are creating a new variable post within the click handler but your Dashboard is using one it captures in closure. You could make your Dashboard function to accept post as an argument.

function Post(title, image, text) {
  this.title = title;
  this.image = image;
  this.text = text;
  this.date = new Date();
}

function Dashboard(post) {
  var main = document.querySelector("main");
  var article = document.createElement("div");
  article.classList.add("post");
  var title = document.createElement("h1");
  var image = document.createElement("div");
  image.classList.add("img");
  var text = document.createElement("p");
  var date = document.createElement("p");
  var postTitle = post.title;
  var postImage = post.image;
  var postText = post.text;
  var postDate = post.date;
  title.innerText = postTitle;
  image.style.backgroundImage = "url(" + postImage + ")";
  text.innerText = postText;
  date.innerText = postDate;
  article.appendChild(title);
  article.appendChild(image);
  article.appendChild(text);
  article.appendChild(date);
  main.appendChild(article);
}

var submit = document.getElementById("submit");

submit.addEventListener("click", function() {
  var inputTitle = document.querySelector(".title").value;
  var inputImage = document.querySelector(".image").value;
  var inputText = document.querySelector(".text").value;
  var post = new Post(inputTitle, inputImage, inputText);
  Dashboard(post);
});

  <input type="text" class="title">
  <input type="text" class="image">
  <textarea class="text"></textarea>
  <button id="submit">+</button>


How to debug outline is not working in Vuetify?

Question: I started a fresh vue3 project with vuetify3 via vue cli.
$ vue create playground-vuelidate
$ cd playground-vuelidate
$ code .
$ vue add vuetify
$ npm run serve

FormInput.vue
<template>
  <v-form>
    <v-container>
      <v-row no-gutters>
        <v-col cols="12" sm="12">
          <v-combobox :items="select1" label="Select1" chips></v-combobox>
        </v-col>
        <v-col cols="12" sm="12">
          <v-text-field
            outline
            v-model="input1"
            :rules="rules"
            label="Input1"
          ></v-text-field>
        </v-col>
        <v-col cols="12" sm="12">
          <v-text-field
            outline
            v-model="input2"
            :rules="rules"
            label="Input2"
          ></v-text-field>
        </v-col>
        <v-col cols="12" sm="12">
          <v-text-field outline v-model="input3" label="Input3"></v-text-field>
          <v-textarea
            v-model="v$.textarea1.$model"
            :class="status(v$.textarea1)"
            label="textarea1"
          ></v-textarea>

{{ $v }}

        </v-col>
      </v-row>
    </v-container>
  </v-form>
</template>

App.vue
<template>
  <v-card class="mx-auto" max-width="1000">
    <FormInput />
    <v-card-actions>
      <v-btn text color="gray accent-4"> Cancel </v-btn>
      <v-btn color="primary"> Submit </v-btn>
    </v-card-actions>
  </v-card>
</template>

It yields this result

It supposes to look like this.
Official Doc

Notes
I have a select, inputs, and textarea all 3 of them the outline CSS doesn't seem to work or applied. Is it a known Vuetify bug ?
Comment: Vuetify 3 documentation is at https://next.vuetifyjs.com/en/components/text-fields/
Answer: Should be
<v-text-field
  outlined
></v-text-field>

not
<v-text-field
  outline
></v-text-field>

This is based from vuetify for vue3
https://next.vuetifyjs.com/en/components/text-fields/


Enable FIPS mode on CISCO Router

Question: Can someone please tell me how to enable/disable FIPS mode on CISCO Router?
Comment: Which Cisco router? What IOS version? There are so many to choose from.
Answer: From this page, it seems that a lot of routers can be FIPS-compliant.
It may require a special IOS version, and tamper evidence labels (to install on chassis, memory and interface cards).

Enable FIPS mode on CISCO Router


server response tags

Question: if a server response header is added to a config file of a site, does it display in IIS 7 as a server response header?
I am having a problem where a no index response header (tag) is repeatedly being added to a high profile website.
This no index header is viewable under the "server response headers" feature.
I have removed the response header a number of times in the past.
The only thing I can think of is that the header is part of a web config file on the development environment and when changes are uploaded the web config file from the dev environment is being copied with it causing the no index response to be pushed to the live environment.
can anyone clarify??
Thanks all!!
Comment: Please quote exactly what you are seeing and what tools you are using to see it. I think your terminology may be a bit off. Are you talking about an HTTP header that looks like "Server: IIS 7.5"? What exactly is a "no index response header (tag)"?
Comment: "x-robots-tag noindex" is the response header that keeps appearing in IIS after I remove it, and yeah - my bad - it is an HTTP response header so apologies for the confusion.
Answer: If you suspect that the web.config file includes a custom header, why don't you have a look? :-)
Open the web.config file in your favorite XML editor (I prefer notepad++), locate the following section:
system.webServer/httpProtocol/customHeaders

and see if any headers are added. It would look something like this (assuming that nothing else was in that web.config file):
<configuration>
   <system.webServer>
      <httpProtocol>
         <customHeaders>
            <add name="x-robots-tag" value="noindex" />
         </customHeaders>
      </httpProtocol>
   </system.webServer>
</configuration>

You can find more info on customHeaders over at IIS.NET

server response tags


Unreasonable WPF DataGrid Loading Time

Question: I've always had long loading times with WPF DataGrids, and I cannot find any similar reports online, so I suspected that I was doing something wrong.  Now I am sure of it, since adding layout complexity considerably slows down execution.  In a very simple layout, the DataGrid populates instantaenously, whereas the code below takes around 3 seconds to execute.
In the following code, it takes ~3 seconds for 150 rows and 11 columns to load, even if each cell is not bound to any property and with AutoGenerateColumns=False. (I have a two core, 2.6GHz processor with plenty of RAM).
The bottle neck takes place when the ItemsSource property is set in a layout as the one below:
<Window x:Class="datagridtest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Border  Background="LightSteelBlue" CornerRadius="10" Margin="10">
    <ScrollViewer Margin="10" HorizontalScrollBarVisibility="Auto">
        <Grid Margin="10,50,0,0">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"  />
                <RowDefinition Height="auto" />
                <RowDefinition Height="auto" />

            </Grid.RowDefinitions>
            <Expander IsExpanded="True" Name="expander1"  Grid.Row="0">
                <Grid>
                    <DataGrid VirtualizingStackPanel.IsVirtualizing="True" AutoGenerateColumns="false" Name="dg" Height="auto" CanUserReorderColumns="False" CanUserResizeColumns="False" CanUserResizeRows="False" CanUserSortColumns="False">
                        <DataGrid.Columns>
                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                            <DataGridTextColumn >
                                <DataGridTextColumn.Header >
                                    <TextBlock Width="140" HorizontalAlignment="Center" TextAlignment="Center">untitled<LineBreak/>column</TextBlock>
                                </DataGridTextColumn.Header>
                            </DataGridTextColumn>

                        </DataGrid.Columns>
                        </DataGrid>
                </Grid>
            </Expander>

            <Expander IsExpanded="true"  Grid.Row="1">
                <Grid>
                    <DataGrid AutoGenerateColumns="True"  Height="auto" />
                </Grid>
            </Expander>

            <Expander IsExpanded="true"    Grid.Row="2">
                <Grid>
                    <DataGrid AutoGenerateColumns="True" Height="auto" />
                </Grid>
            </Expander>
            <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="121,-42,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click_2" />
        </Grid>
    </ScrollViewer>
</Border>

using System.Collections.ObjectModel;

namespace datagridtest
{
///
/// Interaction logic for MainWindow.xaml
///
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

    }

    class row
    {
        public string Name { get; set; }
        public double Age { get; set; }
    }

    private void button1_Click_2(object sender, RoutedEventArgs e)
    {
        ObservableCollection<row> src = new ObservableCollection<row>();

        for (int i = 0; i < 150; i++)
            src.Add(new row { Name = i.ToString(), Age = i / 2 });

        dg.ItemsSource = src;
    }
}
}

Comment: Could you post some sample code that shows this?  I don't think WPF has a built in data grid.
Comment: Thanks Alan.  I guess I'm using the DataGrid from the Toolkit. I added code, and new comments in the original question.
Comment: @Alan: It does in version 4.0 of the .Net framework
Answer: The problem only occurs when the DataGrid is embedded inside a ScrollViewer like:
<ScrollViewer>
    <Datagrid/>
</ScrollViewer>

This makes sense because this configuration causes the whole DataGrid to be drawn at the same time (to be able to size the ScrollViewer's client area correctly).  In essence, it overrides the built-in virtualization behavior of the DataGrid, which implements its own ScrollBars so that not all of its content has to be placed in the layout simultaneously.
In other words, embedding a DataGrid inside a ScrollViewer is rarely needed because the DataGrid has its own automatic scrolling.
Comment: Furthermore, don't ever let a DataGrid autosize in any dimension.  If you are planning to stack them inside other controls, it's a good idea to set its MaxHeight property to something smaller than your screen's size, since DataGrid does not seem to be very efficient when its layout is large.
Comment: +1 Lifesaver! I temporarily put in a ScrollViewer and forgot all about it.. was shocked when I saw the grid crawl on an update.
Answer: I had a similar problem with a UserControl that contained a DataGrid, sometimes when I placed the UserControl on a new form or another UserControl it would lock up the interface (5 seconds?) while it redrew the DataGrid. Same with Resizing.
I tracked it down to

RowDefinition Height="Auto"

and the same performance issue also happened if I put the UserControl in a StackPanel. Seems very much to do with the previously mentioned resizing bug when the whole datagrid needs to be popluated to calculate the size of the encapsulating container.
<UserControl x:Class="ExampleUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" d:DesignHeight="481" d:DesignWidth="773">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <Grid Grid.Row="0">
            <ContentControl Content="{Binding MyDataGridUserControl}" />
        </Grid>
    </Grid>

</UserControl>

I just discovered that setting MaxHeight="[whatever]" for the ContentControl also works, as per a previous comment. It can be larger than the screen.
Comment: Thanks for pointing out the fact that when Height is set to "Auto" the problem arises. In my answer I didn't explicitly emphasize that.  I wouldn't, however, say that this is a bug, just a design issue.  When a data grid handles its own scrollbars and "virtual" client area, many optimizations are possible, but we cannot expect all these optimizations to be in effect when the virtual area is handled by the parent control--or can we? Anyways, at present, the data grid seems to be designed for a very specific use :(  It sucks because it causes us to have scrollbars within scrollbars in some UIs.
Comment: Thank you for this answer - it was indeed the issue I was having. After removing the Height="Auto" for data grid row I had a huge performance increase.
Comment: This sort of brings a limitation to WPF that we wouldn't expect there to be.
Answer: Can you see if all rows are being generated layout-wise? Normally Virtualization should hinder that and only generate the visible rows. (Test it with a template in one of the columns and count it in the constructor). There is a bug if WPF cannot determine the correct width of the DataGrid as it tries to size to the largest column - thus having to generate all rows to calculate the one with the largest width. (To test the last one - place it in a dock-panel instead of a grid - docked left or right)
Also, try VirtualizingStackPanel.VirtualizationMode="Recycling" to let it recycle the templates used.
Comment: Thanks Goblin!  You were on the right track in that my DataGrid was trying to generate all of the rows at the same time.  But this was due to embedding the DataGrid inside a ScrollView.  Virtualization was not the issue (because the size of the DataGrid was not being constrained to screen dimensions).
Answer: I have the same problem with bound Data grid, and I notice that in first load it is fast but on second and next it is slow. So when I add in code:
DataGrid.ItemsSource = Nothing

and then
TableAdapter.Fill(Mydataset.MyStoredProcedure,....)
DataGrid.ItemsSource=Mydataset.MyStoredProcedure

it became very FAST.

Unreasonable WPF DataGrid Loading Time


Javers - Disable sql schema

Question: In Javers and Spring, is can disable the automatic creation sql schema?
So I can create the schema with Liquibase for use multi-tenancy
Answer: This question is unclear. You cant disable schema craeation in JaVers SQLRepository but even if you could, what would be a purpose for that? If you  create different tables than JaVers expects, it crashes.
Comment: I do not want to create different tables.
I just needed to create the same tables in more schemas beyond the 'public'.
For that extracts the creation scripts and used the Liquibase to create
Javers the tables in other schemas.
Besides Liquibase give error when a table already created, when I
multi tenancy in APPLICATION, Spring conseque not create the Beans Javers
for lack of schema
Comment: The way I found to run the application, was to remove the @PostConstruct the annotation method 'ensureSchema' class JaversTransactionalDecorato

Javers - Disable sql schema


Prove by counterexample that a bounded sequence in a metric space need not have a convergent subsequence

Question: I am trying to prove that a bounded sequence in a metric space need not have a convergent subsequence.
My counterexample is: Consider the metric space:  ($(0,1]$,standard norm on $\Bbb R$ restrict to $(0,1]$)
and the sequence $1,\frac{1}{2},\frac{1}{3},...$ which is bounded. As $0\notin (0,1]$,the sequence is not convergent.
I thought about proving that if the sequence has a convergent subsequence, it must converge to $0$, then as $0\notin (0,1]$, we have a contradiction.
Here is my attempt:
Suppose, in order to get a contradiction, that a subsequence of the sequence $x_n=\frac{1}{n}$, call it $(x_{n_j})$, is a convergent subsequence. Suppose it converges to $a\in (0,1]$, then from the definition of convergence:
$(\exists a\in (0,1])(\forall \epsilon>0)(\exists N\in \Bbb N)(j\ge N\implies |x_{n_j}-a|<\epsilon)$
To obtain the contradiction, we prove that for this $a$:
$(\exists \epsilon>0)(\forall N\in \Bbb N)(\exists j\ge N\land |x_{n_j}-a|\ge\epsilon)$
Proof:
We know that $\frac{1}{n}$ can be less then any $a>0$ if we take $n$ large, so we have a term $x_{n_l}$ of $(x_{n_j})$ such that $x_{n_l}<a$.
Set $\epsilon=a-x_{n_l}$, then for all $N\in \Bbb N$, take $j\ge l$, then we have $|a-x_{n_j}|>\epsilon$ since the sequence $\frac{1}{n}$ is decreasing.
Could some please check if the argument above is correct? Thanks in advance!
Comment: For some short substantation of your statement it suffice to notice that [if a sequence converges, then every subsequence converges to the same limit.](https://math.stackexchange.com/questions/213285/prove-if-a-sequence-converges-then-every-subsequence-converges-to-the-same-lim) Sequence $(\frac{1}{n})_{n=1}^{\infty}$ and hence every subsequence is convergent to $0$ in $[0,1]$, so it cannot be convergent in $(0,1]$.
Comment: @PropositionX Your argument is correct, but Przemek is right, one could simplify the argument. Even in complete metric spaces a bounded sequence need not have a convergent subsequence, for example in the case of infinite-dimensional Banach spaces where for example the unit ball is not compact
Comment: @PeterMelech Also, if you take a space with infinitely many points and equip it with the discrete distance $d(x,y)=1$ for all $x\ne y$, that would be a complete metric space. It is a bounded space as well (diameter one) so all sequences are automatically bounded. But it is easy to find sequences that do not have convergent subsequences (for example the sequence terms are pairwise distinct).
Comment: You could also, if you like, take $\{1/n: n\in \mathbb N\}$ to be the whole space....... You can also show that for any$ x>0$ there exists$ r>0$ such that $\{n\in \mathbb N: x_n\in (-r+x,r+x)\}$  is bounded and hence finite.  Because   a  sub-sequence $(x_{n_j})_j $  converges to $ x$  iff for all $r>0$  the set $ \{j\in \mathbb N: x_{n_j}\not \in (-r+x,r+x)\} $ is finite,..... so  $ if (x_{n_j})_j$  converges to $x$ then for all $r>0$ the set  $\{j\in \mathbb N: x_{n_j}\in (-r+x,r+x) \}$ is infinite.
Comment: Thanks you all who leave comments. Got it!
Answer: Take as a  metric space the sequence space $(l^1(\mathbb{R}),d)$ where
$l^1(\mathbb{R})=\{x_n| \sum_{n=1}^{\infty}|x=(x_1,x_2....)| < \infty ,x_n$ is a sequence of real numbers $\}$ and $d(x,y)=\sum_{n=1}^{\infty}|x_n-y_n|$
Then take the subset $c_{00}=\{x|x$ has a finite number of non zero terms
$\}$. So you have the subspace $(c_{00},d)$ of $(l^1(\mathbb{R}),d)$.
Thus a sequence  in $c_{00}$ has the form $x=(a_1,a_2....a_m,0,0......)$
Now take the sequence $x_n=(1, \frac{1}{4},\frac{1}{9}...\frac{1}{n^2},0,0...) \in c_{00}$ which is a Cauchy sequence and bounded but does not converge in $c_{00}$
If it had a convergent subsequence in $c_{00}$ then it would converge in $c_{00}$ which is a contradiction.
If you want a simpler example take the subspace  $(\mathbb{R}$ \ $\mathbb{Q},d)$ of $(\mathbb{R},d)$
where $d$ is the usual metric and the sequence $a_n=\frac{\sqrt{2}}{n} \in  \mathbb{R}$ \ $\mathbb{Q}$.
$a_n$ is a bounded cauchy sequence in $\mathbb{R}$ \ $\mathbb{Q}$ but it does not have a convergent subsequence in $\mathbb{R}$ \ $\mathbb{Q}$
Answer: That's correct. If a metric space is not complete, than a nonconvergent Cauchy sequence is bounded and has no convergent subsequence.
The explanation is simpler if you know about completion: in the completion $\hat{X}$ of the space $X$, the given Cauchy sequence will converge to a point $p\in\hat{X}\setminus X$, so any subsequence will converge to $p$.
In your case the completion of $(0,1]$ is (isometric to) $[0,1]$ and the sequence converges to $0$.
An example in a different direction is the sequence $a_n=n$ in $\mathbb{R}$ with the metric
$$
d(x,y)=\min\{|x-y|,1\}
$$
Here every sequence is bounded, but the given sequence does not converge.
Answer: I see only one minor issue in the proof. In the very last paragraph, you say "then for all $N\in\Bbb N,$ take $j\ge l,$" which will be enough to make sure that $|a-x_{n_j}|\geq\epsilon,$ as you say. However, remember that we also want $j\ge N.$ To fix this, say "then for any $N\in\Bbb N,$ take $j=\max(l,N),$" instead. Do you see why we need to change "all" to "any"? Does this choice of $j$ make sense?
One could also prove (more briefly) that a convergent sequence has all of its subsequences converging to the same limit. Hence, since your sequence converges outside the space, so do all of its subsequences.
Comment: [Related](https://math.stackexchange.com/q/457722/28900).


Which database server scales better: PostgreSQL or MySQL?

Question: I'm working on a website that could eventually have a very large database. The website will be an art community not until deviantART. I'll be running a lot of queries for analyzing how the site is used. I expect some of the queries to kill the database because I don't know how to optimize SQL queries (yet). I'm starting out with a small linux VPS and would move to physical servers in the future.
Which database would scale the best given this situation?
Answer: Before you make a decision based on scalability, you might want to read through these two pages and decide how much you value your sanity:

PostgreSQL gotchas
MySQL gotchas
Comment: I'm allowed to have sanity?
Comment: Excellent post. Don't forget, the larger your database gets, the less you will use it's relation features. If you look at the large social web sites you'll see their use of a relational database is limited to pure key / value storage.
Comment: Those links are VERY outdated.
Comment: At least in the PostgreSQL document, many items include "this is true for versions N.M and earlier of Product X" qualifiers.  Where those are missing, a quick experiment with your installed version followed by an email to the document's author could remedy the situation...
Answer: There are some pretty decent threads on this at stack overflow:
https://stackoverflow.com/questions/110927/do-you-recommend-postgresql-over-mysql
https://stackoverflow.com/questions/216601/postgressql-mysql-oracle-diferences
https://stackoverflow.com/search?q=postgres+mysql
That gotchas site is also great :)
Answer: First let me prefix my answer with the fact that I am heavily biased towards PostgreSQL.  I use both PostgreSQL and MySQL very heavily on fairly large site.  I, from time to time, have problems with MySQL falling over performance wise. When this happens, I usually restart it and things go back to normal.  It's also worth noting that we run PostgreSQL on everything from 8 to 32 core boxes and our MySQL cluster runs on a set of 8 core boxes.  Monty, when he was at Sun, stated that MySQL does not scale on a single box beyond 4 cores.
Answer: Really it depends on what kind of queries you will be running.  Unless you are running very complex queries either will be fine for a very large web site. There are good examples of both databases running very large scale web sites
Comment: Very likely true.  But besides performance there is also manageability and general ease of use to consider.  My personal opinion is that postgres wins hands down in that department.  I just can't figure out why everybody else seems to love mysql :p


Node add form alter & submit custom field

Question: I have a content type "event" with a field called "field_pricelist". It's a dropdown with no values, I add the values when I alter the form. The values come from a custom table (install / schema) in my database. I want to save this custom value on insert/update. My code works but I don't think it's the best way to save/update a custom field.. Any suggestions?
function TableManager_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'event_node_form') {

global $user;
$query = db_select('pricelist', 'p');
$query->fields('p');
$query->condition('user_id', $user->uid,'=');
$results = $query->execute()->fetchAll();

$query2 = db_select('field_data_field_pricelist', 'd');
$query2->fields('d');
$query2->condition('entity_id', $form['nid']['#value'],'=');
$results2 = $query2->execute()->fetchAll();

$dropdown_array = array();
foreach ($results as $r) {
    $form['field_pricelist']['und']['#options'][$r->pricelist_id] = $r->pricelist_name;
}
$form['field_pricelist']['und']['#default_value']['0'] = $results2['0']->field_pricelist_value;
$form['#submit'][] = "TableManager_form_submit";
}

}

function TableManager_form_submit($form, &$form_state) {

global $user;

$nid = $form_state['values']['nid'];
$pricelist_id = $form_state['values']['field_pricelist']['und']['0']['value'];

$query = db_update('field_data_field_pricelist');// Table name no longer needs {}
$query->fields(array('field_pricelist_value' => $pricelist_id));
$query->condition('entity_id', $nid, '=');
$query->execute();
}

Comment: Any reason why don't you 1) just add form element on alter, whole, both element itself and it's data; or 2) [provide custom field](https://www.drupal.org/node/1481082) with all that logic enclosed in field itself?
Answer: Try this...
function TableManager_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'event_node_form') {

    global $user;
    $query = db_select('pricelist', 'p');
    $query->fields('p', array('pricelist_id', 'pricelist_name'));
    $query->condition('user_id', $user->uid);
    $results = $query->execute()->FetchAllKeyed(0,1);

    $results['_none'] = "-Select-";

    $query2 = db_select('field_data_field_pricelist', 'd');
    $query2->fields('d', array('field_pricelist_value'));
    $query2->condition('entity_id', $form['nid']['#value']);
    $results2 = $query2->execute()->fetchField();

    if(empty($results2)) {
      $results2['_none']="-Select-";
    }

    $form['field_pricelist'][LANGUAGE_NONE]['#options'] = $results;
    $form['field_pricelist'][LANGUAGE_NONE]['#default_value'] = $results2;

   // $form['#submit'][] = "TableManager_form_submit";  // No longer need of this function

  }

}

Answer: You were done well node form alter but for submitting you need to use hook_node_submit() this is the best way.
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_submit/7.x
(i.e)
function hook_node_submit($node, $form, &$form_state) {

    if($node->type == 'node_machine_name') {
        //your code..
    }
}

Thank You.
Answer: I'd use allowed_values_function property, rather than feeding it in hook_form_alter. So, select field comes with this special property known as 'allowed_values_function'. This property can't be assigned through Drupal UI, but it can be assigned programmatically. What you need to do is to:
Declare hook_update function in your install module file (TableManager.install):
function TableManager_update_7001() {
  // Get the field info
  $field = field_info_field('field_pricelist');
  $field['settings']['allowed_values'] = '';
  $field['settings']['allowed_values_function'] = 'TableManager_field_pricelist_allowed_values';

  // Save the field
  field_update_field($field);
}

Write up your custom code that's going to return an array of values that field should have. Within your TableManager.module file it'd be that easy:
function TableManager_field_pricelist_allowed_values() {
  $list = array();
  // your logic to get the values
  // example list that needs to be returned
  // $list = array(
  //   'pc1' => t('Pricelist 1'),
  //   'pc2' => t('Pricelist 2'),
  //   'pc3' => t('Pricelist 3'),
  // );
  return $list;
}

After that you'll need to run update.php or drush updb (if you're using) and you should be good to go. Your field is going to be updated, so it's gonna use your function.


Let $a_1,a_2,\cdots,a_n$ be $n$ numbers such that $a_i$ is either $1$ or $-1$.If $a_1a_2a_3a_4+\cdots+a_na_1a_2a_3=0$ then prove that $4\mid n$.

Question:
Let $a_1,a_2,\cdots,a_n$ be $n$ numbers  such that $a_i$ is either $1$ or $-1$. If $$a_1a_2a_3a_4+a_2a_3a_4a_5+\cdots+a_na_1a_2a_3=0$$
  then prove that $4 \mid n$.

My work:
By multiplying all the terms, we get,
$$a_1^4a_2^4\ldots a_n^4=1.$$
I think that I will be able to represent $4n$ a power of $1$, but getting no clue. Please help!
I also think that this problem can be done with invariance and extremal principal too. Please help with these approaches too!
Comment: I am curious how many sequences $(a_1,a_2,\ldots,a_n)\in\{-1,+1\}^n$ are there with the required property for a given integer $n>4$ with $4\mid n$.
Answer: $$(-1)^x \cdot 1^{n-x}=a_1^4a_2^4\ldots a_n^4=1$$
As a result, $$2\mid x.$$
Since $$a_1a_2a_3a_4+a_2a_3a_4a_5+\cdots+a_na_1a_2a_3=0$$
we have, $x = n-x$
Thus $$4\mid n.$$
Comment: Please explain how you got $x=n-x$.
Answer: Hint 1 Each term you add is either $+1$ or $-1$. Since they add up to $0$, it must be an even number of terms. This tells you that $n$ is even.
[If this is not clear, what happens if you add an one to each particular term].
Hint 2 You know already that $n$ is even, and that $\frac{n}{2}$ terms (not a's) have to be $1$ and the other half must be $-1$.
In order for $a_ia_{i+1}a_{i+2}a_{i+3}=1$ an even number of $a_i, a_{i+1}, a_{i+2}, a_{i+3}$ must be $-1$.
In order for $a_ia_{i+1}a_{i+2}a_{i+3}=-1$ an odd number of $a_i, a_{i+1}, a_{i+2}, a_{i+3}$ must be $-1$.
So in total, the number of $-1$ which appears as $a_i$ in your expression have the same parity as $\frac{n}{2}$.
How many times does each $a_i$ appear? Can you finish the problem from here?
Comment: I think that I can do it from here. But,the concept is still foggy for me. Can you please elaborate the hints without providing the solution?
Answer: All summands are either $1$ or $-1$.  Since their sum is equal to $0$ the number of summands $1$ is equal to the number of summands $-1$.  The product of all summands is $1$.  This means that the number of summands $-1$ is even.
Answer: Another approach with realisation.
The sum of four consecutive summands can be $0,\pm2,\pm4$. If we change the sign of one $a_i$, then the signs of all these summands will change, the other summands will saved. Therefore, one such change either does not change the sum or changes it to $4$ or $8$. From the sequence $++\ldots +$ with the sum $n$ we can go to any other with the help of several such changes, so the modified sum will be $n + 4k$. It can be equal to zero only if $n\equiv0\pmod 4.$
Realisation. Evidently for $n=4$ there is no example.
$n=8: A=++++----$
$n=12: B=++++-+-+----$
$n\equiv0\pmod 8: AA\ldots A$
$n\equiv4\pmod 8: BAA\ldots A$
Answer: Consider changes in $S=a_1a_2a_3a_4+\cdots+a_na_1a_2a_3$ under the transformations $a_i \mapsto -a_i$.
$\bullet$ If one or three $a_i$'s have the same sign, then $S \mapsto S \pm 4$.
$\bullet$ If two of the $a_i$'s are positive and two negative, then $S \mapsto S$.
$\bullet$ If all four $a_i$'s have the same sign, then $S \mapsto S \pm 8$.
Since $S=0$ initially, after each transformation $4 \mid S$. Applying the transformation $a_i \mapsto -a_i$ whenever $a_i=-1$ leads to the sum $S=n$. Thus, $4 \mid n$. $\blacksquare$


Diferença entre datas

Question: Sempre que passo a diferença de datas no mesmo mês, dá certo, mas quando é entre meses diferentes, vem um valor negativo. Como eu faço uma diferença entre datas? Veja o meu código. O erro está em total
Código
if (($("#txtDateStart").val().split("/") == "") && ($("#txtDateEnd").val().split("/") == "")) {
    data1 = new Date();
    data2 = new Date();
}
else {
    var dtInicio = $("#txtDateStart").val().split("/");
    var dtFim = $("#txtDateEnd").val().split("/");
    data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
    data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
}
var total = data2.getDate() - data1.getDate();

Comment: Peguei esse código e funcionou. var total = (((Date.parse(data2)) - (Date.parse(data1))) / (24 * 60 * 60 * 1000));
Comment: Para 'finalizar' a pergunta, poste sua resposta e/ou forneça feedback com a razão de as respostas dos colegas não terem funcionado pra você.
Comment: Ainda não conseguiu a resposta?
Comment: Porque você ainda não escolheu uma resposta?
Answer: Me baseei numa das melhores respostas do SO em inglês e apliquei ao seu caso concreto:
if ( ($("#txtDateStart").val().split("/") == "") &&
     ($("#txtDateEnd").val().split("/") == "") ) {
   data1 = new Date();
   data2 = new Date();
}
else {
   var dtInicio = $("#txtDateStart").val().split("/");
   var dtFim = $("#txtDateEnd").val().split("/");
   data1 = new Date(dtInicio[2] + "/" + dtInicio[1] + "/" + dtInicio[0]);
   data2 = new Date(dtFim[2] + "/" + dtFim[1] + "/" + dtFim[0]);
}
var total = dateDiferencaEmDias( data1, data2 );

// a e b são objetos Date do JS
function dateDiferencaEmDias(a, b) {
   // Descartando timezone e horário de verão
   var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
   var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

   return Math.floor((utc2 - utc1) / ( 1000 * 60 * 60 * 24) );
}

Answer: Exemplo:
date1 = new Date('2014/01/01');
date2 = new Date('2014/04/01');
var diferenca = Math.abs(date1 - date2); //diferença em milésimos e positivo
var dia = 1000*60*60*24; // milésimos de segundo correspondente a um dia
var total = Math.round(diferenca/dia); //valor total de dias arredondado

Answer: var total = (((Date.parse(data2)) - (Date.parse(data1))) / (24 * 60 * 60 * 1000));

Comment: Qual a diferença da sua solução para a solução dos colegas: [essa](http://pt.stackoverflow.com/a/13054/2998) e [essa](http://pt.stackoverflow.com/a/13050/2998)? Que te levou a postar uma nova resposta ao invés de marca a possivel resposta que lhe ajudou como correta?
Comment: @Fernando uma diferença, por exemplo, é que essa aqui não leva em conta peculiaridades de timezone. Imagino que em dia que tenha mudança de horário de verão, por exemplo, o resultado possa ter uma variação indevida.
Comment: @Fernando, acho que você não leu os posts. Apenas pegou uma resposta minha agora e comentou. Leia antes tudo, horário e etc e depois poste seu comentário. Veja o que me levou a responder agora. Está aí em algum lugar.
Comment: @pnet, li sim! Afinal não post e não comento algo sem ler! E só questionei a diferença entre sua solução e as demais, pois considerei as demais até mais completas e abrangente que a sua, pois como o Bacco comentou tratam timezone, dias negativos, já a sua não. Então gostaria de saber quais os problemas das demais que te levaram a não escolhe-las como resposta e ter a necessidade de postar outra resposta que não apresenta nada relativamente novo em relação as demais pois a formula de multiplicar a diferença pelos dias, minutos, segundos e milissegundos já está presente nas demais respostas?
Comment: @Fernando, eu ainda não marquei nenhuma resposta, não sei porque você está assim. Posso sim marcar uma outra, que não seja a minha, não vejo problema nisso. Como a solução à época estava num comentário e não mais abri essa página, nem me ative as respostas que foram dadas depois. Recebi a comunicação pelo SOpt do Anderson Madeira que estava questionando que eu havia comentado a solução, mas não havia finalizado e como procuro sempre finalizar, ainda que exista algumas perguntas abertas ainda, fui e respondi, mas não finalizei.

Diferença entre datas


How can I get more volume to my (bass-)voice?

Question: I'm a 19 years old male and my (singing!) range is F2-B3, although my I can get down to D2 when I am relaxed.
My friends and I are singing sometimes and then I am mostly the deepest voice.
The weird thing is, that when my friends are singing for instance a C3 or a B2 it sounds very deep that I start to hit a F2 or G2, to sound as deep. But then I realize that I have to go up many notes - which was irritating at first, as my C3 or B2 sounds like a high note compared to the C3 or B2 of the guy next to me... I hope you know what I mean.
The guy next to me has just more volume, so more "in the chest"! When I am singing the same note, it sounds more straining, more "in the throat".
Does anybody of you know some advice how I can improve my volume? Is it about being relaxed?
Comment: I suspect that this is simply a consequence of your lower voice being compared to someone else's, but I don't know for sure.
Answer: Obviously your range will differ from others, as will your tone. It really isn't super profitable to compare your sound to theirs.
You are correct about relaxing and opening the throat; often basses try to "dig" for the low notes and this creates tension which is not a good thing. Go as low as you can in a relaxed open tone, regardless of what your friends can or can't do.
Your volume will naturally peter out as you approach the bottom of your range. Hit the notes you can hit and don't strain yourself trying to churn out the ones you can't.
Hope this helps!


How to setup views exposed filter with result between 2 fields values

Question: I have content type called the materials with 2 temperature fields as Max. and Min.
in the views, there is between operator from filter and normally it use for user could input 2 values to the form for filter.
from my case, I want user could input 1 temperature value in the filter and the views result will be the termperaure between Max. and Min.  fields.
is that any way could approach this function?
Answer: The Range module allows you to add a numeric range field to a content type and provides Views filters allowing you to select values within or without the range.
Answer: Use the Views Filters Populate module. It allows you to populate multiple field filters.
Create 2 filters:

Min (w/ Is less than or Equal to operator)
Max (w/ Is greater than or Equal to operator)

Add an exposed Global: Populate filters filter with both the Min/Max filters selected. This will create an exposed filter that will search for items between your Mix/Max fields.


Is it possible to use a new SDK-style .csproj file for a UWP project?

Question: Has anyone successfully created a .csproj file for a UWP project that uses the new SDK-style .csproj format? I drew inspiration from this question about WPF, and that got me 90% of the way there.
After that, I began using the MSBuild.Sdk.Extras package, which gave me access to uap10.0 as a <TargetFramework>, and after a little bit of tweaking, I got it actually compiling with the following .csproj:
<Project Sdk="MSBuild.Sdk.Extras">
  <PropertyGroup>

    <TargetPlatformVersion Condition=" '$(TargetPlatformVersion)' == '' ">10.0.17134.0</TargetPlatformVersion>
    <TargetPlatformMinVersion>10.0.17134.0</TargetPlatformMinVersion>
    <TargetFrameworks>uap10.0</TargetFrameworks>
    <OutputType>AppContainerExe</OutputType>
    <LanguageTargets>$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets</LanguageTargets>
    <Platform Condition=" '$(Platform)' == '' ">x86</Platform>
    <PackageCertificateKeyFile>Test.UWP_TemporaryKey.pfx</PackageCertificateKeyFile>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)'=='Debug'">
    <OutputPath>bin\x86\Debug\</OutputPath>
    <DebugType>full</DebugType>
    <PlatformTarget>x86</PlatformTarget>
    <DebugSymbols>true</DebugSymbols>
    <DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)'=='Release'">
    <OutputPath>bin\x86\Release\</OutputPath>
    <DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
    <Optimize>true</Optimize>
    <PlatformTarget>x86</PlatformTarget>
    <UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
  </PropertyGroup>

  <ItemGroup>

    <ApplicationDefinition Include="App.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:Compile</Generator>
    </ApplicationDefinition>

    <Page Include="**\*.xaml" Exclude="App.xaml">
      <SubType>Designer</SubType>
      <Generator>MSBuild:Compile</Generator>
    </Page>
    <Compile Update="**\*.xaml.cs" SubType="Code" DependentUpon="%(Filename)" />

     <AppxManifest Include="Package.appxmanifest">
      <SubType>Designer</SubType>
    </AppxManifest>

  </ItemGroup>

</Project>

However, a few problems remain:

When comparing a stock UWP project, and my custom project, the custom project's compiled /bin directory doesn't seem to include dependency .dlls.
(/bin dir for custom project on the left, stock UWP project on the right.)

Visual Studio's intellisense complains about built-in XAML types not being supported.

...which leads to the resultant .exe immediately crashing on boot.
Does anyone have advice for how to get this thing to the finish line?
Comment: Before Microsoft updates all the tooling, please such won't be easy. Attempts like https://github.com/onovotny/MSBuildSdkExtras still need time to be mature enough.
Comment: Oh, sure. I'm not really expecting a smooth ride. Just trying to figure out what steps I'm missing. The UWP build process is pretty opaque.
Answer: ~EDIT MARK II:~ It looks like the current goal is to support .NET Core 3 (which implies new .csproj style) with the release of WinUI 3.0, which is targeting "some time in 2020" for release.
And, in case the links die, the first is a link to a WinUI GitHub issue, where the PM for the WinUI project says

Our current plan is that managed WinUI 3 apps uses .NET Core 3 instead of .NET Native at release time.

And the second link is to the WinUI project's roadmap, which says:

We're planning to release WinUI 3.0 in 2020.

and

2. Preview release: we're planning to release a more complete preview in the first half of 2020

~EDIT:~ There were some quiet announcements at Build 2019 that UWP will begin running on the .NET Core runtime with the release of .NET Core 3. It seems likely this will involve a move to the new .csproj style for UWP projects as well.
ORIGINAL POST:
It would appear that the answer for now, is no. Per Claire Novotny, the smart lady who made the MS Build SDK Extras:

You cannot currently use the SDK style projects for an application itself, only for UWP class libraries. The project system needs to support deploying and launching it in the correct way as well.
Comment: while it was said that we were supposed to be able to target UWP with class libraries, there is no solution on how to do it. Did you ever get documentation on this?
Answer: It seems the answer is no
https://github.com/dotnet/sdk/issues/1408
Apparently

No plans at the moment to support this.
Answer: The third party sdk, see novotnyllc/MSBuildSdkExtras: Extra properties for MSBuild SDK projects
<Project Sdk="MSBuild.Sdk.Extras">
  <PropertyGroup>
    <TargetFrameworks>net46;uap10.0.16299;tizen40</TargetFrameworks>
  </PropertyGroup>
</Project>

Comment: This is sufficient to reference the UWP TargetFramework in an SDK-style project, but not to actually build a UWP application. You'll notice the answer above includes information from the author of MSBuild.Sdk.Extras to that effect.


python logger's descendants - benefits

Question: I'm having trouble to understand the benefits of creating descendants loggers out of my root logger, in each module. For instance:
In project called "foo", module name called "bar":
import logging
logger = logging.getLogger(__name__)
# other pieces of code, that all of them use log...

And same project, but in module "baz"
import logging
logger = logging.getLogger(__name__)
# other pieces of code, that all of them use log...

instead of just, creating one logger object, and make other modules import and use it. For instance in same project:
from foo.logs import logger
# other pieces of code, that all of them use log...

and foo/logs.py would contain something like:
import logging
logger = logging.getLoger('foo')
# some init logic of the logger...

I can get all data I need from the created LogRecord object: filename, funcName, pathname, name, etc...
Why repeat same procedure of creating a descendant logger (calling getLogger) when I use one? it may also have a minor performance footprint no?
Comment: If you have two questions, you should post to questions, so that you can get answers separately, and so that the title shows what you are asking, and so that other having the same questions can more easily find them, and so that you can accept an answer for each question separately, and so that the your questions can be assessed and handled separately...
Comment: You have more control when using multiple loggers. You can the mute your loggers as you wish, for example you can change log level of `foo.bar` logger to `WARNING` and drop the log level of `foo.baz` to `DEBUG`. You can see which module produced the log record when you are viewing the logs.
Comment: Also, if you have two questions at the same time, you should probably read [this answer to question about the amount of effort you should invest before asking a question](https://meta.stackoverflow.com/a/261593/389289)
Comment: @zvone my bad, noted. It is important to me to explain that I have read and searched about this quite a lot. But nevertheless, would you recommend me then to create a new question to get my second question answered?
Comment: Yes, would do that. Remove the second question here and post it as a new question.
Comment: @zvone done. Thanks!
https://stackoverflow.com/questions/52207163/integrate-nullhandler-of-library-into-my-own-projects-logger
Answer: The reason for creating a separate logger for each file is so that you can later customize what is and what isn't logged without changing the source code.
Logging is usually configured via an external file, which can be modified after the installation is installed, even by users who are not software developers.
For the same reason, there are different logging levels which can be used with each logger, in order to allow more or less logs to be produced. Then at some point, when e.g. exhaustive log data from module a is needed for debugging purposes, the configuration file can be modified to show DEBUG log level for module a without cluttering up the log file with debug info from every module in the application.

python logger's descendants - benefits


Comparing a variable with itself in the previous year in R

Question: I still quite new to programming and have a bit of a problem which I haven't been able to find a solution to, although maybe part of that is because I don't know how to phrase my search query (English isn't my first language...). In any case, I have a dataset that is of the following format (simplified; there's data for more years and weeks, and many more goods):

GoodID
Year
Week
Price

1
2015
3
X1

1
2015
4
Y1

1
2016
3
Z1

1
2016
4
U1

1
2017
3
V1

1
2017
4
W1

2
2015
3
X2

2
2015
4
Y2

2
2016
3
Z2

2
2016
4
U2

What I want to do is add a column that displays the price that a certain good had exactly one year ago. That is, it should display what the price was in the same week, but one year prior.

GoodID
Year
Week
Price
Price last year

1
2015
3
X1
NA

1
2015
4
Y1
NA

1
2016
3
Z1
X1

1
2016
4
U1
Y1

1
2017
3
V1
Z1

1
2017
4
W1
U1

2
2015
3
X2
NA

2
2015
4
Y2
NA

2
2016
3
Z2
X2

2
2016
4
U2
Y2

I'm using tidyverse. Previously I was fine with just having the average across the years, which was easy enough:
df <- df %>%
group_by(GoodID, week)%>%
mutate(avgprice = mean(Price)) %>%
ungroup()

but when I want to compare prices with the ones a year prior I am completely lost. It sounds like something that should have an easy solution, something like
mutate(lastprice = Year-1$Price)

but obviously that doesn't work and I don't know how exactly I should word this. I have tried to filter the data
df <- df %>%
filter(year == 2017) %>%
mutate(lastprice = Price)

df <- df %>%
filter(year == 2016) %>%
mutate(lastprice = Price)

but this of course only resulted in the data entries from all other years being purged at the first try.
Does anyone have a suggestion for how I can go about doing this? Thank you!
Answer: Here's a suggested solution (for future posts, please include code so that your dataframe can be easily created so that people can test any responses):
df %>%
  arrange(week, year) %>%
  group_by(Good_ID, week) %>%
  mutate(price_last_year = lag(price))

The key aspect is dplyr::lag(), which takes care of referencing a value from a previous row. It is clever enough to introduce NAs at the boundaries (i.e. for the first entry in each group).
Comment: @MacAskill. Now it works! +/- It is the same answer as Gregor Thomas. At the same time!!! Upvote for both!!!
Comment: Yes, pretty much identical answer to Gegor but I think mine might have a redundant sort by `week`, which I guess is taken care of by the `group_by`, so I think he wins by the slightest margin of conciseness.
Answer: Use lag() to access the value one row up. As long as we group by Good and Week and sort by year, that should give the previous year's price:
df %>%
  group_by(GoodID, Week) %>%
  arrange(Year) %>%
  mutate(Price_Last_Year = lag(Price)) %>%
  ungroup()


Planos de Testes no VSTS

Question: Estou tentando criar Tests Plans no VSTS (versão Free), mas não estou encontrando o local indicado na documentação:

Ao invés disso, recebo essa interface:

Por acaso a versão Free do VSTS não dispõe do recurso de testes?
Answer: Para utilizar essas funcionalidades você precisar ter uma assinatura do Visual Studio Enterprise ou ter instalada  extensão Test Manager que está disponível no Visual Studio Marketplace
Segue o link, https://marketplace.visualstudio.com/items?itemName=ms.vss-testmanager-web
Comment: Nesse caso, nenhum tipo de teste é possível no VSTS sem essas duas opções?
Answer: Boa noite,
Acessar a opção do Menu "Test Plans" > "Test Plans:

Após isto clicar na opção "New Test Plan":

Planos de Testes no VSTS


Help with proof of Girsanov Theorem

Question: I'm studying this proof of Girsanov Theorem and trying the figure out the details however I need some help with this. I noticed there are, also here on stackexchange, a lot of different versions of the Theorem so I start by stating Girsanov the way I know it:
Theorem: Let $X=X_0+A+M$ be a continuous semimartingale on $(\Omega, \mathcal{F}, \mathbb{P})$ w.r.t. a filtration $\mathbb{F}$. Let $\mathbb{Q}$ be another probability measure on $(\Omega, \mathcal{F})$ such that $\mathbb{Q}_t << \mathbb{P}_t$ for all $t \geq 0$ and with density process $Z$.
Then the stochastic integral $Z^{-1} \cdot \langle Z, M \rangle$ is well defined under $\mathbb{Q}$ and $X$ is a continuous martingale on $(\Omega, \mathcal{F}, \mathbb{Q})$ with local martingale part
$$M^{\mathbb{Q}}=M-Z^{-1} \cdot \langle Z, M \rangle$$
Moreover the quadratic covariation $\langle X,Y\rangle$ of two semimartingales under $\mathbb{P}$ is the same under $\mathbb{P}$ and $\mathbb{Q}$.
I will now give the proof from the lecture notes with my ideas and problems.
Let $T^n = \inf\{t > 0 \;:\; Z_t < \frac{1}{n}\}$. On each $[0,T^n]$ we have that $Z^{-1} \cdot \langle Z, M \rangle$ is $\mathbb{P}$-a.s. finite and therefore also $\mathbb{Q}$-a.s. finite. Since $T^n \to \infty$ $\mathbb{Q}$-a.s. the process $Z^{-1} \cdot \langle Z, M \rangle$ is well defined under $\mathbb{Q}$.
I assume for $Z^{-1} \cdot \langle Z, M \rangle$ to be well defined means that it is $\mathbb{Q}$-a.s. finite, correct? And I see that on $[0,T^n]$ the process $Z$ stays away from zero, by why is $Z^{-1} \cdot \langle Z, M \rangle$ $\mathbb{P}$-a.s. finite?
Next the proof continuous with
\begin{align*}
(M^{\mathbb{Q}}Z)_t^{T^n} &= M_0Z_0 + \int_0^{T^n \wedge t} M^{\mathbb{Q}} dZ + \int_0^{T^n \wedge t}ZdM^{\mathbb{Q}} + \langle M^{\mathbb{Q}}, Z \rangle_{T^n \wedge t}\\
&=M_0Z_0 + \int_0^{T^n \wedge t} M^{\mathbb{Q}} dZ + \int_0^{T^n \wedge t}ZdM
\end{align*}
I calculate that $\int_0^{T^n \wedge t}ZdM^{\mathbb{Q}} = \int_0^{T^n \wedge t}ZdM - \langle M^, Z \rangle_{T^n \wedge t}$. Now what to do with the last term? If I use linearity for quadratic covariation (I don know if this even holds) I get $\langle M^{\mathbb{Q}}, Z \rangle_{T^n \wedge t} = \langle M^, Z \rangle_{T^n \wedge t} - \langle Z, \langle Z,M \rangle\rangle_{T^n \wedge t}$. The first term cancels, but what to do with the second?
I now see how it follows that $M^{\mathbb{Q}}$ is a local martingale, but how does that show that $X$ is a continuous semimartingale w.r.t. $\mathbb{Q}$? And that it's local martingale part is $M^{\mathbb{Q}} $? Lastly is there an easy way to see the last claim with the quadratic covariation?
Thanx in advance!
Answer: In order of increasing technicality:

$\langle X,Y \rangle$ is the same under $P$ and $Q$ because $\langle X, Y \rangle_t$ is a $P_t$-limit in probability of $\sum_{i}(X_{t_{i+1}}-X_{t_i})(Y_{t_{i+1}}-Y_{t_{i}})$ for $\{t_i\}$ a partition $\Delta$ of $[0,t]$ as $|\Delta| \to 0$. Since $Q_t \ll P_t$ the $Q_t$-limit also converges, showing that it must be the $Q$-joint variation as well.
The martingale $Z$ is strictly positive $Q$-a.s. First suppose $Q \ll P$ and let $\tau$ be the first time $Z_t$ or $Z_{t-}$ hits $0$, and let $\tau_n$ be the first time $Z \leq 1/n$. Then for positive rational $q$ we have $1/n \geq E[Z_{\tau_n} 1_{\tau_n < \infty}] \geq E[Z_{\tau+q}1_{\tau_n < \infty}]$. Sending $n\to \infty$ give $E[Z_{\tau+q}1_{\forall n, \tau_n < \infty}] = 0$ so $Z_{\tau+q} = 0$ a.s. all $q$ on $\{\tau < \infty\} \subseteq \{\forall n, \tau_n < \infty\}$. Right continuity then implies $Z = 0$ on $[\tau,\infty)$ a.s. Thus $Z_{\infty} = 0$ on $\{\tau < \infty\}$, and hence $Q(\tau<\infty) = \int 1_{\tau < \infty} Z_\infty dP = 0$. For the case $Q_t \ll P_t$ for all $t$, just stop $Z$ at $t$ and apply the result to get $Z$ is a.s. strictly positive on $[0,t]$ for all $t$ a.s., and hence on $[0,\infty)$ a.s.
If $X$ is cadlag and $XZ$ is a $P$-local martingale, then $X$ is a $Q$-local martingale because a localizing sequence under $P$ is also such under $Q$. In particular $MZ - \langle M,Z \rangle = \int Z dM + \int MdZ$, so $ZM-\langle Z,M\rangle$ is a $P$-local martingale, and hence $M-\frac{1}{Z}\langle Z,M\rangle$ is a $Q$-local martingale. Since $\frac{1}{Z}$ and $\langle Z,M\rangle$ are $Q$ semimartingale, $\frac{1}{Z}\langle Z,M\rangle = \int\frac{1}{Z}d\langle Z,M\rangle + \int\langle Z,M\rangle d(\frac{1}{Z})$ under $Q$.
Thus $$M-\int\frac{1}{Z}d\langle Z,M\rangle = (M-\frac{1}{Z}\langle Z,M\rangle) + (\frac{1}{Z}\langle Z,M\rangle-\int\frac{1}{Z}d\langle Z,M\rangle)$$
$$
= (M-\frac{1}{Z}\langle Z,M\rangle) + \int\langle Z,M\rangle d(\frac{1}{Z})
$$ is the sum of two $Q$ local martingales.
Comment: 1. is clear now.
Comment: 2. Where in the proof do we need that $Z$ is strictly positive $Q$-a.s.? The proof uses that $Z^{-1} \cdot \langle Z, M\rangle $ is $P$-a.s. finite on $[0,T^n]$. I see that on this interval clearly stays away from zero, so $Z^{-1}$ stays away from zero. But how to conclude the integral is $P$-a.s. finite?

3. It is clear to me how to conclude $M^Q$ is a local martingale (under $Q$) from the formula you gave. But I'm confused as to how to get to this formula. What to do with the $\langle M^Q, Z \rangle$ term?
Furthermore, ok M^Q is a local martingale, how is X then a semimartingale under Q? Ty
Comment: In your proof, how do you know that $T_n \to \infty$ a.s. ($P$ or $Q$)? Of course $T_n \leq T_{n+1}$ but how do you know that $Z$ doesn't hit zero in finite time? You know this because $Z$ is strictly positive $Q$-a.s., so it must be that $T_n \to \infty$.
Comment: @Dylan I've updated my answer to avoid necessitating that $Z^{-1} \cdot \langle Z,M\rangle$ be $P$=a/s/ finite.

Help with proof of Girsanov Theorem


Como usar icon SVG no addMarker (MarkerOptions) do Google Maps API Android

Question: Estou utilizando o seguinte código de Exemplo da documentação do Google Maps API v2 para Android:
mMap.addMarker(new MarkerOptions()
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_bike))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(41.889, -87.622)));

Funcionou muito bem para imagens .PNG, porem no meu APP só estou utilizando ícones e imagens em .SVG criadas pelo próprio Vector Asset do Android Studio 3, e gostaria de manter esse padrão em todo o aplicativo, mas não conseguir fazer o addMarker aceitar meus arquivos .SVG...
Encontrei a seguinte pergunta no Stackoverflow em Inglês, mas nenhuma resposta funcionou pra mim:
Custom marker in google maps in android with vector asset icon
Preciso deixar claro, que minha necessidade é pegar um arquivo .svg dos diretórios res/drawable e incluir como parâmetro do método icon() da classe MarkerOptions() do Google Maps API v2 p/ Android, por favor só responda se a solução for para esse uso.
Se possível, faça um teste criando qualquer icone .svg no Vector Asset do Android Studio e inclua esse arquivo como icone no MarkerOptions, se funcionar ai no seu Maps, você tem a solução que eu procuro.
Obs:

Meus SVG foram criados corretamente e estão todos funcionais, não é problema nos arquivos svg.
Estou seguindo esse Guia da Documentação do Google Maps
A activity do Mapa esta funcional com icones Bitmap padrão (PNG).
Os testes estão sendo feitos em um (dispositivo físico) Tablet Samsung 7" com Android versão 4.4.4 SDK 19.
Answer: Escreva um método para obter um BitmapDescriptor
private BitmapDescriptor getBitmapDescriptorFromVectorDrawable(int id) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        VectorDrawable vectorDrawable = (VectorDrawable) getDrawable(id);

        int h = vectorDrawable.getIntrinsicHeight();
        int w = vectorDrawable.getIntrinsicWidth();

        vectorDrawable.setBounds(0, 0, w, h);

        Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bm);
        vectorDrawable.draw(canvas);

        return BitmapDescriptorFactory.fromBitmap(bm);

    } else {
        return BitmapDescriptorFactory.fromResource(id);
    }
}

Altere o seu código para usar o método:
mMap.addMarker(new MarkerOptions()
                .icon(getBitmapDescriptorFromVectorDrawable(R.drawable.ic_bike))
                .anchor(0.0f, 1.0f) // Anchors the marker on the bottom left
                .position(new LatLng(41.889, -87.622)));

Nota: O id passado a getBitmapDescriptorFromVectorDrawable() tem de ser de um VectorDrawable(SVG).
Fonte: Get BitmapDescriptor from a VectorDrawable resource for use as an icon on a Google Map Marker.
Comment: Estou recebendo o seguinte erro: VFY: unable to resolve virtual method 18696: L com/example/myfirstapp/ViewMapsActivity;.getDrawable (I)Landroid/graphics/drawable/Drawable;...
E/AndroidRuntime(10017):  at com.example.myfirstapp.ViewMapsActivity.onMapReady(ViewMapsActivity.java:87)... Depois disso o APP para, assim como os outros exemplos que testei e citei na pergunta.
Comment: O código foi testado na versão 4.4.2 e 7.0. Esse erro que refere parece-me ser devido à utilização de um método que não existe na versão do dispositivo, o método só existe numa versão superior da do dispositivo. Como isso é outro problema faça uma nova pergunta, inclua o código do mapa e do arquivo gradle.


Imagemagick convert command in php script not working

Question: I am using php imagemagick and i want to run convert command in php script but it don't work.
My code is here-
<?php
    exec( "/usr/bin/convert new2.png output.jpg");
 ?>

new2.png is in the same directory.
Comment: Hi Kusum Gupta - could you [edit] your question to explain more clearly what is not working. For example, do you get an error? Or does something else happen you weren't expecting?
Comment: @Vince, trying to convert image format (**png to jpg**) through php program execution method ` exec() ` [http://php.net/manual/en/function.exec.php] and open image in browser. Basically i have a file new.php which contain block of code-- `` When i execute this file in my local server i.e. localhost/new.php i get no output.   i want to display this converted image  in browser with jpg format.
Answer: It is a while since I tried this:
1/ php page with you php code called for instance image.php
2/ On another html page use

I assume your image would display if you refreshed your page. When the page loads the image is created but it is not there for the image tag to display.


Philip Glass Etude 16 fingering

Question: Fellow pianists, what's your way of playing motifs from the 16th etude by Philip Glass?
I mean the

d-e flat-d-c sharp-double d; and
d-e flat-d-c-double b flat?

M1

M2
Sorry it is typeset across the line only.

Answer: Excerpt 1
Option A
For the first excerpt — D-Eb-D-C# D:D — the critical element is using finger 2 on the C#. It's not an easy movement to the following octave, particularly getting finger 5 in place on time, but that's the way to do it. The first three notes are a matter of comfort. 3-4-3 or 1-3-1 are both good options.
Option B
A second possibility, if absolutely necessary, would be to use the thumb on C# and then "slide" over the following D. In that case, the fingering would be 2-3-2-1 1:5.
Excerpt 2
Here again, finger 2 on C is the key element. The movement to be Bb octave is tricky because of the need for the short thumb to travel all the way to the Bb. In this case, 1-3-1-2 1:5 is probably best, because it allows the thumb to be close to the Bb right from the beginning. Just make sure when playing the D, the thumb is close to the front edge of the Eb.
Comment: I think I find Option B fractionally easier than Option A for excerpt 1, but they're both okay for me at the marked tempo.

For excerpt 2 I'd go 3-4-3-2 1:5 though, I think.

Philip Glass Etude 16 fingering


how to store values in an empty 2d array in php with 20x20 size 2d array

Question: How can I store values in an empty 2d array?
here is my code. Please tell me what is wrong with the code I'm an newbie trying to learn PHP. Thanks!
$array2d = array(array());

How can I store data make it a 20x20 array?
Comment: If you keep it empty what would be wrong? Why `20x20`?
Comment: Hello sir! I trying insert a random word and insert it to a 20x20 grid.  I think I can only achieve it if I create a 20x20 2d array.
Comment: No need.. Just do loop and assign the random word.
Comment: because i want to position it diagonally.
Answer: If there's nothing between the lines and all you're asking is how to create an empty 20x20 array, this is the way to do it:
$array2d = array_fill(0, 20, array_fill(0, 20, null));

To break that down, the inner array_fill() creates a one-dimensional array with 20 items, which are all null (replace that with any value you want). The outer array_fill() then creates a one-dimensional array filled with 20 arrays created with the inner function.
To set a value to a given index:
$array2d[5][12] = 'A';

Comment: Thank you sir that helps! ^_^


bind zone file inside cfengine

Question: I have some zone files that uses bind specific $GENERATE directive like this
<code>$GENERATE 50-100 srv-${-50,3,d}  A 10.34.38.$
</code>
Now when I add this to cfengine, it tries to expand ${...} and gives an error. I can escape this ${ with \${ and that passes cfengine but I can't use named-checkzone then (cfengine LITERAL directive also will make named-checkzone fail as it adds @@LITERAL in the zone file). One option would be to expand $GENERATE to single lines. Is there any other option I have?
Answer: Is this CFEngine 2 or CFEngine 3?
If it it is CFEngine 3, would it help if you use the built in variable const.dollar for this?
Consider the following example:
<code>body common control {
    bundlesequence => { "test"};
}

bundle agent test {
    reports:
        linux::
            "$GENERATE 50-100 srv-$(const.dollar){-50,3,d}  A 10.34.38.$";
}
</code>
This outputs the following by cf-agent:
<code># /var/cfengine/bin/cf-agent -K -f /tmp/test.cf
R: $GENERATE 50-100 srv-${-50,3,d}  A 10.34.38.$
</code>
Is it something like this you are trying to achieve?

bind zone file inside cfengine


How do I evaluate a decreasing geometric progression to determine Outstanding Loan Balance

Question: A loan is amortized over 5 years with monthly payments at nominal interest rate i=9% convertible monthly. First payment of $1000 is to be paid 1 month before loan date. Each succeeding monthly payments will decrease by 2% after the first payment. Calculate the outstanding loan balance after the 40th payment has been made.
My textbook only showed geometric progression that is increasing which is given by,
$$
 \frac{1-(\frac{1+k}{1+i})^n}{i-k}
$$
but I am not sure how I can evaluate a geometric progression that is decreasing.
Comment: What is represented by $k$?
Answer: Recall the present value for an annuity-immediate $$\require{enclose} a_{\enclose{actuarial}{n} i} = v + v^2 + \cdots + v^n = \frac{1 - v^n}{i}$$ where $v = (1+i)^{-1}$ is the periodic present value discount factor.  When the payments are in geometric sequence, e.g. $$v + (1+k) v^2 + (1+k)^2 v^3 + \cdots + (1+k)^{n-1} v^n,$$ this is simply $1/(1+k)$ times the same annuity-immediate with a different present value discount factor $$v' = (1+k)v,$$ or $$i' = \frac{1+i}{1+k} - 1 = \frac{i-k}{1+k}.$$  Thus it has present value $$\frac{1}{1+k} a_{\enclose{actuarial}{n} i'} = \frac{1 - (v')^n}{i'(1+k)} = \frac{1 - \left(\frac{1+k}{1+i}\right)^n}{i-k},$$ as claimed.
The above derivation does not stipulate that $k > 0$.  The only requirement is that $k \ne i$ for this formula to work.  If $-1 < k < 0$, the payments are geometrically decreasing since then $0 < 1+k < 1$.  So if payments decrease by $2\%$ per month, then $k = -0.02$ in your formula.

You may also want to refer back to this earlier question you asked and I answered.  In that answer, I used $r$ instead of $1+k$.