php regex and possibly using (?<!a)b within my own regex

Question: Trying to work on a PHP regex that will match words that may be functions, that are not in double quotes. While ignoring anything that is in double quotes that may be functions. The below already matches 'hello(world)'. And will place 'hello(world)' in one array then 'hello' in another. However, I want to have a conditional that does not add it as stated above.
preg_match_all('#(\w*)\s*\(.*?\)#i',$str,$m);

I was trying to play with it. And using the following example to help me.
(?<!a)b

Though the pattern turns out wrong when applied. If anyone has any help in the matter, I would appreciate it.
As a output of the current design of the regex. Take the following example.
Input:
one($two) two($1) three($2one)}meme1(you2) this(that) die ("now") these function myfunc($me) empty()
Output:
array (
  0 =>
  array (
    0 => 'one($two)',
    1 => 'two($1)',
    2 => 'three($2one)',
    3 => 'meme1(you2)',
    4 => 'this(that)',
    5 => 'die (\\"meohmy\\")',
    6 => 'myfunc($me)',
    7 => 'empty()',
  ),
  1 =>
  array (
    0 => 'one',
    1 => 'two',
    2 => 'three',
    3 => 'meme1',
    4 => 'this',
    5 => 'die',
    6 => 'myfunc',
    7 => 'empty',
  ),
)

Comment: Strip out double quotes (with content) beforehand. Better yet use the tokenizer, or PHP_Parser; that's more exact (or less effort) than a regex for finding function names.
Comment: @mario I think you may have negated the fact that I am not looking to strip out the quoted lines. Only overlook them. Which if I can figure out how to use (?<!a)b. Can be done. And it is not a duplication of the aforementioned link. In simplicity I have a simple script language designed in another language .. lsl for Second Life. This regex is suppose to scan for key commands from that lsl while not trying to process it. Just to check that its valid in or out of quotes. Using the PHP_Parser to determine simplistic is or is not in quotes will make the end design bulky.
Comment: You're not supposed to throw the original content away, but make a *temporary copy* sans double quoted stuff, then run your regex. You can't have arbitrary-length lookbehinds with PCRE. You are looking to exclude `print "text notafunction(123) there";` right? That could only work with assertions if the string isn't multiline etc.
Comment: @mario And ultimately unneeded when as stated if someone with better understanding of (?<!a)b. Could tell me how to work that in. Would suffice.
Comment: @mario How can I put this in better words. My original regex works perfectly for my needs. It has done its work on that simple base. So pushing it into complexity is a scope thats unneeded for the end means. Oh well will keep seeing how to put (?<!a)b into an applicable context for that regex. Everything else is done in the lsl processor script for the game I have designed. All I need is something to determine is or is not in quotes. Thank you though.
Comment: @mario To add to my above comment. No one has access to the way codes get pushed in our out of the game. Well they shouldn't -heh- This is simply a design structure I wish to add in for myself when polling data. So nothing will be multiline =) Well okay maybe in some case where I might think it looks better multiline. Then that would be something to look at.
Comment: Which part of your example input/output demonstrates the double-quotes requirement?
Answer: As stated in the comment, you can't have arbitrary-length lookbehind. What you can have however, is arbitrary-length lookahead. Just as - I think - you wanted to have a lookbehind to count the ", you can count those who come after. Something along the lines of:
/(\w+)\s*\(.*?\)(?=(?:[^"]|".*?")*$)/

However:
- Be sure you apply this on well formated code
- If would be fooled by an escaped " (you can fix that, I don't have the courage atm)
- I didn't bother looking at the performance, so you may have some work here
Overall, this may not be a good idea.
Edit:
What does it do? I took your regex, and added a check after your matchs. Each time it finds a match, it will check until the end of the string that there is a pair number of " (extremely inefficient against a large string).
A more efficient way? Sure. The fact that you can't catch an undefined number of groups in a regex is a bother. It means you'll have to loop through your string. Basically, use preg_match with all its arguments (get the position of the match in the 'matches' array thanks to the 4th argument (see the preg_match doc) and loop with the 5th), and with something like this:
/(?:[^"]|".*?")*?(\w+)\s*\(.*?\)/

(as I'm writing this, I'm thinking that it's not that efficient either, but is still better against large strings.)
(note: I didn't test it as I'm extremely sleepy, if you're satisfied with either solutions, close the question, if not, I'll be back anyway)
Comment: To be completely honest within the structure of what I was wanting to do this worked perfectly. Like a charm. So much appreciated. I am still learning about regex so while I understand some of it when sectioned. Trying to see how it pieced it in your work. That way I can know how to do it myself in better detail then to be stumped. I was using http://www.functions-online.com as a tool. And the work I am doing is all being passed to a script myself. So no one should be adding bad data. Uness I do something myself thats silly.
Comment: As for escaping data. All data is being escaped before it hits the regex. Which I am hoping that works well enough. I have voted this as best answer as it was what I was wanting. Even if I may have seemed a bit unclear. So thank you kindly again.
Comment: What I meant about the escaped part is: *"I'm a string with a \" lololol" would fool it.
Comment: Also tested the regex against the full input thats being done. Its a basic game but wanted a one line regex. I know it was possible with a few lines. Though I like one line solutions if they can do whats needed. Between the server <> client the response was .2 seconds in overall command processing. The pulled in test file was 1 MB. And was using a PHP server contacting a LSL object within SecondLife.
Comment: Yeah as it could also imply a lookbehind, as you'd have to see if the " has no \ before it. (but the \ could have a \ before and so on... god dammit I need sleep, have fun ;))
Comment: LOL thanks a lot for the help even if you are sleepy. It has helped.
Comment: To give you an idea on how it was being applied. I have done a bit of coding work before but never much with regex. Though all the other ways I looked at were lengthier. And here comes my desire to apply a regex to the solution. The game integrates with a inventory system, player, game, world. Passing commands from in-game to the PHP and back. I just needed a simple way to observe when things were in and out of quotes. What reason? So that I could pass functions between objects without it being called.
Comment: For example say I was having things communicate. And this is only an example. If say the inventory system passed commands to player. But had a relay attached to send also to the game. The quotes would allow player to exec the commands its allowed. And then say it would pass the rest on to world. Then the world would construct a preprocessor with the quoted commands. Then generate a new exec.
Comment: But thats only an example. It may seem ineffective when noted here. Though in any other processing way my work would not well "work".


sed, awk, perl or lex: find strings by prefix+regex, ignoring rest of input

Question: I need to find strings with a certain prefix, followed by a regexp, in a bunch of files, but ignore the rest of the input (including the content of the line before the prefix, and after the end of the matching regexp).
What's the best tool for the job?  grep finds complete lines; sed is usually used just for editing and select-and-replace; awk?  perl?
I also thought about lex, but am I really after a compiler compiler?!

Edit: the input is several thousand of HTML files, the prefix + regular expression would be https://([-.0-9A-Za-z]+\.[A-Za-z]{2,}) (of which I want $1), and the rest of the input ignored.
Comment: Example please. What do you mean by "prefix"?
Comment: "https://" would be the prefix.
Comment: What do you mean by "regexp?"  Examples of the strings would help.
Comment: Why do you think grep is not a solution?  Sounds like it will work just fine with the right expression, but without more details and input samples we're all just guessing.
Comment: Amended the question.
Comment: I don't get it.  Why was this put [on hold], after the problem was clarified, and a proper solution was posted?  What's there that's unclear and requires further amendment?
Answer: If you won't have more than one of the pattern on a single line, I'd probably use sed:
sed -n -e 's%.*https://\([-.0-9A-Za-z]\{1,\}\.[A-Za-z]\{2,\}\).*%\1%p'

Given the data file:
Nothing here
Before https://example.com after
https://example.com and after
Before you get to https://www.example.com
And double your https://example.com for fun and happiness https://www.example.com in triplicate https://a.bb
and nothing here

The sed script produces one entry per line, showing the last entry when there's more than one on the line:
example.com
example.com
www.example.com
a.bb

A Perl script can be used for multiple entries per line:
$ perl -nle 'print $1 while (m%https://([-.0-9A-Za-z]+\.[A-Za-z]{2,})%g);' data
example.com
example.com
www.example.com
example.com
www.example.com
a.bb
$

Comment: I have no clue what the html input is; I'd like to be able to find more than one occurrence of my pattern on any given line.


Por que não consigo mudar o texto da div com ação submit de botão de form?

Question: Tentei isso:

let form = document.querySelector('.form');

function postar(evento){
    evento.preventDefault();
    let conteudo = form.querySelector('.escreverTweet').innerText;
    let display = document.querySelector('.display').innerText;
    display += conteudo;

}

form.addEventListener('submit', postar);
Answer: quando você fez
let display = document.querySelector('.display').innerText;

você pegou o conteúdo em innerText do elemento, e nao o elemento, portanto, você nunca alterou o elemento.
podia tentar algo como
let display = document.querySelector('.display');
display.innerText += conteudo;

Comment: muito obrigado!


How to convert 'void *' return from a C function to 'UnsafeMutableRawPointer' in Swift 3?

Question:
I'm trying to convert a lua bridge from Swift 2 to Swift 3. I am not the original author so there are aspects of the library I don't know very well and the original author seems not interested to continue working on the project. I have most of the conversion done but there remain one place I'm stuck and could not figure out. I've tried searching on SO and on the Internet but could not find anything that could help me solve the problem.
If anyone is interested in looking at the full source code, here is my fork of the project on github: https://github.com/weyhan/lua4swift (My changes is in the Swift3 branch)
Allow me setup the context to the error I'm stuck on. There is a Userdata class, specifically in the method userdataPointer<T>() -> UnsafeMutablePointer<T> the c function lua_touserdata returns the block address of userdata as a void * pointer type.
Original code written in Swift 2:
public class Userdata: StoredValue {

    public func userdataPointer<T>() -> UnsafeMutablePointer<T> {
        push(vm)
        let ptr = lua_touserdata(vm.vm, -1)
        vm.pop()
        return UnsafeMutablePointer<T>(ptr)
    }

    public func toCustomType<T: CustomTypeInstance>() -> T {
        return userdataPointer().memory
    }

    public func toAny() -> Any {
        return userdataPointer().memory
    }

    override public func kind() -> Kind { return .Userdata }

}

After the conversion with Xcode 8 migration tool, Xcode is complaining about the return line with error Cannot invoke initializer for type 'UnsafeMutablePointer<T>' with an argument list of type '(UnsafeMutableRawPointer?)':
return UnsafeMutablePointer<T>(ptr)

I've fixed it with:
return (ptr?.assumingMemoryBound(to: T.self))!

Following that above change, now Xcode 8 is now complaining about the calling statement in createCustomType:
public func createCustomType<T: CustomTypeInstance>(setup: (CustomType<T>) -> Void) -> CustomType<T> {
    lua_createtable(vm, 0, 0)
    let lib = CustomType<T>(self)
    pop()

    setup(lib)

    registry[T.luaTypeName()] = lib
    lib.becomeMetatableFor(lib)
    lib["__index"] = lib
    lib["__name"] = T.luaTypeName()

    let gc = lib.gc
    lib["__gc"] = createFunction([CustomType<T>.arg]) { args in
        let ud = args.userdata

        // ******* Here's the line that is causing problem in Swift 3
        (ud.userdataPointer() as UnsafeMutablePointer<Void>).destroy()
        // *******

        let o: T = ud.toCustomType()
        gc?(o)
        return .Nothing
    }

    if let eq = lib.eq {
        lib["__eq"] = createFunction([CustomType<T>.arg, CustomType<T>.arg]) { args in
            let a: T = args.customType()
            let b: T = args.customType()
            return .Value(eq(a, b))
        }
    }
    return lib
}

Where I'm getting stuck is the line :
(ud.userdataPointer() as UnsafeMutablePointer<Void>).destroy()

I believe the original author is attempting to clear the memory block where the pointer returned by userdataPointer() call is pointing to.
With the Xcode 8 auto migration tool the above line is converted as below:
(ud.userdataPointer() as UnsafeMutableRawPointer).deinitialize()

However Xcode now is then complains that Cannot convert call result type 'UnsafeMutablePointer<_>' to expected type 'UnsafeMutableRawPointer'.
From my research, the change to the return line in userdataPointer seems correct, so I think the issue is with the cast to UnsafeMutableRawPointer. I've tried dropping the cast to UnsafeMutableRawPointer and invoke ud.userdataPointer().deinitialize() directly but I get this error Generic parameter 'T' could not be inferred.
Other things I've tried is to convert the UnsafeMutablePointer to UnsafeMutableRawPointer but It always result in Xcode 8 complaining one thing or another. Any suggestion on how to get this to work?
Answer: As you may have already found out, Swift 3 attempts to provide better type safety when it comes to pointers.  UnsafeMutablePointer can now only represent a pointer to an instance of a known type.  In Swift 2, a C void * was represented by UnsafeMutablePointer<Void>, allowing void and non-void pointers to be treated in the same way, including trying to call a de-initializer of the pointed-to type, which is what the destroy() method in the problematic line of code does:
  (ud.userdataPointer() as UnsafeMutablePointer<Void>).destroy()

In Swift 3 the de-initializer on the pointee is called using the deinitialize() method of the UnsafeMutablePointer structure.  It appears that the migration assistant got confused.  The line
(ud.userdataPointer() as UnsafeMutableRawPointer).deinitialize()

makes little sense because (1) UnsafeMutablePointer cannot be converted using as to UnsafeMutableRawPointer;
 (2) UnsafeMutableRawPointer has not deinitialize() method.  In Swift 3, UnsafeMutableRawPointer is a special type to represent void*.  It is actually quite understandable why the migration tool made this mistake: it blindly replaced destroy() with deinitialize() and UnsafeMutablePointer<Void> with the corresponding Swift 3 type UnsafeMutableRawPointer, without realizing that the conversion would not work.
I don't quite understand why calling destroy() on a void pointer would work in Swift 2.  Maybe this was a bug in the program or some compiler trick allowed the correct de-initializer to be called.  Without knowing enough about the code, I can't be more specific than to suggest analyzing it to figure out what is the type pointed to by that pointer on which destroy() was called.  For example, if we know for sure that it is always the placeholder type T used on the following line:
   let o: T = ud.toCustomType()

then the offending line simply becomes
  (ud.userdataPointer() as UnsafeMutablePointer<T>).deinitialize()

We need the conversion in the parentheses to allow the compiler to infer the generic parameter.
Thank you for bringing up an interesting problem.  BTW, once you get over this obstacle, you are likely to run into other problems.  One thing that jumps out is that UnsafeMutablePointer has no .memory in Swift 3; you'll have to use .pointee instead.
Here's an update.  After playing with Swift 2.2 on Linux, I realize that calling destroy() on an UnsafeMutablePointer cast as UnsafeMutablePointer<Void> won't call A's deinitializer, even if it has one.  So, you have to be careful with that line...
Comment: The Swift 3 migrator seems to convert those `.memory` to `.pointee` right. You are right that the migrator got confused in a few places but generally it works in most of the conversion.

I've managed to fix it by changing the offending line to: `UnsafeMutablePointer(ud.userdataPointer()).deinitialize()`
I think this is correct but if you know it's wrong I'd appreciate if you let me know. Thanks for the long analysis!
Comment: What you did works the same as what I suggested.  Either way we need a cast or initialization just to tell the compiler what the generic parameter is when calling `userdataPointer()`.  Be careful, however: the problematic line in the old code didn't de-initialize user data.  The new code will.  If the subsequent `toCustomType()` call tries to return the same userdata object, it will be already de-initialized.  Of course, I don't know the code, just sharing general observations.
Comment: The old code meaning this line? `(ud.userdataPointer() as UnsafeMutablePointer).destroy()`. Thanks for the heads up. I'll be looking into it.
Comment: Yes, as far as I can tell, that code wasn't doing anything.  Its replacement will actually de-initialize userdata...
Comment: Thanks! I'll definitely be looking out for any side effects.
Answer: Try creating an instance of UnsafeMutableRawPointer instead of trying to cast it:
UnsafeMutableRawPointer<T>(ud.userdataPointer()).destroy()
Comment: Although the form I use was this:
`UnsafeMutablePointer(ud.userdataPointer()).deinitialize()`
Thanks.


Contagem progressiva usando for

Question: Se eu fizer esse for:
for (var i = 0; i < 9; i++) {
  document.write(i);
}

O resultado vai ser: 123456789
Como faço pra ao invés de ser assim: 123456789, ele criar uma contagem com um numeral só?
Tipo uma contagem progressiva.
Comment: O que é "uma contagem com um numeral só"?
Comment: Isso que fiquei com dificultade explicar. Sabe quando a gente ta digitando aqui e mostra quantos caracteres estão faltando? "N caracteres restantes" no casso, esse N, seria "Um numeral só".
Comment: Você quer que ele imprima: 9999999999 - ou você quer que ele execute o loop 10 vezes, mas na última vez ele escreva: 9? Ou nenhum dos dois?
Comment: Só piorou, agora nem tenho ideia do que está falando, esse comentário não parece indicar nada relacionado ao que está na pergunta.
Comment: veja se é isso que vc quer... http://jsfiddle.net/hqh6Lne9/
Comment: Olha minha edição. So aparece um número, certo? Só vai diminuindo.
Answer: Você pode passar argumentos para a função:

var span = document.querySelector('span');

for (var i = 0; i < 10; i++) {
  setTimeout(function(a) {
    span.innerHTML = a;
  }, i * 1000, i);
}

O método setTimeout() recebe como argumentos uma função para ser executada depois que o tempo expira, onde nesse caso é function(a).
O tempo, em Milissegundos, que o método irá esperar antes de executar a função, que nesse caso é i * 1000 - i * 1000 porque a cada iteração o timer var aguardar um tempo diferente (um segundo a mais a cada chamada). 1000 Milissegundos é igual a 1 segundo, nesse caso, o timer irá exibir o contador com 1 segundo de intervalo.
E por último, o método aceita parâmetros, quantos precisar, que poderá ser usada na função interna - nesse caso o parâmetro a da função terá o valor do último parâmetro em , i * 1000, i);
Comment: Isso, serão os parâmetros que poderão ser usados na função.
Comment: Sempre presente os downvotes anônimos :p
Comment: Também não sei o motivo do downvote pra você, foi a melhor resposta ao meu ver. No caso, teve downvote pra todos, não entendi.
Comment: Pode me explicar esse final, Lucas? i * 1000, i
Comment: Claro @LucasCarvalho, editei a resposta, se não ficou muito claro pergunte aqui
Comment: Não, o i * 1000 eu entendi, só não entendi o ,i (virgula i) kk
Comment: Entendi. Obrigado! :)
Answer: Lucas,
se o programa for executado no console ele segue um padrão de execução e imprime tudo que for mandando, não possibilitando um clear, mas há uma gambiarra. A "solução" é usar o console.clear(), só que o problema reside na diferença de execução de browser para browser, como aponta essa página do MDN.
Caso seja para uma textArea ou div:
var i = 0;
theLabel = document.getElementById("minhaDiv");
var interval = setInterval(function(){
    if (i == 100) clearInterval(interval);
    theLabel.innerHTML = i;
    i++;
},
1000);

Answer:

        var i = 10;
theLabel = document.getElementById("counter");
var interval = setInterval(function(){

    theLabel.innerHTML = i;
    i--;
},
1000);

Comment: Gostaria de entender pq deram -1 na minha resposta se é válida?
Comment: Eu não sei qual foi o motivo do negativo porém sempre deixa uma descrição sucinta de como o código funciona. Respostas com código somente as vezes acabam caindo na fila revisão.
Answer: Olá voce tem que colocar seu contador em um div e ir alterando ele com o tempo

for (var i = 0; i < 9; i++) {
    document.getElementById("demo").innerHTML=i
}

Mas eu acredito que um spinner seja uma solução melhor que essa.

.loader {
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

Ai você coloca um timeout.
acho que é para mostrar o load da pagina que você quer eu não estou colocando todo o código mas se for isso que você quer vou atras.

Contagem progressiva usando for


Why are Formula 1 tracks usually oriented clockwise?

Question: In other sports, for example track and field athletics, the track is always oriented counter-clockwise.
Why aren't Formula 1 tracks oriented similarly? (Maybe it's just me, but I find it much more convenient to make left turns than right turns.)
Explanation as to why my question is different than the one linked:
That question asks why tracks are oriented clockwise in other sports, and to me the reasons for that are quite obvious and make sense. However, I was surprised about Formula 1 (and perhaps other car racing?) tracks being oriented unusually.
Comment: Related question: http://sports.stackexchange.com/q/1000/1723
Comment: Interesting piece of trivia: Dutch ice speed skater and Olympic medal winner [Bob de Jong](http://en.wikipedia.org/wiki/Bob_de_Jong) is known to skate clockwise in training every now and then, whereas competition ice skating is always counter-clockwise.
Answer: Simply put, it's their age-old tradition.  In fact, many Europeans ask why North American race circuits are all but universally "anti-clockwise".
The origins of the various traditions are seemingly complex, and certainly debatable, but as I understand it late 1700s American horse racing power brokers purposefully created a US standard of left-turn-only racing, in defiance to England's centuries long right-hand standard.  Then later America doubled-down and did the same exact thing with field and track.  Olympic standards went back and forth in the early days of the modern Olympic era, but world pressure to standardize one way or the other happened to fall in a pro-American era, and basically the world adopted the American left-only standard for track and field – as I understand it - and this in turn influenced just about every other 'rotational sport', if you will.
Then later still, America adopted the German left-side automobile standard, and roadways, and this led to the natural adoption of left-hand race circuits here, and I believe that bit is actually well documented – why left-hand wheeled cars race turning mostly left.
All the while right handed race circuits never lost hold in Europe, from a time before automobiles.
Germans invented automobiles as we know them, and the French invented the Grand Prix format, so one would think they would have also went with left-handed race circuits (both F1 and MotoGP - and all their precursors), but apparently they stuck with the old-school right hand turn standard, which was helped considerably by the fact that certain infrastructure was already built.
(Note: A Brit will no doubt summarize this all quite different: ~"Brits invented the standards in motorsport that all of Europe now uses." : )
But Romans used a sun dial.  A post sticking up in the Northern hemisphere, as the sun moves across the sky East to West, the shadow moves "clockwise" around the dial.
(So basically I have no idea what I'm talking about, but your question hasn't been answered so I'm giving it a go with this "straw man" post.)
I'm going with "it's simply their age-old tradition"., and you fill in the blanks as to why that is.
Comment: Note: related to this is the 1908 summer Olympics in London, where the US tradition started of not dipping the flag as the athletes march by during the opening ceremony.  The US flag bearer – a burly shot putter – stated for the press after, _"This flag dips for no earthly king."_, and it has been a US Olympic tradition ever since.
Comment: You're oversimplifying it. Races aren't done counterclockwise because it's simply a tradition, but it was chosen that way because it's more natural for spectators to watch left-to-right than the other way around. You're also exxagerating the America-England rivalry and I doubt Americans would purposely do something like this to defy English tradition.

https://www.livescience.com/32442-why-are-races-run-counterclockwise.html


A version of fundamental theorem of calculus

Question: Let

$\mu$ be a finite measure defined on the Borel subsets of $\mathbb{R}$ such that $\forall t \in \mathbb{R}, \mu\big(\{t\}\big)=0$;
$F: \mathbb{R} \to \mathbb{R}$ be a continuously differentiable function;
$a,b\in \mathbb{R}$ be such that $a < b$.

Is it true that
\begin{equation}
\int_{[a,b]} F'\bigg(\mu\big((-\infty,t]\big)\bigg) \operatorname{d}\mu(t) = F\bigg(\mu\big((-\infty,b]\big)\bigg) - F\bigg(\mu\big((-\infty,a]\big)\bigg)?
\end{equation}

It is obvious that the result holds if $\mu$ is absolutely continuous w.r.t the Lebesgue measure, i.e. if there exists a non-negative $\varphi \in L^1$ such that for all Borel subsets $A$ of $\mathbb{R}$ it holds that $$\mu (A) = \int_A \varphi(t) \operatorname{d}t.$$
In fact, in this case, the function
$$
\mathbb{R} \to \mathbb{R}, t\mapsto F\bigg(\int_{-\infty}^t \varphi(s) \operatorname{d}s\bigg)
$$
is an absolutely continuous function, with derivative given a.e. by
$$
\mathbb{R} \to \mathbb{R}, t\mapsto F'\bigg(\int_{-\infty}^t\varphi(s)\operatorname{d}s\bigg) \varphi(t)
$$
and so by the fundamental theorem of calculus for absolutely continuous functions
\begin{align}
\int_{[a,b]} F'\bigg(\mu\big((-\infty,t]\big)\bigg) \operatorname{d}\mu(t)  &= \int_{[a,b]} F'\bigg(\int_{-\infty}^t\varphi(s)\operatorname{d}s\bigg) \varphi(t) \operatorname{d}t \\ &= F\bigg(\int_{-\infty}^b \varphi(t) \operatorname{d}t\bigg) - F\bigg(\int_{-\infty}^a \varphi(t) \operatorname{d}t\bigg) \\&= F\bigg(\mu\big((-\infty,b]\big)\bigg) - F\bigg(\mu\big((-\infty,a]\big)\bigg).
\end{align}
However, what about the general case?
Comment: This is a suggestion: Let's start with $F$ being increasing and bounded. Then $G(t)=F(\mu(-\infty,t])$ defines a measure $\mu_G$ on $\mathbb{R}$. Then you may appeal to Lebesgue-Besicovitch differentiation to see you get an expression form $\frac{d\mu_G}{d\mu}$. This will give you the absolutely continuous part of $\mu_G$ with respect to $\mu$.
Answer: 0. We introduce the following notation:

For a finite Borel measure $\mu$ on $\mathbb{R}$, we write
$$G(x) = \mu((-\infty, x]).$$

If $f$ is a function on $[a, b]$, then
$$ \bigl[ f \bigr]_{a}^{b} = f(b) - f(a). $$

If $f$ is right-continuous and has left-limit at $a$, then we write the jump size of $f$ at $a$ by
$$ f(a^-) = \lim_{x\uparrow a} f(x) \qquad\text{and}\qquad \Delta f(a) = f(a) - f(a^-). $$

1. Suppose that $\mu$ is atomless. Then we indeed have
$$ \int_{[a,b]} (F'\circ G) \, \mathrm{d}\mu = \bigl[ F\circ G \bigr]_{a}^{b}. \tag{$\diamond$} $$
In order to prove this, let $\Pi = \{a = x_0 < x_1 < \dots < x_n = b\}$ be a partition of $[a, b]$. Then
\begin{align*}
\left| \int_{[a,b]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{a}^{b} \right|
\leq \sum_{i=1}^{n} \left| \int_{(x_{i-1}, x_i]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{x_{i-1}}^{x_i} \right|. \tag{1}
\end{align*}
By the mean value theorem, there exist $y^*_i, z^*_i \in [G(x_{i-1}), G(x_i)]$ such that
$$
\int_{(x_{i-1}, x_i]} (F'\circ G) \, \mathrm{d}\mu
= F'(y^*_i) \mu((x_{i-1}, x_i])
= F'(y^*_i) \bigl[ G \bigr]_{x_{i-1}}^{x_i} \tag{2}
$$
and
$$
\bigl[ F\circ G \bigr]_{x_{i-1}}^{x_i} = F'(z^*_i) \bigl[ G \bigr]_{x_{i-1}}^{x_i}. \tag{3}
$$
So it follows that
\begin{align*}
\text{(1)} = \sum_{i=1}^{n} \left| F'(y^*_i) - F'(z^*_i) \right| \bigl[ G \bigr]_{x_{i-1}}^{x_i}.
\end{align*}
Letting the mesh size $\|\Pi\| = \max\{ x_i - x_{i-1} : 1 \leq i \leq n\} \to 0$, this bound converges to $0$ by the uniform continuity of $G$ and $F'$.

2. Now we turn to the general case. We claim that, for any $F \in C^1([a,b])$, the following holds:
$$
\begin{aligned}
\int_{(a,b]} (F'\circ G) \, \mathrm{d}\mu
&= \bigl[ F\circ G \bigr]_{a}^{b} - \sum_{x \in (a, b]} \left( \Delta(F\circ G)(x) - F'(G(x)) \Delta G(x) \right).
\end{aligned} \tag{$\dagger$}
$$
Note that the domain of integration is $(a, b]$ and not $[a, b]$. This is merely for convenience, and the version for the integral over $[a, b]$ may be obtained by adding the term $F'(G(a))\Delta G(a)$ to the right-hand side of $(\dagger)$.
In order to prove $(\dagger)$, let $\mathcal{D}$ denote the set of discontinuities of $G$ on $(a, b]$. Since $\mu$ is finite and $\mathcal{D}$ is at most countable, for each $\delta > 0$ we can find a finite subset $\mathcal{D}_{\delta} \subseteq \mathcal{D}$ such that
$$ \mu(\mathcal{D}\setminus\mathcal{D}_{\delta}) < \delta. $$
Now fix $\epsilon > 0$. Then we can find $\delta \in (0, \epsilon)$ such that
$$ \forall x, y \in [a, b] \ : \quad |x - y| < \delta \ \Rightarrow \ |F'(x) - F'(y)| < \epsilon. $$
Then by noting that $G$ is either continuous or has jump size less than $\delta$ at each point of $(a, b]\setminus\mathcal{D}_{\delta}$, we can find a partition $\Pi = \{a = x_0 < \dots < x_n = b\}$ of $[a, b]$ satisfying the following conditions:

$\mathcal{D}_{\delta} \subseteq \Pi$,

If $x_i \in \mathcal{D}_{\delta}$, then $(G(x_i^-) - G(x_{i-1})) < \frac{\epsilon}{|\mathcal{D}_{\delta}|} $ and $\left| F(G(x_i^-)) - F(G(x_{i-1})) \right| < \frac{\epsilon}{|\mathcal{D}_{\delta}|} $.

If $x_i \notin \mathcal{D}_{\delta}$, then $ [G]_{x_{i-1}}^{x_i} < \delta $.

Using this, we may write
\begin{align*}
\int_{(a,b]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{a}^{b}
= \sum_{x \in \mathcal{D}_{\delta}} \left( F'(G(x)) \Delta G(x) - \Delta(F\circ G)(x) \right) + \Sigma_{\text{c}} + \Sigma_{\text{d}},
\end{align*}
where
\begin{align*}
\Sigma_{\text{c}}
&:= \sum_{\substack{1 \leq i \leq n \\ x_i \notin \mathcal{D}_{\delta}}} \left( \int_{(x_{i-1},x_i]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{x_{i-1}}^{x_i} \right), \\
\Sigma_{\text{d}}
&:= \sum_{\substack{1 \leq i \leq n \\ x_i \in \mathcal{D}_{\delta}}} \left( \int_{(x_{i-1},x_i)} (F'\circ G) \, \mathrm{d}\mu - [F(G(x_i^-)) - F(G(x_{i-1}))] \right).
\end{align*}
We study $\Sigma_{\text{c}}$ and $\Sigma_{\text{d}}$ separately.

For each $i \in \{1,\dots,n\}$ such that $x_i \notin \mathcal{D}_{\delta}$, Mean Value Theorem allows to choose $y^*_i$ and $z^*_i$ in $[G(x_{i-1}), G(x_i)]$ satisfying $\text{(2)}$ and $\text{(3)}$. Moreover, $ [G]_{x_{i-1}}^{x_i} < \delta $ implies $\left| y^*_i - z^*_i \right| < \delta$. So
\begin{align*}
\left| \int_{(x_{i-1},x_i]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{x_{i-1}}^{x_i} \right|
\leq \left| F'(y^*_i) - F'(z^*_i) \right| \bigl[ G \bigr]_{x_{i-1}}^{x_i}
< \epsilon \bigl[ G \bigr]_{x_{i-1}}^{x_i}.
\end{align*}
Summing this over all $i \in \{1,\dots,n\}$ satisfying $x_i \notin \mathcal{D}_{\delta}$, we obtain
$$ \left| \Sigma_{\text{c}} \right| \leq \epsilon [G]_{a}^{b}. $$

For each $i \in \{1,\dots,n\}$ with $x_i \in \mathcal{D}_{\delta}$,
$$ \left| \int_{(x_{i-1},x_i)} (F'\circ G) \, \mathrm{d}\mu \right|
\leq \left( \sup |F'| \right) (G(x_i^-) - G(x_{i-1}))
< \left( \sup |F'| \right) \frac{\epsilon}{|\mathcal{D}_{\delta}|}. $$
So it follows that
$$ \left| \Sigma_{\text{d}} \right| \leq \epsilon \left( 1 + \sup |F'| \right). $$

Together these prove that
$$ \left| \int_{(a,b]} (F'\circ G) \, \mathrm{d}\mu - \bigl[ F\circ G \bigr]_{a}^{b} - \sum_{x \in \mathcal{D}_{\delta}} \left( F'(G(x)) \Delta G(x) - \Delta(F\circ G)(x) \right) \right| < \epsilon \left( 1 + \sup |F'| + [G]_{a}^{b} \right) $$
and letting $\epsilon \to 0^+$ proves $(\dagger)$.
Comment: @Bob, Since I do not have a reference that immediately comes into my mind, I included the proof as well. The case of $\int_{(a,b]} F'(G(x^-))\,\mu(\operatorname{d}x)$ then easily follows by noting that $$\int_{(a,b]} (F'(G(x))-F'(G(x^-))) \,\mu(\operatorname{d}x)=\sum_{x\in(a,b]} (F'(G(x))-F'(G(x^-))) \mu(\{x\}).$$
Comment: Can you give me a pointer to a reference where $(1)$ is proved? I'm wondering what happens if, with your notation, we try to calculate $\int_{[a,b)} F'\big(G(x^-)\big)\mu(\operatorname{d}x)$ in the *atomic* case.


Probability of picked card being a spade or ace

Question: A pack of card is well shuffled and . Top 25 cards are removed. From the remaining cards 14th card from top is picked find the probability of card being an Ace or a Spade.
Comment: If the deck is well-shuffled, any card can be in any position with equal probability. Therefore any card can be in the $25+14$th position with equal probability... Is there something I'm missing?
Comment: The removal of the top 25 cards has no effect on the probability distribution of the bottom 27 cards.  Each card remains uniformly likely to be any card in the deck.
Comment: I do not know the answer but I want to know that removal of 25 cards will have what effect on probability.
Comment: @Joshua and mjqxxxx Thanks I was in doubt
Comment: @ArpitBajpai: All permutations of the cards are equally likely. So the preliminary counting is irrelevant. You will be happy if you get an Ace or a Spade. How many cards make you happy?
Comment: There will be 16 cards or in other words favourable events.
Answer: The chosen card is the $39$-th from the top of the shuffled deck. All permutations of the deck are equally likely, so each of the $52$ cards is equally likely to be in the $39$-th position. $16$ cards are either an ace, a spade, or both, so the probability of getting one of these cards is
$$\frac{16}{52}=\frac4{13}\;.$$


Bochner's Theorem and Universal Kernels

Question: Bochner's theorem asserts that a shift-invariant and properly scaled continuous kernel $K(x,y) = k(x-y)$ is positive definite (and hence a reproducing kernel of some RKHS) if and only if its Fourier transform $p(w)$ is a probability distribution:
$$k(x-y) = \int_{\mathbb{R}^d} p(w) e^{i w^T(x-y)} dw$$
I am now wondering what this expression tells us about the universality of the corresponding RKHS. For which probability distributions $p(w)$ is the kernel $k(x-y)$ universal? Are there necessary and sufficient conditions?
Comment: Do you know the paper [https://jmlr.org/papers/volume7/micchelli06a/micchelli06a.pdf](https://jmlr.org/papers/volume7/micchelli06a/micchelli06a.pdf)?
Comment: Thanks, I will have a look
Answer: We can write this continuous positive definite kernel as $$k(x-y) = \int_{\mathbb{R}^d} p(w) e^{i w^T(x-y)} dw = \int_{\mathbb{R}^d}  e^{i w^T(x-y)} d\mu(w),$$ in which $$\mu(A)=\int_{A} p(w) dw,$$ to each measurable set $A\subset \mathbb{R}^d$, and $\rho:\mathbb{R}^d\to [0,\infty)$ is a measurable function.
If $\rho\in L^1(\mathbb{R}^d)$ and $supp(\mu)$ has positive Lebesgue measure then Theorem 15 of https://jmlr.org/papers/volume7/micchelli06a/micchelli06a.pdf tell us that $K$ is a universal kernel.
Please see also Theorem 3.7 in https://doi.org/10.1007/s11117-016-0414-4 to density in $C_0(\mathbb{R}^d)$.
You can find some related result searching for "\( K(x,y)=f(x-y)\)  universal kernel" on SearchOnMath, for instance.
Comment: I agree, when $\rho\in L^1$.
Comment: Thanks again, I have to admit this is surprising to me. Is $\lambda(supp(\mu))>0$ also a necessary condition? What happens if $supp(\mu)$ has zero measure?
Comment: This is a good question, and I do not know a general answer. You can ask something also when $\rho\not\in L^1(\mathbb{R}^d)$. Note that $K(x-y)=\cos(f(x)-f(y))=cos(f(x))\cos(f(y))+\sin(f(x))\sin(f(y))$ is not a universal kernel, because it is not strictly pd.
Comment: This text is also related to your question [https://arxiv.org/pdf/1003.0887.pdf](https://arxiv.org/pdf/1003.0887.pdf)
Comment: Quick thought, if $p(w) \in L^1$ but vanishes almost everywhere, then the kernel is zero, right? So it will not be universal
Comment: Yes because it is continuous.
Comment: So for continuous tranlsation invariant positive definite kernels $\lambda(supp(\mu))>0$ is not only sufficient but also necessary for universality?

Bochner's Theorem and Universal Kernels


How to guarantee if a real function is $C^\infty$ without using $f^{(n)}$

Question: I know that function $f(x)=x+\frac{1}{1+e^x}$ is $C^\infty$ but I wanna prove that.
Question
Is there something that I could use to guarantee this without actually calculating $f^{(n)}$ ?
Answer: It is the sum of a trivially $\mathcal C^\infty$ function and the reciprocal of another  $\mathcal C^\infty$ function which never vanishes. The rules of computation of the derivative of a reciprocal show this reciprocal is also  $\mathcal C^\infty$.


How to send an email to all members of a group after the group is flagged?

Question: I use the Group module. I create a flag to mark groups. I wish that when a group is marked, an email is sent to all members of that group. How to do this ?
I created the following rule, but I find nothing in "conditions" in relation to the groups :
{ "rules_email_groupe" : {
    "LABEL" : "Email groupe",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_achats_groupes" : [] },
    "DO" : [
      { "mail" : {
          "to" : "firstname.lastname@example.com",
          "subject" : "Invitation \u00e0 la vente group\u00e9e de [flagged-group:title]",
          "message" : "Bonjour,\r\n\r\n\r\nle groupe [flagged-group:title], vous invite \u00e0 sa vente group\u00e9e.\r\nElle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2].\r\n\r\n\r\nCordialement,\r\nL\u0027\u00e9quipe [site:name]\r\n[site:url]\r\n\r\nPour rester inform\u00e9 des nouveaut\u00e9s et b\u00e9n\u00e9ficier de nos offres promotionnelles, suivez-nous sur :\r\nhttps:\/\/www.facebook.com\/S1biosecom\r\nhttps:\/\/twitter.com\/S1biosecom\r\nhttps:\/\/plus.google.com\/+S1biosecom\r\nhttps:\/\/www.pinterest.com\/S1biosecom\r\n\r\nPS : ceci est un mail automatique, merci de ne pas y r\u00e9pondre.",
          "from" : "[site:mail]",
          "language" : [ "flagging-user:language" ]
        }
      }
    ]
  }
}

Any suggestions?
Some more details about my setup:

An overview of the Flags I've defined:

More info about some of my fields (I also use Display Suite):

The fields I defined for my Group Type "Entreprise":

Update: By using the Rules Component included in the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?" I'm getting closer, but I still have to find out what to do with those 2 date variables I've to pass to that Rules Component, as shown here:
Comment: @Pierre.Vriens Thank you this is exactly the question
Comment: Please QA-review my edited of your question (I only tried to explain the screenprints you added). Feel free to rework if needed, or simply perform a rollback to the prior version if you don't like my edits at all, ok?
Answer: Looking at the rule you included, it seems that your Rules Event is fine. But obviously your Rules Action (to send an eMail) is to only send it to 1 (hardcoded) eMail ID. Read on for more details about how you can get this to work ...
Step 1:
Create a flag (similar to yours) to flag a group. In my case I named it (surprise ...) "Flag a group", and with machine name "flag_a_group" (just replace in what follows this machine name of that flag with your own flag's machine name).
Step 2:
Create a Rules Component "Send eMail to all members of a Group", which you can do like so:

The type of this component is an "Action Set" (no need for any conditions).
Action 1 is to build a list of all the members of the flagged group. It uses "Fetch entity by property", with these additional specs:

Entity type value = Group Membership.
Property value = Group.
Value of the data selector = Group.
limit result count = blank (we do not want to limit the nr of results).
Provided variables = "Group members" (variable label) and "group_members" (variable name).

Action 2 is to iterate (= loop) over each of the members of the flagged group. It uses "Add a (rules) loop", with these additional specs:

The list to loop over = group-members
Current list item = "Member of group" (variable label) and "member_of_group" (variable name).
Sub-action (i) of this Action 2 is to just "Show a message on the site" (while QA-testing this Rules Component), with message type = Status and with a message something like "Group member named "[member-of-group:user:name]" and eMail "[member-of-group:user:mail]" will receive an eMail because of flagging this "[group:group-type]" group titled "[group:title]" and id "[group:gid]" (note the various tokens which might be interesting).
Sub-action (ii) of this Action 2 is to actually send an eMail to the "member_of_group" being processed in the loop, using various tokens similar to those in Sub-action (i).

Here is how the Rules Component looks like (in Rules export format):
{ "rules_send_email_to_all_members_of_a_group" : {
    "LABEL" : "Send eMail to all members of a Group",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "TAGS" : [ "group" ],
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "group" : { "label" : "Group", "type" : "group" } },
    "ACTION SET" : [
      { "entity_query" : {
          "USING" : {
            "type" : "group_membership",
            "property" : "group",
            "value" : [ "group" ]
          },
          "PROVIDE" : { "entity_fetched" : { "group_members" : "Group members" } }
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "group-members" ] },
          "ITEM" : { "member_of_group" : "Member of group" },
          "DO" : [
            { "drupal_message" : { "message" : "Group member named \u0022[member-of-group:user:name]\u0022 and eMail \u0022[member-of-group:user:mail]\u0022 will receive an eMail because of flagging this \u0022[group:group-type]\u0022 group titled \u0022[group:title]\u0022 and id \u0022[group:gid]\u0022" } },
            { "mail" : {
                "to" : "[member-of-group:user:mail]",
                "subject" : "eMail notification to group [group:title]",
                "message" : "Hello [member-of-group:user:name],\r\n\r\nyou are a member of the group [group:title] (which is of type [group:group-type]).\r\n\r\nYou are receiving this eMail since user [site:current-user] just flagged this group.\r\n\r\nGreetings,\r\n\r\nPS: contact the site admin by eMail (via [site:mail]) for more details if needed",
                "language" : [ "" ]
              }
            }
          ]
        }
      }
    ]
  }
}

If you have the Rules UI enabled you can simply import the above rule in your own site, no need to tweak anything in it, though you may want to tune the Subject and Message content of the actual eMail as you want (just remember the various tokens you may want to use).
Step 3:
Create a rule "Send a group notification by flagging a group", which you can do like so:

Rules Event: When a group is flagged with the flag from Step 1.
Rules Conditions: none (no need for it).
Rules Action: perform the Rules Component from Step 2.

Here is how the rule looks like (in Rules export format, disabled as shown here):
{ "rules_send_a_group_notification_by_flagging_a_group" : {
    "LABEL" : "Send a group notification by flagging a group",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "flag" ],
    "ON" : { "flag_flagged_flag_a_group" : [] },
    "DO" : [
      { "component_rules_send_email_to_all_members_of_a_group" : { "group" : [ "flagged-group" ] } }
    ]
  }
}

If you have the Rules UI enabled you can simply import the above rule in your own site, after you adapt the flag's machine name to fit yours. Don't forget to enable the rule also.
Step 4:
Add any additional parameters to the Rules Component to pass any relevant extra data from the rule (from Step 3) to the Rules Component (from Step 2). E.g. that date field you added to the flag to be included in the email also (as in your question, like "Elle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2].".
For more details about this, refer to the answer to "How to pass a Flag field's value to a Rules Component triggered by the flag?". Some more details about how to use that answer in the context of this question also:

looking at the message of the eMail in your rule here, I see 2 tokens that look like dates: [flagging:field-flag-date:value] and [flagging:field-flag-date:value2]. But your screenprints do not show how this "field-flag-date" is defined.
My best guess is that you have 1 field with 2 values, no?. If so, you only need 1 Rules Condition to check "Entity has field", which I think will be "flagging:field_flag_date". And in the Rules Action you should then be able to specify (drill down) to both [flagging:field-flag-date:value] and [flagging:field-flag-date:value2].

Voilà
So here you go: only 3 (robust) modules (Flag, Rules and Group) is what's needed to be able to trigger an eMail of all members of a Group that is flagged by an authorized user (with zero custom code).
True, the actual eMail is hardcoded in the Rules Component (would be nice to transform that into something with 2 extra Flag "fields", to specify during the flagging what the actual Subject and message content of the eMail should be).
VBO alternative
Another solution could be to use a combination of Rules and VBO. That would have the advantage that you get all the power of Views available to filter which group members you want to be eMailed ...
Comment: Thank you, it works. However it is possible to retrieve the date field that I added to the flag to include in the email. As my question ? "Elle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2]."
Comment: @Mathieu : merci for the accept. Check my edited answer (Step 4 that I added) to also address your previous comment ("solution to the problem, changes the problem", right?). Disclosure: I haven't QA-tested that, but as per standard Rules facilities that MUST work.
Comment: Thank you, but I do not understand what I have to add in step 2. I know the rules, but I find the components.
Comment: @Mathieu : your prior comment is a bit hard to understand (is it incomplete?). Also, how about posting that as a new question, with a link (reference) to this answer if you want? And a question that is something like "How to pass additional parameters to a Rules Component from a Rule that invokes it" (+ in the question details you explain that you want to apss some flagging-data from the Rules Event). What do you think?
Comment: I do not control the components and I do not understand how to add "Elle commencera [flagging:field-flag-date:value] et se terminera [flagging:field-flag-date:value2]."
Comment: Thank you for your new answers. I do not know what hostname to use for the date field of the flag. There is one field that includes a start date and an end date. Should I use the field catching 1 or celuis capture 3?


Natural panoramic camera controls

Question: A user is looking at his screen, interacting with a camera set in a world at position $(0, 0, 0)$, looking at $(0, 0, -1)$ and with an "up" direction of $(0, 1, 0)$.
The user's viewport width is $w$ and his viewport height is $h$.
The camera's focal length is $f$, the focal width is $w_f$ and focal height is $h_f$.
Vectors can be represented in the four coordinate systems:

the viewport coordinate system (in pixels) ($x_p$),
the film coordinate system ($x_f$),
the camera coordinate system ($x_c$),
the world coordinate system ($x_w$).

And converted via the following transformation equations:

$x_f = T_{f \leftarrow p} x_p$
$x_c = T_{c\leftarrow f} x_f = T_{c\leftarrow f} T_{f\leftarrow p} x_p $
$x_w = T_{w\leftarrow c}x_c = T_{w\leftarrow c}T_{c\leftarrow f} T_{f\leftarrow p} x_p$

As a user drags his mouse on the screen from the initial position $p_i$ to the final position $p_f$, I want to find the transformation $T_{w\leftarrow c}$ such that

$p_{i_{world}} = p_{f_{world}}$
The up direction is maintained

In other words, the point in the world under the mouse "follows" the mouse as it is being dragged and the camera does not experience roll about the "look at" vector. Similar to how your pointer follows your finger while panning on google maps, but in 3D with a fixed camera looking at a 3D picture.
Here's what I got so far:
In this situation, $T_{c\leftarrow f}$ and $T_{f\leftarrow p}$ are constant since the camera's film size, the camera's focal length and the viewport size are constant.
This means that provided I know the initial mouse position $p_{i_{pixels}}$ and final mouse positions $p_{f_{pixels}}$. Then (1) can be rexpressed as
$$ p_{i_{world}} = T_{f_{w \leftarrow c}} p_{f_{camera}} $$
Since I can calculate both $p_{i_{world}}$ and $p_{f_{camera}}$, then I can find an axis-angle representation of $T_{f_{w \leftarrow c}}$.
$$ \theta = \cos^{-1} \left( \frac{ a \cdot b }{ |a| |b| } \right) $$
$$ \hat{n} = \frac {a \times b} {| a \times b |} $$
Where $a = p_{i_{world}}$ and $b = p_{f_{camera}}$.
I can turn that into a quaternion if I want, but if I apply that to my camera, I lose condition (2) and the user experiences some dizzying roll of his camera.
What kind of transformation should I do to get a $T_{w \leftarrow c}$ that maintains the up condition and $p_{i_{world}} = p_{f_{world}}$?
Comment: I'm leaving this question open because I'd rather give the bounty to the true solution (if there is one) rather than an approximate solution.
Answer: For those of you who can make do with an approximate solution. I found
one using small-angle approximations and Euler angles.
First, $T_{w \leftarrow c}$ can be expressed using Tait-Bryan angles in the
$YXZ$ order (yaw about $y$, pitch about $x'$, roll about $z^{\prime\prime}$).
In this order, condition (2) (maitaining the up direction) can be respected if we
restrict the roll angle to $0$.
For $\theta$ is the yaw angle about the $y$ axis and $\phi$ is the pitch angle
about the $x'$ axis, the corresponding transformation matrix is the following:
\begin{equation}
T_{w \leftarrow c} =
\begin{bmatrix}
  C_{\theta} & S_\theta S_\phi & S_\theta C_\phi \\
  0          & C_\phi          & - S_\phi        \\
  -S_\theta  & C_\theta S_\phi & C_\theta C_\phi
\end{bmatrix}
\end{equation}
But because the notation is getting tedious, from now on
\begin{equation}
T       = T_{w\leftarrow c} \\
p_{1_c} = p_{i_{camera}}    \\
p_{2_c} = p_{f_{camera}}    \\
p_w     = p_{world}.
\end{equation}
Recalling condition (1),
\begin{equation} \label{eq:T}
p_w = T_2 p_{2_c} = T_1 p_{1_c}
\end{equation}
Now, since we both know $p_{1_c}$ (the corresponding mouse position at the last
frame) and $p_{2_c}$ (the mouse position at the current frame). We know that
\begin{equation} \label{eq:d}
p_{1_c} = D p_{2_c}
\end{equation}
And thus,
\begin{equation}
T_2 p_{2_c} = T_1 D p_{2_c} \\
\Rightarrow T_2 = T_1 D \\
\end{equation}
Great! If I can solve (or approximate) $D$, I can find $T_2$!
Since $p_{1_c}$ and $p_{2_c}$ are "not far away" from each other. We can assume
that they are some small $\Delta \theta$ and small $\Delta \phi$ away from one
another.
\begin{equation}
D =
\begin{bmatrix}
  C_{\Delta\theta}  & S_{\Delta\theta} S_{\Delta\phi} & S_{\Delta\theta} C_{\Delta\phi} \\
  0                 & C_{\Delta\phi}                  & - S_{\Delta\phi}                \\
  -S_{\Delta\theta} & C_{\Delta\theta} S_{\Delta\phi} & C_{\Delta\theta} C_{\Delta\phi}
\end{bmatrix}
\end{equation}
Using small-angle approximations, we know
$$
\sin x \approx x \\
\cos x \approx 1 - \frac{x^2}{2}
$$
Knowing this and $p_{1_c} = D p_{2_c}$, we can get second degree polynomial
equations for $\Delta\theta$ and $\Delta\phi$. In fact, from the second row of
the matrix, we find that
$$
0 = - \frac{y_2}{2} \Delta\phi^2 -z_2 \Delta\phi + (y_2 - y_1) \\
$$
For which we can find two solutions. We will choose the one that respects the
small-angle assumption.
$$
\Delta\phi = \frac{-b \pm \sqrt{b^2 - 4 a c}}{2a}
$$
And finally, from the first row of the matrix we get,
$$
0 = - \frac{x_2}{2} \Delta\theta^2 - (\Delta\phi y_2 + z_2 ( 1 - \frac{\Delta\phi ^2}{2})) \Delta\theta + (x2 - x1)
$$
For which we can find two solutions. And by choosing the one that respects the
small-angle assumption, we have successfully approximated $D$!
$$
\Delta\theta = \frac{-b \pm \sqrt{b^2 - 4 a c}}{2a}
$$
Now that $D$ is approximated, we can calculate $T_2$ by adding $\Delta\theta$
and $\Delta\phi$ to the angles of $T_1$.
We're done!
Comment: [Demo.](https://charlespwd.github.io/natural-panoramic-controls/)
[Source code.](https://github.com/charlespwd/natural-panoramic-controls/)

Natural panoramic camera controls


Is it possible to trace the delegation path for a DNS lookup?

Question: I'm trying to determine why a Nagios host check is failing (hostnames and IPs have been changed to protect the guilty):
: jmglov@laurana; host www.foo.com
;; connection timed out; no servers could be reached

: jmglov@laurana; for ns in `grep -o '\([0-9]\+[.]\)\{3\}[0-9]\+$' /etc/resolv.conf`; do ping -qc 1 $ns; done
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.

--- 192.168.1.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 10.911/10.911/10.911/0.000 ms
PING 192.168.1.2 (192.168.1.2) 56(84) bytes of data.

--- 192.168.1.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.241/0.241/0.241/0.000 ms

So I know that my nameservers are reachable, meaning that some nameserver along the delegation path to the authoritative nameserver for my host is not responding. Is there an easy way to determine which nameserver this is (basically a traceroute for DNS)?
Answer: Does this do the job for you?
dig +trace google.com

From the man page:

+[no]trace
         Toggle tracing of the delegation path from the root name
  servers for the name being looked up.
  Tracing is disabled by default. When
  tracing is enabled, dig makes
  iterative queries to resolve
         the name being looked up. It will follow referrals from the root
  servers, showing the answer from each
  server that was used to resolve the
  lookup.
Comment: That works a charm!
Comment: https://www.digwebinterface.com/ is really useful for this
Answer: For Windows you can trace your dns query with
nslookup -debug google.at

You can also trace it online (of couse from another host) on http://www.simpledns.com/lookup-dg.aspx
Comment: This does not do the same as "dig +trace google.com" in a Linux or macOS system. It still does a recursive query to your local DNS instead of querying directly every nameserver in the trace.
Comment: This does not give the full details that I was looking for.  I have my router set to use Google's DNS and I was trying to confirm that it is actually doing that and not using my ISPs DNS.  If I perfrom an `nslookup` from the command prompt it tells me that the answer to my lookup came from 192.168.1.1, it's leaving out the intermediate steps.  A `dig` from my linux box provides more detail, including showing 18.104.22.168 in the chain.  Is there a way to do this via Windows?
Comment: `nslookup` just like `dig` works also under Mac OS X terminal.


Apply function over nested list of dataframes in r

Question: Apologies if this has been asked before - I've found a few answers related to applying functions over nested lists, but haven't managed to find one I can apply to my specific case.
I have a list containing two lists of dataframes:
set.seed(1)

df1 <- data.frame(x = rnorm(10), y = rnorm(10))
df2 <- data.frame(x = rnorm(10), y = rnorm(10))
df3 <- data.frame(x = rnorm(10), y = rnorm(10))

df4 <- data.frame(x = rnorm(20), y = rnorm(20))
df5 <- data.frame(x = rnorm(20), y = rnorm(20))
df6 <- data.frame(x = rnorm(20), y = rnorm(20))

lista <- list(df1, df2, df3)
listb <- list(df4, df5, df6)

list <- list(lista, listb)

I'd like to apply something like the following function over the two lists of dataframes:
f <- function (constant1, constant2, dfa, dfb){
  (constant1 * (sum(dfa$x) + sum(dfa$y))) + (constant2 * (sum(dfb$x) + sum(dfb$y)))
}

So, for the list defined above, the function would use dfa = df1 and dfb = df4 in the first iteration. For the second iteration, these would become dfa = df2 and dfb = df5, and so-on.
With both constants set as 1, the output should be a list containing three items:
> output
[[1]]
[1] 8.242232

[[2]]
[1] -2.19834

[[3]]
[1] 4.330664

I'm guessing I need mapply to do this, but can't work out how to call the dataframes.
Among many other attempts, I tried the following (which throws the error $ operator is invalid for atomic vectors):
output <- mapply(function(a, b, c, d) f(constant1 = a, constant2 = b, dfa = c, dfb = d),
                 a = 1, b = 1, c = list[[1]][[1]], d = list[[2]][[1]])

Answer: You can use mapply like this :
mapply(function(a, b) f(constant1 = 1, constant2 = 1, dfa = a, dfb = b),
                      list[[1]], list[[2]])
#[1]  8.242232 -2.198340  4.330664

Or perhaps better :
mapply(f, list[[1]], list[[2]], MoreArgs = list(constant1 = 1, constant2 = 1))

Answer: a tidyverse solution
library(tidyverse)

foo <- function(x, constant1, constant2){
  x %>%
  bind_rows(.id = "gr") %>%
  group_by(gr) %>%
  summarise(res= sum(x,y)) %>%
  mutate(gr1 = rep(1:(n()/2), n()/(n()/2))) %>%
  group_by(gr1) %>%
  summarise(res=sum(res[1]*constant1,res[2]*constant2)) %>%
  pull(res)}

foo(list, constant1 = 1, constant2 = 1)
[1]  8.242232 -2.198340  4.330664


Multichoosing (Stars and bars)

Question: Suppose we have 'n' Stars and 'k' bins. We have to distribute 'n' stars in 'k' bins (using k-1 bars) such that bins can be empty. We can do this in $\binom {n+k-1}{k-1}$ = $\binom {n+k-1}{n}$ ways. But Sometimes we use another notation $\left({{k}\choose {n}}\right)$ to represent $\binom {n+k-1}{k-1}$, Which says 'k multichoose n'. But normally as n > k, then how can we choose more objects from less objects i.e. n from k. So, I think It has to be like this $\left({{n}\choose {k}}\right)$.
Comment: In the event that others come to read this problem in the future, I recommend typesetting the multichoose function as `$\left(\!\!\binom{n}{r}\!\!\right)$` to display $\left(\!\!\binom{n}{r}\!\!\right)$, increasing or reducing the number of `\!` used depending on fontsize.
Comment: There is no strict rule that $n$ must be greater than $k$ in every combinatorial setting, though I would say it's conventional.
Answer: The notation $\left( \! \binom{k}{n} \! \right)$ stands for the number of multisets of size $n$ on $k$ symbols.  The important thing to note is that the $k$ symbols are distinguishable and the $n$ "positions" in the multiset are indistinguishable (order doesn't matter).
This suggests a bijection (one-to-one correspondence) with the number of ways to put balls (indistinguishable objects) in labeled boxes (distinguishable objects).  Specifically, the $k$ symbols in the multiset correspond to the boxes, and the $n$ positions in the multiset correspond to the balls.
Therefore,
$$
\left( \! \binom{k}{n} \! \right) = \binom{n + k - 1}{k - 1} = \binom{n + k - 1}{n}.
$$
The only restrictions on the integers $k$ and $n$ are
$$
n \ge 0 \quad \text{and} \quad k \ge 1.
$$
In particular, it doesn't matter which is greater.
Comment: $k$ represents the number of choices we have when we first put a star in a bin--and also every time we put another star in a bin thereafter. The number $n$ is the number of times we choose something. It's actually very compatible conceptually with the binomial notation. The difference is that the binomial notation assumes the number of choices shrinks by one each time, but here it does not.
Comment: Can you explain it $\left(\! \binom{k}{n} \! \right)$ in words. I didnt understand it from your above explanation. Here '**k**' represents number of bins and '**n**' represents number of stars.
Answer: The normal notation $n\choose{k}$ is read aloud as
"n choose k" because it is the number of ways to construct a set of k objects by choosing them from a set of n objects. The key thing to note her is that you are choosing without repetition. Once an object has been chosen, there are less objects to choose from.
The notation $\left( k \choose n\right)$ is read aloud as "k multichoose n" because it is the number of ways to choose a set of n objects by choosing them from a set of k objects, but this time you are allowed to choose as many of each object as you like. So if you like, you write down what you chose and then you put the object back, so there are always the same number of objects to choose from. Alternatively, you can think that there are a large collection of objects that come in k types. Thus k can be smaller than n because you just choose some of the same objects you already chose to make up the extra. Indeed, even if k was 1, you could still choose n of the same object and it would work.
The reason the k is at the top is because of how it relates to the "stars and bars". Remember that the stars and bars are really a description of the instructions for making your combination. You have n stars and k bins. You imagine your k bins in a row, and you start at the leftmost bin. In the "stars and bars" notation, the star tells you to put another star in the bin you're up to, and the bar tells you to switch to a new bin.
Now think about choosing n objects out of k when you can choose objects multiple times. Number your k objects from 1 to k and start out thinking about object 1. Now the stars tell you to pull out another of the same object, and the bars tell you to start looking for a new type of object.
Answer: "How can we choose more objects from less objects i.e. $n$ from $k$" (when $n > k$)?
It is very easy. We do not "use up" one of the $k$ objects when we choose it.
We can choose the same object again as many times as we like (just as we can put
many stars in the same bin).
You have a pile of $n$ stars. One at a time, you pick up a star, choose a bin (from a set of $k$ bins), and put the star in it. Then you repeat the process (choosing from the same set of $k$ bins every time) until all stars are in bins.
Now you have made $n$ selections from an initial set of $k$ choices. And you can keep on making as many more selections as you want from the same set.

Note that using the stars-and-bars argument, you can conclude that
$$
\left( \! \binom{k}{n} \! \right) = \binom{n + k - 1}{k - 1}.
$$
The right side has a $k$ on the bottom and an $n$ on the top, sure enough. But it also has a $k$ on top. So the right side already looks a little like the left side, though not very much.
But you could just as easily use stars-and-bars to say that
$$
\left( \! \binom{k}{n} \! \right) = \binom{k + n - 1}{n}.
$$
Now that looks much more compatible. Both the left and right side have a $k$ on top and an $n$ on the bottom, showing that the notations are not so very contradictory after all.
The top part of the right-side notation is just a little larger than the top of the left side, namely it is greater by $n - 1$.

Multichoosing (Stars and bars)


Specific set contained in product-sigma-algebra of Lebesgue and Borel sigma algebra

Question: The following lines are from a proof in my stochastic analysis lecture notes:
Let $(\Omega, \mathcal{F}) = ([0,1], \mathcal{L})$ where $\mathcal{L}$ denotes the $\sigma$-algebra of Lebesgue sets in $[0,1]$.
Define $A \subset [0, \infty) \times \Omega$ by $A = \{(x, x): x \in [0, 0.5]\}$.
Then $A \in \mathcal{B}[0, \infty) \otimes \mathcal{F}$.
I'm struggling to prove this. The product sigma algebra is generated by the inverse image of the projection maps, therefore it's generated by sets $B \subset [0, \infty) \times \Omega)$ of the form $B = \{(t, \omega) \in [0, \infty) \times \Omega): t \in  B, \omega \in F  \}$ for some $B \in \mathcal{B}[0, \infty), F \in \mathcal{F}$.
I don't see now how $A$ can be expressed as a sequence of countable intersections, unions and complements of sets $B$ since $A$ doesn't have a rectangle-like form and consists of uncountable many singletons.
Answer: Hint: consider the set $A_n$ which is a union of $n$ squares arranged along the diagonal.  Show that $A$ is the countable intersection of the sets $A_n$.
Answer: Let $A_n = \bigcup_{k=0}^{n-1} \left[\frac{k}{n}, \frac{k+1}{n}\right) \times \left[\frac{k}{n}, \frac{k+1}{n}\right) \cup \{ 0.5,0.5\}$.
Claim: $$\bigcap_{n=1}^{\infty} A_n = A$$
Proof:
"$\supseteq$": Let $x \in [0, 0.5)$ and $n \in \mathbb{N}$ be arbitrary. Divide $[0,0.5]$ into $n$ intervals of equal length. $x$ must lie in one of those intervals, say the $k$-th interval (i.e. $\left[ k/n, (k+1)/n \right)$). Therefore $\{x, x\}$ must be in $\left[ k/n, (k+1)/n \right) \times \left[ k/n, (k+1)/n \right)$ which by definition is a subset of $A_n$.
The proof for the case $x = 0.5$ follows by definition.
"$\subseteq$": Let $x \notin A$. This means that $d(x, A) > c$ for some $c > 0$ where $d$ is the distance w.r.t. the maximum norm in $\mathbb{R}^2$. By definition of $A_n$ we see that for each point $a \in A_n$ we must have $d(A,a) \leq \frac{1}{2}n$ for each $n$. This expression gets arbitrarily small for $n \to \infty$ and therefore there must exist some $n \in \mathbb{N}$ such that $x$ isn't in $A_n$ which completes the proof.


React Native : Aligning images side by side on one line with a dynamic number of images

Question: I am new to react native and I am trying to implement this view :
The view I try to implement
The first difficulty I encounter is to show the little green circles side by side.
The second comes from the fact that the number of little green circles is not constant... This number comes from my API. I would like to show from 2 to 6 little green circles depending on the number sent by my API (note that I know how to retrieve this information from my API, my problem is how to implement the View).
Thank you very much for you help...
Comment: well, show us the code so.
Comment: {greenCirclesArray.map( unneededItem => } is one solution. Could also use a FlatList, have a function instead of the map that uses a for loop to push all the  components into an array and then just have that array between the {}, etc. What have you tried and what isn't working?
Comment: Hi @HBSKan Thanks so much for your help. I realize now that it was not so difficult... But you know was it is to start in a new language... Sometimes we look too far and we forget the basics! I warmly thank you for your rapid and accurate answer.
Comment: No worries. Good luck!
Answer: As suggested by @HBSKan, the answer is:
<code><View style={{flexDirection: "row"}}>{this.state.InfoFromApi.logo_tab.map( elem =>
  <Image key={elem.type} style = {styles.logo} source={require('../assets/green_circles.png')} />
)}</View>
</code>
Thanks to him!


Model create using dictionary in django

Question: In Django is it possible to create through dictionary similar as to filtering?
Here is my models.py:
class Personnels(models.Model):
    name = models.CharField(max_length=100)

Here is my views.py:
from . models import *

def artists(request):
    personnels = Personnels.objects.all()

    if request.method == "POST":
            data = {"name": "Dean Armada"}
            Personnels.objects.create(data)

However the code above will throw an error. What I really am trying to do is to do a create function coming from a "request.POST" but my views above serves as a simple example on doing it
Comment: `Personnels.objects.create(**data)`
Comment: Crap I forgot about the two asterisk! Thanks!
Comment: Possible duplicate of [Can a dictionary be passed to django models on create?](http://stackoverflow.com/questions/1571570/can-a-dictionary-be-passed-to-django-models-on-create)
Answer: Simply unwrap the dictionary within create function like:
Personnels.objects.create(**data)

Comment: i am facing the problem when i used this due to presence of a foreign key https://stackoverflow.com/questions/69349618/trying-to-save-dict-in-my-model-but-getting-error-due-to-foreign-key/69355144#69355144

Model create using dictionary in django


How to get an element at a specific index in an ObservableCollection

Question: I am trying to make a tabbed browser code sample, but I am having trouble implmeneting the solution correctly. I have created a custom class BrowserItem which has two values, my custom web browser and a url string. I then created an ObservableCollection of type BrowserItem, in which I add new items to the ObservableCollection on a click event. For some reason though, when I call my ShowTab method in my MainPage to show the web browser instance that the user selects (from a ListBox populated by the ObservableCollection), I am getting an ArgumentOutOfRange exception. To illustrate, what I have so far is as follows:
BrowserItem.cs
public FullWebBrowser browser
    {
        get;
        set;
    }

    public string url
    {
        get;
        set;
    }

Settings.cs
public static Setting<ObservableCollection<BrowserItem>> Browsers = new Setting<ObservableCollection<BrowserItem>>("Browsers", new ObservableCollection<BrowserItem>());

Where the Setting class above saves and gets the ObservableCollection from isolated storage.
MainPage.xaml.cs
private void ShowTab(int index)
    {
        this.currentIndex = index;
        //Settings.Browsers.Value.ElementAt(currentIndex);  //ArgumentOutOfRange exception
        int count = Settings.Browsers.Value.Count;

        if (count <= 0)
        {
            FullWebBrowser browser = new FullWebBrowser();
            browser.InitialUri = "http://www.bing.com";

            BrowserItem Browser = new BrowserItem();
            Browser.browser = browser;
            Browser.url = browser.InitialUri;
            Settings.Browsers.Value.Add(Browser);
            BrowserHost.Children.Add(Browser.browser);
        }

        //SearchBar.Text = Settings.Browsers.Value.ElementAt(currentIndex).url ?? "";

        if (Settings.Browsers.Value.ElementAt(currentIndex) == null)  //ArgumentOutOfRangeException
        {
            FullWebBrowser browser = new FullWebBrowser();
            browser.InitialUri = "http://www.bing.com";

            BrowserItem Browser = new BrowserItem();
            Browser.browser = browser;
            Browser.url = browser.InitialUri;
            Settings.Browsers.Value.Add(Browser);
            BrowserHost.Children.Add(Browser.browser);
        }

        for (int i = 0; i < Settings.Browsers.Value.Count; i++)
        {
            if (Settings.Browsers.Value.ElementAt(i) != null)
            {
                Settings.Browsers.Value.ElementAt(i).browser.Visibility = i == this.currentIndex ? Visibility.Visible : Visibility.Collapsed;
            }
        }
    }

The ArgumentOutOfRangeException first occurs on Settings.Browsers.Value.ElementAt(currentIndex); in the ShowTab method, and everywhere else containing the same statement. I would just like to show the webbrowser of the corresponding index value in the ObservableCollection in MainPage.
Comment: have you checked the value of the index passed and the size of the collection?
Comment: You must accept previously answered questions which can help other audience who are searching for similar issues.
Comment: Yes, I just noticed that the collection was not being populated when initialized, so I adjusted my solution above. However, I still receive an ArguementOutOfRange exception when checking to see if a certain index is null in ShowTab on line `if (Settings.Browsers.Value.ElementAt(currentIndex) == null)`. The user is allowed to add an item on a click event in another page, and I pass in the newly created index value of the collection to my MainPage, and from there I must check to see if that index value contains a BrowserItem, and if not add one.
Answer: You need to add items to the collection somehow from somewhere. There should be some code like
 Settings.Browsers.Value.Add(browserItemInstanceHere);

OR
 Settings.Browsers.Value = getSomeBrowserCollections();

You cannot get item from an empty collection and you index must not be greater than Count-1
Comment: You can't unless you put null there. E.g. `for(int i=0;i<5;i++) values.Add(null);` By that you initialized every location to null. But that doesn't make sense. If you didn't add anything object to that location, it doesn't exist. The `Add` method is incremental, starts at 0,1,2... as you call it. It can't jump a location.
Comment: Ok I just edited my solution regarding the `ShowTab` method, to first check to see if the collection is empty, and if so add a new item. That works. Afterwards, however, if the user wishes to add a new BrowserItem to the collection from another page, I want to check to see if the collection's respective index is null, and if so I must add another BrowserItem to it and then show this to the user. On line `if (Settings.Browsers.Value.ElementAt(currentIndex) == null)` how can I change this to check to see if the collection is null here (I still get the ArgumentOutOfRange exception)?
Comment: the code to add item and to show tab needs to be different. Show tab should only Show the requested tab. If the index is not in the collection just ignore and exit the function. `if(index > count || index < 0) return;`
Comment: Also, the list from which users select from should be fed from your collection so that the number of items is the same as size of your collection. this way the user will not select an index not in the collection.
Comment: Ok that makes sense, I will try to change my solution when I can. I do still have a question about how to check to see if a certain index value in the ObservableCollection is null though?
Comment: OK thanks for your advice. I wasn't sure because I first used an array in which I checked to see if the index was null, then changed this to an ObservableCollection which is why I was still checking the index for a null value.
Comment: Yes array has fixed size so they have default values but collection tends to have the size of added items. So by default no items are added and the size = 0.


Como criar um botão arredondado no Xamarin.Forms

Question: Eu estou precisando criar um botão arredondado no Xamarin.Forms parecido com aquele principal do material design, mas sem perder as propriedades de um botão convencional e sem perder a característica de todas as plataformas do xamarin.forms. Gostaria de usar a melhor prática para fazer isso, sem usar gambiarras com imagens etc. Obrigado pessoal!
Edit1: Esqueci de comentar que estou usando o FormsAppCompatActivity para habilitar o material design no Android
Answer: Você pode usar a propriedade BorderRadius para criar um botão com os cantos arredondados:
Seguindo a propria documentação do Xamarin:
<Button Text="BlueButton"
        BorderColor="Blue"
        BorderRadius = "5"
        BorderWidth = "2"/>

Caso esteja tendo problemas para o botão arredondado no Android da pra você fazer
um render customizado.
[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace AppCompatRender.Droid
{
    public class CustomButtonRenderer : Xamarin.Forms.Platform.Android.AppCompat.ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);
            if (e.OldElement == null)
            {
                Control.SetBackgroundResource(Resource.Drawable.CustomButtonBackground);
            }
        }
    }
}

Adicione um novo Resources/Drawable que tenha o mesmo nome que você está usando no seu SetBackgroundResource por ex. CustomButtonBackground.axml, dessa forma difinindo os cantos do retangulo como 10dp:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
    <corners android:radius="10dp" />
</shape>

Obs: Fiz a tradução dessa resposta do SOEng
Comment: Tentei utilizar essa propriedade mas ela não surge efeito algum no meu botão. Tentei diversos valores, tirei outras propriedades para ver se alguma podia influenciar a outra, mas não.
Comment: nao esta funcionando apenas no Android, ou em todos?
Comment: Apenas no Android por conta do FormsAppCompact, eu vi essa resposta também, só que como eu chamo esse botão no Xamarin.Forms? Se responder essa eu coloco como resolvido. Obrigado pela ajuda


GNU less: How can I search while ignoring case sensitivity without using less -I option?

Question: From GNU less manpage

-i or --ignore-case
Causes searches to ignore case; that is, uppercase and lowercase are considered identical.
This option is ignored if any uppercase letters appear in the search pattern; in other words, if a pattern contains uppercase letters, then that search does not ignore case.
-I or --IGNORE-CASE
Like -i, but searches ignore case even if the pattern contains uppercase letters.

This is a great way of searching in GNU less, while ignoring case sensitivity. However, you must know in advance that you'd like to search while ignoring case sensitivity and indicate it in the command line.
vim solves this problem by letting the user specify \c before a search, to indicate that the pattern should be searched while ignoring case sensitivity.
Is there a way to do the same in less (without specifying -I in the command line)?
Comment: You can set the LESS environment variable to "-I" and each time you run less it will get the -I option
Answer: You can set it from within less by typing -i and then doing the normal search procedure.
Have a look in the help for less by pressing h
Comment: FYI, if you add any capital letters to your search, it will run a case-sensitive search even with Ignore Case enabled.
Comment: Thanks :) I was looking only at the man page, and forgot to look at the inline help. This is exactly what I was looking for.
Answer: After turning on Ignore case in searches by pressing -i you'll have to supply a lower case search pattern to perform a case insensitive search. If the search pattern has upper case characters the search will still be case sensitive.


How can you find $\int_0^8xf'(x)\,{\rm d}x$ when $f(8) = 9$ and $f(4+x) = -f(4-x)$?

Question: This is the actual question:
If $f: \mathbb R \to \mathbb R$ is a continuous differientable function and given that $f(8) = 9$ and $f(4+x) = -f(4-x)$, what is $\int_0^8xf'(x)$d$x$?
This is what I have thus far:
If $f(8) = 9$ and $f(4+x) = -f(4-x)$, then $-f(0) = 9 \Rightarrow f(0) = -9$.
Say $u = x$ and d$v = f'(x)$d$x$, then d$u = $d$x$ and $v=f(x)$.
So    $\int_0^8xf'(x)$d$x = \int_0^8u$d$v = uv|^8_0 - \int^8_0v$d$u. = (8\cdot9 - 0\cdot9) - F(x)|^8_0 = 72 - F(x)|^8_0$ (not sure if this is a correct notation). Since I don't know what $f$ is, I obviously don't know its integral either. What other way can I use to find the solution?
Thanks in advance.
Comment: To solve it use integration by parts: $\int_0^8 xf'(x){\rm d}x = [xf(x)]_0^8 - \int_0^8 f(x){\rm d}x$ and try to use the $f(x+4) = -f(x-4)$ property to deduce the value of the last integral ($f$ is odd about $x=4$)
Comment: I changed the title as it was not the same as the question body. The answer to the title as it was before is simply you can't. There is not enough information in just knowing $f(a)$ and $f(b)$ to be able to evaluate $\int_a^b xf'(x){\rm d}x$.
Comment: @Winther I see it now. The surface area between the $x$ axis and the function line between $0$ and $4$ is the opposite of the one between $4$ and $8$. Thank you!
Answer: The function $f$ is odd with respect to the point $x=4$. We therefore replace $f$ with
$$g(x):=f(4+x)\ .$$
Then $$g(-x)= -g(x),\quad g(4)=9,\quad f(x)=g(x-4),\quad f'(x)=g'(x-4)\ .$$
It follows that
$$J:=\int_0^8 x f'(x)\>dx=\int_0^8 x g'(x-4)\>dx\ ,$$
and substituting $x:=4+t$ $(-4\leq t\leq 4)$ gives
$$J=\int_{-4}^4 (4+t) g'(t)\>dt=4\bigl(g(4)-g(-4)\bigr)+\int_{-4}^4 tg'(t)\>dt=72+0=72\ ,$$
since  $g$ is odd and $g'$ is even.
Answer: HINT.-$$\int_0^8 xf'(x){\rm d}x =\int_0^8 xd(f(x)= [xf(x)]_0^8 - \int_0^8 f(x){\rm d}x\\\int_0^8 xf'(x){\rm d}x=72-\int_0^8 f(x){\rm d}x$$ Now calculation gives $f(4)=0$ and because of $f(4+x) = -f(4-x)$ the function can be considered as being odd respect to the new origin $x=4$.
A realization of such a function is the straight line $$f(x)=9(\frac x4-1)$$ In this case we have $$\int_0^8 xf'(x){\rm d}x=72-\int_0^89(\frac x4-1)dx=72$$
It seems it could be other realizations of $f(x)$ according to the fact that $f$ odd respect of $x=4$ but always the answer will be $72$.
Answer: Solution
Notice that $$\int_0^8xf'(x)\,{\rm d}x=\int_0^8x\,{\rm d}f(x)=xf(x)\bigg|_0^8-\int_0^8 f(x)\,{\rm d}x,$$
where$$xf(x)\bigg|_0^8=8f(8)-0f(0)=72,$$
and
\begin{align*}
\int_0^8 f(x)\,{\rm d}x&=\int_0^4 f(x)\,{\rm d}x+\int_4^8 f(x)\,{\rm d}x\\
&=\int_0^4 f(x)\,{\rm d}x+\int_{-4}^0 f(x+8)\,{\rm d}x\\
&=\int_0^4 f(x)\,{\rm d}x-\int_{-4}^0 f(-x)\,{\rm d}x\\
&=\int_0^4 f(x)\,{\rm d}x+\int_{4}^0 f(x)\,{\rm d}x\\
&=0.
\end{align*}
where we apply the fact $f(x+8)=-f(-x)$ and a series of variable substitution.
As a result,$$\int_0^8xf'(x)\,{\rm d}x=72-0=72.$$


Existe "Require once" em Javascript/Jquery

Question: Fiz uma classe em JS (Modelo ES6), ta funcionando beleza, mas como eu faço pra colocar ela num arquivo externo e dar, um Require Once como no PHP? Tem como fazer isso? Valeu ;)
Answer: Isso depende do seu ambiente, se você for utilizar usando jQuery no webbrowser (para um site, por exemplo), você pode dar uma olhada nos plugins como browserify que fazem mais ou menos o modelo do require do NodeJS.
Se você estiver utilizando o ambiente do Node, então basta usar o próprio require, mas não acredito que haja um require_once, até porque os objetos são armazenados em variáveis, eles não são incorporados ao ambiente.


Segue won't perform when activated without a button xcode Swift 2

Question: I'm trying to make an IOS application and checking whether the user has logged in or not. When a user is not logged in, it should display a login form. Ive created multiple View Controllers and connected them with segue's. Than I used self.performSegueWithIdentifier("userLoggedOff", sender: self) to activate the segue. But the error EXC_BAD_ACCESS appears.
However, when I try to activate the same segue with the same code linked to a button, it all works. Really frustrating... Thnx for your help.
This is the full code. I used JSON to get the user's account info. It's probably not the way to do it, but i'm a beginner in xcode, swift and app-making in general.
import UIKit
import WebKit

class StartController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        checkLoginStatus_main()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func checkLoginStatus_main(){
        let requestURL: NSURL = NSURL(string: "https://www.example.net/account/accountinfo.php")!
        let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithRequest(urlRequest) {
            (data, response, error) -> Void in

            let httpResponse = response as! NSHTTPURLResponse
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {

                do{

                    let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)

                    if let accounts = json["account"] as? [[String: AnyObject]] {

                        for account in accounts {

                            if let status = account["status"] as? String {

                                if let name = account["name"] as? String {
                                    if(status == "true"){
                                        print("LoggedIn") // THIS WORKS
                                        self.continueScanner()

                                    } else {
                                        print("LoggedOut") // THIS WORKS
                                        self.continueLoginForm()
                                    }
                                }

                            }
                        }

                    }

                }catch {
                    print("Error with Json: \(error)")
                }

            }

        }
        task.resume()
    }

    func continueLoginForm(){
        self.performSegueWithIdentifier("userLoggedOff", sender: self)
    }

    func continueScanner(){
        self.performSegueWithIdentifier("userLoggedIn", sender: self)
    }
}

This is the error:
Screenshot of the error
Here is the full output:
LoggedOut
1   0x18771c654 <redacted>
2   0x1834bcfe4 <redacted>
3   0x1834b1e50 _os_once
4   0x1834ba728 pthread_once
5   0x1886a6d98 <redacted>
6   0x1886a6680 WebKitInitialize
7   0x188c4bfa0 <redacted>
8   0x100791a3c _dispatch_client_callout
9   0x1007928b4 dispatch_once_f
10  0x182ebcfc8 <redacted>
11  0x182ec38b8 <redacted>
12  0x182ecdd78 <redacted>
13  0x188f9c130 <redacted>
14  0x188f9c2cc <redacted>
15  0x188f9be9c <redacted>
16  0x188ca9ff4 <redacted>
17  0x188f9c154 <redacted>
18  0x188f9be9c <redacted>
19  0x188e780a0 <redacted>
20  0x188f9c154 <redacted>
21  0x188f9c2cc <redacted>
22  0x188f9be9c <redacted>
23  0x188e773d4 <redacted>
24  0x188d19140 <redacted>
25  0x188addfcc <redacted>
26  0x1889a07ec <redacted>
27  0x1889a0744 <redacted>
28  0x18928f504 <redacted>
29  0x188cfcca0 <redacted>
30  0x188d22a04 <redacted>
31  0x188d257a0 <redacted>

Comment: You should go to Breakpoints panel and click little Plus button in the bottom. When the breakpoint is set, run your project as usual, this may give you a clue.

http://i.stack.imgur.com/BPe8N.png
Comment: Please post the full error.  There should be more than just `EXC_BAD_ACCESS`.
Comment: I added a screenshot
Comment: did you try to set Exception breakpoint?
Comment: @Lenny There should be an explanation in the Xcode console saying why you are getting the EXC_BAD_ACCESS. Look at that and add that information to your post.
Comment: @DrewC updated my post
Comment: @heximal where should is set the breakpoint?
Comment: You should try dispatching your `performSegueWithIdentifier` on the main thread - `dispatch_async(dispatch_get_main_queue(), { self.performSegue...`
Comment: Make sure your call to performSegueWithIdentifier is being made on the main thread. Have a look at http://stackoverflow.com/questions/26262398/uilabel-text-updated-inside-a-swift-closure-refuses-to-show for more info.
Comment: @Paulw11 clearly types faster than me :)
Comment: @Paulw11 It works, thank you! :) So if I understand it correctly, the code makes sure the segue is performed on the main thread?
Comment: Yes, that is right.  The network operation completes on a background thread and all UI updates must be on the main queue.
Answer: @Paulw11 has solved the problem in the comments on my post.
dispatch_async(dispatch_get_main_queue(), { self.performSegue...

Thanks for your help everyone!
Answer: I think you probably need to implement prepareForSegue
    override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
        if (segue.identifier == "userLoggedOff") {
            let vc = segue.destinationViewController as? LogInScreenViewController
        } else if (segue.identifier == "userLoggedIn") {
            let vc = segue.destinationViewController as? UserLoggedInViewController
//This should be the name of whatever view controller they go to if they are logged in.
    }
    }

Comment: it won't help. prepareForSegue method is optional in viewcontroller implementation.
Comment: Thank you for your answer! Unfortunately, it doesn't seem to slove the problem
Comment: This won't make any difference. All you're doing is needlessly loading the destination view controller into a variable you don't do anything with.


Check if liferay community is active or not

Question: I need check if the community is active or not through code. I am using Liferay 6.0.6 CE.
When I fetch myPlaces using List<Group> myPlaces = user.getMyPlaces(max); I get all the not active communities in the list as well which I don't want. I want only the active communities to be returned in the List.
Answer: Sometimes it is necessary to program a little bit self :)
    List<Group> myActivePlaces = new ArrayList<Group>();
    List<Group> myPlaces = user.getMySites();
    for (Group group : myPlaces) {
        if(group.isActive()){
            myActivePlaces.add(group);
        }
    }


String into array

Question: I have a string like:
     {
        "OperationResult": [
                 {
                   "CA::Read:PackageItems": {
                           "Read.PackageItem.RemoteBalanceAssigned": false,
                           "Read.PackageItem.CLSpvInfo": "1|-1#-9223372036854775000",
                           "PackageList":
                             [
                               "TopSim-4GSim1GBData",
                               "TopSim-ATBReactivation"
                             ],
                           "PackageTypeList":
                             [
                                "optional-unsubscribed", "optional-unsubscribed"
                             ],
                          "PackageFunctionalNameList":
                                [
                                  "FreeUnits",
                                  "AccumulationReward+MultipleThresholds"
                                ],
                          "PackageSubStateList":
                            [
                              "",
                              ""
                            ],
                          "PackageEligibilityList":
                          [
                            true,
                            true
                          ]
            }
        }]
    }

I am trying to get it into array. but I want filter this string and only put PackageList":["xxxx-yyy","zzz-zzz"]  and "PackageSubStateList":[TRUE,FALSE]}
Any thing in between should be filter out.
The resulted array should be like:
PackageList {
               name: xxxx-yyy,
               state: TRUE,
             }
               ....

Comment: Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php)
Comment: Why not just parse it and access the object props?
Comment: Is that an exact copy of the string? The `"optional-"optional-unsubscribed""` looks wrong and makes it pretty much un-parsable.
Comment: If you have tried using simple xml to parse it, that should have been included in the question along with the code you tried.
Comment: @Fshamri In this case, you should rethink about using this service or call their support and ask for help. If response is not in the form of XML, JSON etc, then parsing will be difficult and won't make sense.
Comment: that erm `string` looks like an object?
Comment: my web service returns response in raw test format. I couldn't parse it using simple xml
Comment: If this is your string, I saw some problem : 1/ `"optional-"optional-unsubscribed""` looks wrong for me, 2/ For me it missed `}]}` at the end to close the `{"OperationResult":[{` at the beginning
Answer: //The json posted in the question is invalid, assuming valid json gets used here afterwards:
$string = '{"OperationResult":[{"CA::Read:PackageItems":{"PackageList":["xxxx-yyy","zzz-zzz"],
"PackageTypeList":["optional-unsubscribed","optional-"optional-unsubscribed""],
"PackageFunctionalNameList":["FreeUnits","AccumulationReward+MultipleThresholds"],
"PackageSubStateList":[TRUE,FALSE]}';

$object = json_decode($string);
$wanted = $object['OperationResult']['CA::Read:PackageItems'];

$wanted should now contain what you need
Comment: Could be a copy-paste error, but what the OP has posted, is not valid json.
Comment: Yeah seems like he is missing some closures at the end, I assumed valid json for this one
Comment: seems I missed when pasted the string
Comment: I have used your code. it converts the string to json object but iam getting "Undefined index: CA::Read:PackageItem" error

String into array


Which hook can I use before or after submitting a webform form?

Question: I created a webform form with drupal 8.
I would like to populate a database table with information from my form before or after submitting.
I guess there must be a hook like hook_webform_pressave () or hook_webform_insert () but I have not found the solution.
Thank you for your help
Comment: Yes, if you can't find a webform specific solution like answered by @sonfd, the entity hooks you've mentioned should work. Submissions are stored in the entity `webform_submission`, so a hook would be named like this `mymodule_webform_submission_presave()`.
Answer: Take a look at the answer to Add a custom submission handler to a form. This will tell you how to add a submit handler to a form. You can use the same approach to add a custom submit handler to the webform and then perform the operations you want from the submit handler.


There is no ViewData item of type 'IEnumerable' that has the key 'Categorias'

Question: Estou com um problema com o dropdownlist. Eu populei ele com informações que estavam em meu DB.
Código da controller:
    public ActionResult NovoProduto()
    {
        ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
        return View();
    }

ele carrega na view tudo certo. Estou recebendo na view desta forma:
@Html.DropDownList("categorias", "selecione uma categoria")

só que quando eu faço uma ação, exemplo, cadastrar um novo produto, e tenho um return para a tela em que existe o dropdownlist ele dá erro.

"{"There is no ViewData item of type 'IEnumerable' that has the key 'Categorias'."}"

Só que não faço ideia do porquê do erro, pois não muda nada quando retorna: eu apenas adicionei algo em uma tabela que não tem nada a ver com a da lista.
Answer: Cada vez que se dá um return, você deve repopular sua ViewBag novamente.
Então, se você tem esse endpoint para abrir o form de "Produto Novo":
[HttpGet]
public ActionResult NovoProduto()
{
    ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
    return View();
}

Deve ter a mesma lógica após o POST do formulário:
[HttpPost]
public ActionResult NovoProduto(Produto produto)
{
    // Salva o produto ...

    // Popula a ViewBag novamente
    ViewBag.categorias = new SelectList(db.Categoria, "CategoriaId", "Nome");
    return View();
}