What is this notation used for the singer?

Question: Consider this excerpt from Te Deum Laudamus by C.V. Stanford:

What is the notation used on top of the voice?
I suppose the letters indicate the notes (d(o)-r(e)-m(i)-s(ol) for re-mi-fa#-la in D major), and the symbols relate to the rhythm?
Answer: This is the Tonic Sol-fa system developed by John Curwen (Wikipedia). His primer on the subject can be found at IMSLP.
colon (:) = weak rhythmic accent
vertical line (|) = strong rhythmic accent (beat 1 is preceded by the bar line)
dash (-) = held note
underline (_) = melisma
apostrophy (') = octave
A video explaining the system:
Comment: @Edward Take a look at the link to Curwen's book. That's where the 3/4 interpretation I used is specified. I doubt Curwen addressed 5/4 as it would have been extremely uncommon in the 19th century.
Comment: This video says that the short vertical line | divides the bar into two halves, like another source which I based my answer off of (which I lost track of, unfortunately).  This may just be true in the special case that we only care about 2- 3- and 4- beat bars, though.  No sources I found address how to notate 5/4 for example.  "*|* : | : :" would make sense to me (for a 2+3 feel), violating the rule that it divides the bar in half, and instead taking it to divide a bar at a strong pulse.
Comment: Ok, I think I found the passage of interest.  Curwen says that the upright bar appears "In the middle of measures which contain four or six beats...", so it's easy to see why these secondary sources say that the bar divides the measure in half.  It is technically true.  But Curwen also says the line expresses a subordinate accent, and I believe that is the real important part.
Answer: This is known as Tonic Sol-fa notation.  The notation indicates a key and then represents pitches as letters, much like the common solfege system.  The chromatic scale is as follows:
d de r re m f fe s se l le t
The sharps de, re, fe, se, and le are enharmonic to flats ra, ma, sa, la, and ta.
The single letters are all pitches diatonic to the major key, and they use the same letter as the first letter of the usual solfege (do re mi fa sol la ti).
As for rhythm, the bar is divided by the symbols

| : | :

Each symbol functions like a bar line, except they're really "beat lines" or "half beat lines" or maybe something else, depending on the time signature. The "|" is the first pulse in the measure (and also, a strong pulse), "|" is a strong pulse besides the measure start, and ":" indicates a weak pulse.  A period (.) divides a beat (or half beat, or...) in half. Underscores represent slurs/melisma.  The dash (—) represents that the last note is being held over this beat.
Comment: @BrianTHOMAS I suspect that the system assumes that one never encounters E sharp in the key of C without first modulating into some other key.  I further suspect that one would have to look long and hard to find an example where this assumption causes a problem.
Comment: @BrianTHOMAS from the link in this answer: "Chromatic alterations are marked by the following vowel, "e" for sharp (pronounced "ee") and "a" for flat (pronounced "aw")."  But note that the system descends from movable _do_, which I assume is why it's called "tonic," so F sharp is not the product of chromatic alteration in D major; it's just _m._
Comment: The chromatic scale example above uses naturals and sharps. How do you notate _flats_ in tonic sol fa?
Comment: i think this is good casue, because singers use it to kind of be in tune easier, you have to remember not auto in tune, so seeing A note is one thing but you got to sing the A note.
Comment: @phoog - What would the name of E# be in tonic solfa? (given that C is Do). When I tried this I got Mi for E natural and Mee for E# and Mi and Mee have the same vowel sound...


NodeJS - How do I increase the memory heap size?

Question: I want to increase the memory heap size, but every time I try to do that it fails. I tried to install the package npm i increase-memory-limit but it doesn't do anything. I did run the command increase-memory-limit after installing it, but I still get the same crashes as before.
Currently I'm writing my NodeJS code in the PyCharm IDE on a Windows 10, if that helps.
Edit:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory
 1: 00007FF686C0094F napi_wrap+124431
 2: 00007FF686BA2696 v8::base::CPU::has_sse+34502
 3: 00007FF686BA3356 v8::base::CPU::has_sse+37766
 4: 00007FF6873A6F4E v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF68738EF91 v8::SharedArrayBuffer::Externalize+833
 6: 00007FF68725C85C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1436
 7: 00007FF687258890 v8::internal::Heap::AddRetainedMap+2608
 8: 00007FF68727289E v8::internal::Factory::AllocateRawFixedArray+94
 9: 00007FF687279C34 v8::internal::Factory::NewFixedArrayWithFiller+52
10: 00007FF687279BF1 v8::internal::Factory::NewFixedArray+65
11: 00007FF68714A98F v8::internal::FeedbackNexus::ic_state+56767
12: 00007FF68715C6C5 v8::Message::GetIsolate+14101
13: 00007FF687168600 v8::Message::GetIsolate+63056
14: 00007FF68714438C v8::internal::FeedbackNexus::ic_state+30652
15: 00007FF68700E8AA v8::internal::OrderedHashMap::ValueAt+62122
16: 00007FF6877D2C6D v8::internal::SetupIsolateDelegate::SetupHeap+567949
17: 000002A6CAD8B865

Comment: Please explain how it fails and the steps you are performing to provoke the issue. You might be able to solve your problem using the max-old-space-size option for node. You might take a look at https://medium.com/@vuongtran/how-to-solve-process-out-of-memory-in-node-js-5f0de8f8464c
Comment: I've developed a script for a small company I'm working with and after handing out the exe file (made with npm nexe) to the research team, they've told me that the script can't run for too long because they get an error related to the question I've made. I've tested the script myself, but not for more than 10 or 20 minutes and I didn't know about this error and now I'm trying to figure out what to be done. Hopefully I've made myself more clear regarding my issue.
Comment: "As of Node.js v8.0 shipped August 2017, you can now use the NODE_OPTIONS environment variable to set the max_old_space_size globally" [**Check this post out:** https://stackoverflow.com/a/48895989/4200039](https://stackoverflow.com/a/48895989/4200039)
Comment: If you copy past the error into the question someone may be able to give you more specific help.
Comment: Sorry for the late reply. Anyway, I've just updated the post with the error.
Comment: @chipswithdrips I believe you might need to alter your way of using nexe. I am not too familiar with it myself, but you might need to add the --enableNodeCli flag (and the --build flag) during your build and then add e.g. --max_old_space_size=5000 when running the actual exe file. Take a look at the following for inspiration: https://github.com/nexe/nexe/issues/383
Answer: When starting node server, check script that is running
it should be something like node index.js or something like that.
Not so sure how it is in PyCharm when you run node
But what can help you is option --max-old-space-size
So, I would suggest to try with command like
node --max-old-space-size=8192 index.js


Does an unconditional probability of 1 or 0 imply a conditional probability of 1 or 0 if the condition is possible?

Question: I can't seem to find any references saying that an event with probability 1 or 0 is independent of any event with positive probability, if that's even true and can't seem to be able to extend the argument here soooo......
Suppose we have a probability space $(\Omega, \mathscr F, \mathbb P)$ and let A and B be events s.t. $P(B) > 0$.
If $P(A) = 1 (/0)$, then $A = \Omega(/\emptyset)$ a.s.
$\to A \cap B = \Omega(/\emptyset) \cap B \ \text{a.s.} \ \tag{*}$
$$\to P(A \cap B) = P(\Omega(/\emptyset) \cap B)$$
$$\to P(A \cap B) = P(B(/\emptyset))$$
$$\to P(A|B)P(B) = P(B(/\emptyset))$$
$$\to P(A|B) = 1(/0) \ QED$$
Is that right? What is the justification or alternative for $(*)$?
Comment: As @Dilip pointed out, $A = \Omega$ "a.s." isn't really what you mean.  Rather $\Omega \setminus A$ has probability zero..
Comment: @P.Windridge Well there's always using indicator functions?
Comment: You mean $\mathbb{P} ( \left\{\omega: \mathbb{1}_A( \omega ) = 1 \right\}) = 1$ ? :D  Or $\mathbb{1}_A = 1$ a.s. for short.  Well.. but.. here the LHS does actually *equal* the RHS for some realisations :)  It's a bit of dodge :)
Comment: @P.Windridge Added answer. How is it?
Answer: I almost surely do not know what is meant by a.s. in the equation
tagged with a $*$ in your question, but the proof of the independence
stuff is straightforward.
Given any event $B$, not necessarily of positive probability, we can
express it as the disjoint union of the events $A\cap B$ and
$A^c\cap B$, that is, $B =  (A\cap B) \cup (A^c\cap B)$.
Hence we have that
$$P(B) = P(A\cap B) + P(A^c\cap B).\tag{1}$$

If $P(A) = 1$ (i.e. $P(A^c) = 0$), then, since $A^c \cap B \subset A^c$,
we have  $P(A^c \cap B) \leq P(A^c) = 0$, that is,
$P(A^c \cap B) = 0$. It follows from $(1)$ and the assumption that
$P(A) = 1$ that
$$P(B) = P(A\cap B) \Longrightarrow P(A)P(B) = P(A\cap B),$$
that is, $A$ and $B$ are independent events.

If $P(A) = 0$ (i.e. $P(A^c) = 1$), then, since $A\cap B \subset A$,
we have that $P(A\cap B) \leq P(A) = 0$ and so
$$0 = P(A\cap B) = P(A)P(B),$$
that is, $A$ and $B$ are independent events.

Events of probability $1$ (or of probability $0$) have the
property that they are independent of all other events
including (somewhat surprisingly) themselves!
Comment: Brilliant: No indicator functions or almost sureness. Thanks Dilip Sarwate. If $P(B)=0$, does it still hold that $P(A|B)=1$? :O
Comment: Independence is probably independent (lol) of $P(B) > 0$ but to speak of conditional probabilities I think requires $P(B) > 0$. Added answer. How is it?
Answer: Prove $P(A|B) = 1$ if $P(A) = 1, P(B) > 0$:
$$P(A) = 1$$
$$\to 1_A = 1_\Omega \ \text{a.s.}$$
$$\to 1_A 1_B =1_\Omega 1_B \ \text{a.s.}$$
$$\to 1_{A \cap B} =1_B \ \text{a.s.}$$
$$\to P(A \cap B) = P(B)$$
$$\to P(A|B)P(B) = P(B)$$
$$\to P(A|B) = 1 \ QED$$
The last line assumes $P(B) > 0$.

Prove $P(A|B) = 0$ if $P(A) = 0, P(B) > 0$:
$$P(A) = 0$$
$$\to 1_A = 1_{\emptyset} \ \text{a.s.}$$
$$\to 1_A 1_B = 1_{\emptyset} 1_B \ \text{a.s.}$$
$$\to 1_{A \cap B} = 1_{\emptyset} \ \text{a.s.}$$
$$\to P(A \cap B) = P(\emptyset)$$
$$\to P(A|B)P(B) = 0$$
$$\to P(A|B) = 0 \ QED$$
Note: The last line assumes $P(B) > 0$.

Prove A and B are independent if $P(A) = 0$
$$A \cap B \subseteq A$$
$$\to 0 \le P(A \cap B) \le P(A) = 0$$
Also, $P(A)P(B) = 0$. Hence, we have
$$P(A \cap B) = P(A)P(B) \ QED$$
Note: This does not seem to assume that $P(B) > 0$

Prove A and B are independent if $P(A) = 1, P(B) > 0$
$$P(A \cap B) = P(A|B)P(B) = P(B) \tag{*}$$
$$P(A)P(B) = P(B)$$
$$\to P(A \cap B) = P(A)P(B) \ QED$$
Note: $(*)$ makes use of '$P(A|B) = 1$ if $P(A) = 1, P(B) > 0$'
Comment: In $P(A \cap B) = P(B|A)P(A) = 0$, $P(B\mid A)$ is undefined when $P(A)=0$.
Comment: $P(A\cap B) \leq P(A)$ since $(A\cap B) \subset A$. When $P(A)=0$, we have that $P(A\cap B)=0$ without the need for mentioning conditional probabilities at all: whether or not $P(B\mid A)$ is defined or not is irrelevant. When $P(A) = 0$, you cannot write $P(A\cap B) = P(B\mid A)P(A)$ without implying that $P(B\mid A)$ is defined and has finite value.
Comment: I don't care what de Finetti says or said; your (now-deleted) assertion that $P(A\cap B)= P(B\mid A)P(A)$ does not make sense when $P(A)=0$ since $P(B\mid A)$ is undefined when $P(A) = 0$. Your _current_ assertion that $P(A\cap B) = 0$ needs _just a little_ justification as to why it is so: what you need to say is that $(A\cap B) \subset A$ and so $P(A) =0$ implies that $P(A\cap B)=0$. Just a bald statement that $P(A\cap B) = 0$ (because you need it to be $0$) raises doubts as to whether you really understand what is going on, or you are just using proof by authority: e.g. de Finetti says so.
Comment: @DilipSarwate 1 [Is it](http://math.stackexchange.com/a/1494801/140308)? 2 So $P(A \cap B)$ is undefined when $P(A) = 0$? Afaik $P(A \cap B) = P(B|A)P(A)$. Is is that $P(A \cap B) = P(B|A)P(A)$ for $P(A) > 0$ and 0 if $P(A) = 0$?
Comment: @DilipSarwate 3 Ah so do you mean that in the first place $P(A|B)$ is meaningnless if $P(B) > 0$? 4 [This](https://en.wikipedia.org/wiki/Conditional_probability#As_an_axiom_of_probability) doesn't seem to assume $P(B) > 0$
Comment: @DilipSarwate Edited. I guess you disagree with de Finetti. Thanks ^-^
Comment: Okay I guess you disagree with [DirkGently](http://math.stackexchange.com/questions/1494682/is-it-correct-to-say-that-pa-1-to-pab-1-pa-1-to-pab-pa/1494801#1494801). Thanks @DilipSarwate. Going to edit


Is finding a good multilayer perceptron (MLP) model just luck?

Question: I am trying to build a MLP model for a classification task. I am using Tensorflow in Python for building a DNN model, there are a lot of parameters. At least, how many hidden layers and how many neurons per each layer is a tough question.
I tried with different combination of hidden layers, and each of them give a different result. I just try and try and try again ...
It seems to me that, if the process stops and I can find a good model, it is just luck. For instance, if I stop with the hidden layers as [100,1000,2000,5], I mean, I just find that after many times of trial.
Is it true? Is there a way to build a MLP model for a particular dataset?
P/S: Now, I understand that MLP with multi hidden layers is deep neural network and belongs to deep learning. Is it true?
Answer: Yes it has been observed that deep MLPs can be tricky to optimize. In fact they suffer from a diminishing returns with added complexity, see Big Neural Networks Waste Capacity by Yoshua Bengio and Yann Dauphin.
MLPs do belong to deep learning models as they stack layers of neurons together with nonlinear activation functions.
MLPs are universal function approximators, but as you mentioned that doesn't mean it's easy to find a good parameterization of an MLP via optimization. Perhaps we haven't found the appropriate optimization method as it seems that most people predominantly use variants of minibatch stochastic gradient descent due to their nice scaling properties as well as their stochastic-ness which might help us "jitter" our way out of some local minimas during training. However for larger capacity MLPs, these are dense, fully connected models and perhaps there's lots of 2nd order interactions between the units which leads to poor conditioning of our optimization problem and can lead to some finicky results, precisely the kind you are observing. Bengio and Dauphin discuss this in the above paper that I linked.
What type of data are you training on? If it's image data it's highly recommended you use a convolutional neural network. The convolutional layers offers all sorts of benefits over vanilla MLPs. It is hypothesized that the sparsity helps the network learn stronger, discriminative features and in general that the use of convolutional layers itself is a strong prior for image data.
For language modeling people seem to have some success using the Word2Vec embeddings. See one of the original innovative articles back from 2003 A Neural Probabilistic Language Model and some of the more recent work by Mikolov, Sutskever and others on word embedding and recurrent neural networks, see Distributed Representations of Words and Phrases
and their Compositionality.


Regra no model para formatar data

Question: Estou com duas regras em dois campos.
No campo data_despesa, quero pegar do formato d/m/a e passar para a-m-d. Acontece que quando salva no banco, fica como 0000-00-00. Não sei debugar no model para ver como está transformando e no controller, quando debugo o $this->request->data) não pega com a validação.
O campo valor_despesa está ok. Está trocando a "," por ".". O problema é somente na formatação de data_despesa.
O que há de errado?
Segue o código do model:
<?php

class Despesa extends AppModel {

    public $name='despesa';
    public $useTable='despesas';
    public $primaryKey='id_despesa';

    public $validate=array(
'data_despesa'=>array(
    'data'=>array(
'rule'=>array('data'))),

'valor_despesa'=>array(
'preco'=>array(
'rule'=>array('preco'))));

    public function data($check) {
        $dataDespesa=explode("/", $check['data_despesa']);

        $dataDaDespesa="";

        $dataDaDespesa=$dataDespesa[2]."-".$dataDespesa[1]."-".$dataDespesa[0];

        return true;
    }

    public function preco($check) {
        $valorDespesa=str_replace(",", ".", $check['valor_despesa']);

        return true;
    }

}
?>

Comment: Se usar `<code>` para formatar a pergunta, o prettify do site não funciona: http://pt.stackoverflow.com/editing-help
Comment: o campo `data_despesa` está com o tipo `date` no Banco de Dados? Se sim, o formato `yyyy-MM-dd` é o formato padrão dos campos tipo 'date'. O que você pode fazer é modelar este valor para mostrar na tela, mas os campos de data sempre salvarão neste formato no Banco de Dados. Se fosse possível salvar de qualquer maneira, o Banco de Dados teria problemas para comparar duas datas.
Comment: @DennnE
 o que eu quero é mudar de d/m/a para y-m-d eu consegui no controller, mas no model, não consigo. Estava uma gambiarra essa validação no controller, por isso quero implementar no model.
Answer: Para mudar o formatado da data de um objeto DateTime que provavelmente o cake usa, use o método format().
Mude:
public function data($check) {
    $dataDespesa=explode("/", $check['data_despesa']);
    $dataDaDespesa="";
    $dataDaDespesa=$dataDespesa[2]."-".$dataDespesa[1]."-".$dataDespesa[0];
    return true;
}

para:
public function data($check) {
    $dataDespesa = $check['data_despesa']->format('Y-m-d');
    return true;
}

Não conheço o cake, talvez seja necessário mudar o return true para  return $dataDespesa.
Como formatar valores monetários no PHP veja essa resposta

Regra no model para formatar data


for loop broke, but debugger can not find any problems

Question: To simplify, the for loop in this code does not work. I am trying to have it countdown until remTime reaches 0. A while loop works, but only if it's set to while True:
Here is the code:
import datetime
from time import sleep

currentHour = int(datetime.datetime.now().strftime('%H'))
currentMin = int(datetime.datetime.now().strftime('%M'))
currentSec = int(datetime.datetime.now().strftime("%S"))

currentHourToSec = currentHour * 3600
currentMinToSec = currentMin * 60

currentTotalSec = currentHourToSec + currentMinToSec + currentSec
remTime = 86400 - currentTotalSec

x = 86400

for x in range(0):
    print(remTime)
    remTime = remTime - 1
    x = x - 1
    sleep(1)

Any help is greatly appreciated! Thank you so much!
Comment: What are you expecting from `range(0)`?
Comment: What about `while remTime > 0:` or just `while remTime:` .
Comment: Perhaps instead of randomly changing things, you should really understand what you're doing. Randomly changing things won't accomplish anything beyond frustrating you.
Comment: Alternatively, `while True: ...`, then `if remTime == 0: break`
Comment: Okay, thanks! I'll go try that.
Comment: It works! Thank you so much!
Comment: What is it that you *think* `for x in range(0):` means?
Comment: Well... I tried changing it to `range(86400)` but that didn't work either.
Comment: I'm trying to have `remTime` countdown until it reaches 0.
Comment: Can't you just use your `while True` setup, that you claim works? Why are you trying to use a for loop in the first place?
Comment: It works, but it never stops. I want it to stop when `remTime` reaches 0. After all there is no negative time.
Comment: A duplicate of what though...
Answer: for x in range(remTime, 0, -1):
    print(x)
    sleep(1)

According to the docs, range requires a starting value, stopping value, and step, also known as increment/decrement range(start, stop, step).
Since you want remTime to be reduced by one, and you want to visually see it go down via print, you can use range(remTime, 0, -1) which tells python, I want to start from remTime, and I want it to step/decrement down by -1 until it reaches 0.
Comment: Although it does work, I think giving OP a bit more explanation as to why would be helpful, as OP seems to be a new programmer.
Comment: Ermm, I dont know if this is gonna sound rude, but first what is OP mean?
Comment: Don't worry, it's not rude. OP just means original poster, basically the person who posted the question
Comment: Actually, I dont really know what to explain tho, as Aidan seems to know what he wants and I merely just simpliy the things that he his doing
Comment: No worries, I added an explanation that will hopefully give OP some insight


Shell scripts, python, ld_library

Question: I've got a program that calls a shell script from python. In the shell script, I add to the LD_LIBRARY_PATH like so, pointing at the .so's from mdbtools.
NEWPATH=${PWD}"/mdbtools/usr/lib/x86_64-linux-gnu"
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$NEWPATH

I'm pretty sure this part of the code is correct. I then call one of the programs from the .so, "mdb-export" like so, using variables from the input. :
mdb-export ${1} Athlete > "${2}athlete.csv"

Here's the confusing part. When I call the script from the commandline
./buildscvs abcd.mdb 1234

it works perfectly. The csvs are populated as expected. However, when I call the script from python:
    try:
        p = Popen([cmd, filename, prepend],  stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate()[0]
        print "p", p
    except Exception as e:
        print str(e)

cmd, filename, and prepend are as follows
filename = /app/djangoFiles/meetPlanner/2011ROXBURY.mdb
cmd = /app/djangoFiles/meetPlanner/buildcsvs.sh
prepend = 824365891

The csvs come out blank. This seems consistent with what happens when you run a command with an unknown program name, like if I ran
abcd 1234.mdb > test.csv

Does anyone have any idea what's going on? I'd very much appreciate any help you can give me
Thank you!
EDIT
After changing to
    subprocess.check_call()
as suggested below, I now get the following error message:
/mdb-export: error while loading shared libraries: libmdb.so.2: cannot open shared object file: No such file or directory

Comment: Why are you redirecting stdin and stdout to a pipe when you aren't using them? Just use `subprocess.check_call()` instead and any stdout and stderr should be printed, which will make debugging this vastly easier.
Comment: That helped -- thank you! Now I get this `/app/djangoFiles/meetPlanner/mdb-export: error while loading shared libraries: libmdb.so.2: cannot open shared object file: No such file or directory`. This doesn't come up when I run it from the terminal. Any ideas?
Answer: You must check not only stdout but stderr also.
(stdout, stderr) = Popen([cmd, filename, prepend],  stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True).communicate()
if stderr != "":
    print stderr

Also you write that ou set LD_LIBRARY_PATH, but where? In the script or in the python program? If in the python program you must pass the environment hash in the Popen call, but you don't do this.
The error that you get
/app/djangoFiles/meetPlanner/mdb-export: error while loading shared libraries: libmdb.so.2: cannot open shared object file: No such file or directory

means exactly that that LD_LIBRARY_PATH is set incorrectly (or is not set at all).
update
Ok, now we know that you set LD_LIBRARY_PATH in the script.
Don't forget to export it.
export LD_LIBRARY_PATH

Comment: Just add `export LD_LIBRARY_PATH` before the call of `mdb-export` in the script (to check the correctness of the idea).
Comment: do you export it? I mean in the script? it is possible that in the shell the variable is already exported ant that is why the script works, but in python script not yet
Comment: I set the LD_LIBRARY_PATH in the script itself
Comment: That makes sense. Do you have any suggestions for how to debug how to set it correctly? It works when I call it from command line, but not from the python program
Comment: I don't export it, but would be happy to try. What do I need to do to export it?
Comment: Got it! Thank you -- my path was off

Shell scripts, python, ld_library


regular expression conditional validation

Question: sample input text:
a) owner.table_name
b) table_name

can somebody suggest regular expression so that I get out put in such a way that i get text upto "." (if "." exists) and if "." doesnt exist then return empty
output:
a) owner
b) empty
regular expression so that I get out put in such a way that I get text from "." up to end (if "." exists) and if "." doesn't exist then return entire string
output:
a) table_name
b) table_name
Comment: [Have you tried anything?](http://www.whathaveyoutried.com) It usually helps to know what you've already attempted so that we don't reiterate things that haven't worked for you.
Comment: Are you looking for `owner(\.table_name)?`?
Comment: Why not use one regular expression (with matching groups) for both tasks?
Comment: Cyborg37 names it, we need some code. It would be useful to know your programming language, to give you some boilerplate code too (e.g. accessing capture groups of your regex)
Comment: I am using oracle posix. for 1) i tried '[^.]*' and for 2)  tried '\.(\w+)' but both does not solve the case where there is no "."
Answer: The following regex should work:
(?:(\w+)\.)?(\w+)

It creates two capture groups (see this debuggex example to play around with it)
The first group will be empty, with the input table_name. For owner.table_name both groups have the appropriate values.
Answer: Here's a regex that would match both in one:
((?<owner>\w+)\.)?(?
\w+)

If the tool you are using allows named groups, the first group will be called "owner" and will be any word before a period. The second group will be called "table" and will be any word after a possible "owner".


Using GCV to tune ridge parameter: alternatives for small number of data points

Question: I have previously used ridge regression, with suitable ridge parameter $\lambda$ tuned by generalized cross validation, to fit a dataset of around 100 points to around 10 predictor variables (with strong correlations between predictors). It worked well.
I am currently trying the same thing on a smaller data set, around 30 points and 6 predictors. The out-of-set prediction from GCV tuned ridge regression is always poor (r2<0.05). I have tried cutting the model down to 2 not-strongly-correlated predictors, still a poor result.
For the bivariate model (one predictor) out of set prediction is reasonable (r2=0.5). This leads me to think that there are enough data points to use GCV, but not enough data points to tune a ridge parameter using GCV.
Is there any way to estimate the minimum number of data points I need?
Also if I can't get any more data what alternatives are open to me?
Answer: To follow up on this, it turned out cv.glmnet in R was failing to automatically find the optimal value of lambda. If I manually set the range of lambda I could find it, and the model fitted just fine with cross-validated $r^2 \approx 0.5$.
So, there were enough data points after all.


Does data transformed in a certain way from a normal distribution fit some other common distribution?

Question: I have sampled a number of $x$ values from a normal distribution with mean 0 and sd 0.2. I then transformed these $x$ values to $y$ values using the formula $y = e^x/(e^x + 1)$. I know that the $y$ values will have a mean of 0.5 and all lie between 0 and 1.

Do these y values fit some common distribution?
Is there a way to figure this out in R?

What I am looking for is if there is a simple distribution to describe the y values that would allow me to describe it in terms of a few parameters and possibly sample directly from it in R.
Comment: the distribution is given by a few parameter already with your definition ? what is the difference for the application you havde in mind, between sampling things directly and using a transfomation after sampling ?
Comment: To sample y, just sample x from a Normal(0, 0.2) distribution and compute y = e^x/(e^x+1).  You can use (0, 0.2) as the parameters: by means of this formula they completely determine the distribution.
Answer: You have:
$X \sim N(\mu,\sigma^2)$
By definition:
$Y = \frac{e^X}{e^X+1}$
Therefore, the cdf of $Y$ is:
$P(Y \le y) = P(\frac{e^X}{e^X+1} \le y)$
Simplifying the RHS, we get:
$P(Y \le y) = P(X \le -log(\frac{1-y}{y}) )$
Therefore,
$P(Y \le y) = \Phi(-log(\frac{1-y}{y}),\mu,\sigma^2)$
Differentiating the above wrt $y$, we get the pdf $f(y)$ as:
$f(y) = (\frac{1}{y(1-y)}) \phi(-log(\frac{1-y}{y}),\mu,\sigma^2)$
I do not think the above pdf has a standard name.
onestop identifies the correct name for the pdf in his answer: Logit-normal distribution.
Reg how to sample it in R you can use the inverse-transform sampling. The idea is as follows:

Generate a uniform random variate: $U \sim U[0,1]$
Set $U = \Phi(-log(\frac{1-y}{y}),\mu,\sigma^2)$ and invert for $y$.

However, the use of the inverse method sampling is not necessary as a you could just sample values of $Y$ by sampling from $X$ first and then doing the logistic transformation (as given in your question).
Answer: This is called a logit-normal distribution (by analogy with the much more common log-normal distribution). Knowing that doesn't simplify sampling from it, however, or change the parameters used to describe it, which are still the mean and SD (or variance) of the parent normal distribution.
Comment: Unless I'm misleading, the second moment are not exactly identical between the two.
Comment: @chi - I meant the usual parameterisation of the logit-normal is in terms of the mean and SD of the related normal dist, not that the mean and SD of the logit-normal are the same as that of the related normal. Sorry if that was, or still is, unclear - i'm editing in a hurry as i should really have left for work by now!
Answer: The trivial way is just to realize this transformation and see what happens:

This looks pretty normal, indeed qqnorm confirms it:
Comment: Thank you for sharing your philosophy.  I agree: it's good to help people learn to answer their own questions.  Empirical investigation ("trying"), though, is usually best when informed by theoretical considerations to indicate the limits of its applicability.  In this case you're safe with the Q-Q plot, because it is so sensitive to deviations from normality and you used a largish sample size of about a thousand, but the histogram alone can be deceiving.  (Almost *any* bell-shaped histogram "looks" normal!)
Comment: Try the plots with a N(0,10^2) (i.e., 10 is standard deviation). It will not appear to be normal anymore.
Comment: @Srikant I agree, this is an answer to second point of the question.
Comment: You will run into trouble when you use any normal distribution with substantially nonzero mean.  The logistic transformation is almost linear for values near zero but becomes strongly nonlinear for more extreme values.  The resulting distribution will be strongly skewed; a normal approximation will be poor.  This explains why your answer is effective for the particular distribution proposed by the OP (so I upvoted it and hope others do too) but also puts constraints on its generalization to similar looking problems.
Comment: @whuber I agree, but I won't run into trouble, rather see that in such case it is not normal. This answer is just to promote trying as a technique, not to imply that resulting distribution will be always normal.


Knowing set of sums of pairs, calculate variables

Question: I apologize in adavnce if it was answered before.
If I had say, 4 variables: A, B, C, D, that are unrelated and only knew sums of any pair from these, how do I calculate values of variables?
All variables are positive but not necessarily integers.
And how would that change if there were more variables? Is this even possible? Or would I have to know anything more?
Comment: For any of the variables $X, Y, Z$, you have $(X+Y)-(Y+Z)+(Z+X) = 2X$. So as long as you have at least 3 variables, you can calculate each variable that way.
Comment: could you post this as answer? It seems to suit what I need most.
Answer: Assume that $A,B,C,D$ are real numbers.  Suppose $A\leq B\leq C\leq D$.  Then, $A+B\leq A+C\leq A+D \leq B+D \leq C+D$ and $A+C\leq B+C \leq B+D$.  Hence, if we order the pair sums as $S_1\leq S_2\leq S_3 \leq S_4 \leq S_5 \leq S_6$, then we know $A+B=S_1$, $A+C=S_2$, $B+D=S_5$, and $C+D=S_6$.
Note that $T:=S_1+S_6$ must be the same as $S_2+S_5$ and $S_3+S_4$.  We have a system $A+B+C+D=T$, $A+B=S_1$, $A+C=S_2$, and $B+C\in\left\{S_3,S_4\right\}$.  If $B+C=S_j$ with $j\in\{3,4\}$, you get $A=\frac{S_1+S_2-S_j}{2}$, $B=\frac{S_1-S_2+S_j}{2}$, $C=\frac{-S_1+S_2+S_j}{2}$, and $D=T-A-B-C=S_6-\frac{S_1+S_2+S_j}{2}$.  There are two possible solutions (with both $j=3$ and $j=4$) if $S_2+S_4\leq S_6$; otherwise, there is only one solution with only $j=3$.
Comment: well, I can't assume I got variables in any order... As I only know sums of any 2 of these,  and any sums at that.
Comment: You can always assume "without loss of generality" that your variables are ordered as I said.
Comment: whole thing is that I don't need raw numbers, these pairs are results of device test. I can only test devices in pairs and need to know which device has which result (single variable of pair)

And you can assume that variables are only in real positive numbers
Comment: You would still be able to figure out which device produces which number, assuming that $A,B,C,D$ are all known, because you know which two devices sum to which of the $S_i$'s.
Answer: Let $X$ be the variable you want to calculate, and let $Y$ and $Z$ be two other variables.
You have :
$$X = \dfrac{(X+Y)+(X+Z)-(Y+Z)}{2}$$


Prove: for a graph $G=(V,E)$, if$ |V| \ge 5$, there is a cycle in $G$ or in complement $G$

Question: I tried to do this with number of edges: if $|E| \ge n$ there is a cycle in $G$.
I got stuck when $|E|\lt n$.
Thanks!
Comment: not necessarily
Answer: Let $K=\{\{v,w\}:v,w\in V\}$ be the set of all possible edges for $V$, note that $|K|=(|V|^{2}-|V|)/2$. In particular, for $|V|\geq 5$ we find that $|K|\geq 2|V|$. Now let $G=(V,E)$ be a graph with $|V|\geq 5$.
If $|E|\geq|V|$, then $G$ has a cycle. If $|E|<|V|$, then in the complement graph of $G$, $\hat{G}=(V,K\setminus E)$ we find that
$$K\setminus E=(|V|^{2}-|V|)/2-|E|\geq 2|V|-|V|=|V|,$$
so the complement graph of $G$ has a cycle.
Answer: Let's suppose that there is no cycle neither in $G$ nor complement of $G$. In complement of $G$ there are $\frac{n(n-1)}{2}-E$ edges. If in both graphs there are no cycles, then number of edges in both graph is less than $n$. This means that the sum of number of edges in both graph is less than $2n$. So $\frac{n(n-1)}{2} < 2n \iff n < 5$ contradiction.


Acessando um JSON com JS

Question: Estava tentando acessar um JSON com JS, eis um exemplo de como eles são:
{
  status: "0",
  ano: "Não Informado",
  competencia: "Não Informado",
  id_Publication: "8"
}

Mas na verdade essa é somente uma parte do JSON completo. Esse é "um array multidimensional". Como eu posso acessar as informações dentro de p, mais especificamente a parte da competência?
Já tentei usar esse código:
{
  targets: 7,
  data: "",
  render: function(data, type, full){
    returnconsole.log(full);
  }
}

Ele retorna todo o JSON se uso dessa maneira e se coloco:
{
  targets: 7,
  data: "",
  render: function(data, type, full){
    returnconsole.log(full['p']);
  }
}

Ele retorna os dados somente de p, MAS se eu tento colocar:
{
  targets: 7,
  data: "",
  render: function(data, type, full){
    returnconsole.log(full['p.competencia']);
  }
}

Ele retorna undefined.
Comment: Esse JSON não é valido. Corrige o mesmo para que possamos responder, está bem confuso, valida ele aqui: https://jsonformatter.curiousconcept.com/
Comment: É válido sim, funciona aqui, isso é um exemplo, como eu posso acessá-lo? @LeonardoBonetti
Comment: Agora sim está válido. Vou postar a resposta !
Answer: Basta criar um objeto do seu JSON myObj ={json aqui} e acessar pelo nome do objeto ponto atributo: myObj.competencia. Simples, fácil e rápido.

myObj = {status: "0", ano: "Não Informado", competencia: "Não Informado", id_Publication: "8"};

console.log(myObj.competencia)

Acessando um JSON com JS


Using fonts with html

Question: I have a font, Indie Flower, which I'm trying to use in my site. I've followed what Google told me:
Copy and pasted this into my headtag:
<link href="https://fonts.googleapis.com/css?
family=Indie+Flower&display=swap" rel="stylesheet">

Then i specified my css like so:
.event {
font-family: 'Indie Flower', cursive;
font-size:80px;
border: none;
color: rgba(255,255,255,0.6);
text-align: center;
}

So why isn't it displaying?
Comment: Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and **the shortest code necessary to reproduce it in the question itself**. You aren't showing your HTML.
Comment: If it's live site share your site url over here
Answer: It is happening because you are using white as a text color that rgba(255,255,255,0.6) means white color with opacity of 0.6. for black color you have to put rgba(0,0,0,0.6).
This is working code
I hope it helped you.

.name {
font-family: 'Indie Flower', cursive;
font-size:30px;
border: none;
color: rgba(0,0,0,1);
text-align:center;
}
<link href="https://fonts.googleapis.com/css?
family=Indie+Flower&display=swap" rel="stylesheet"/>

  Muhammad Muzammil

Comment: Note: the `` tag does not use and does not need a closing slash and never has in HTML.
Comment: Leave that just see that i have solved your issue. I am a blogger user so that's why its my regular practice.
Answer: You have a space in your link. Remove the space and make sure your white font color is not causing issues with you seeing it.
Answer: The link is wrong. Check this. I got this correct link and it's working fine.
Html file:
<!DOCTYPE html>

    <title></title>

    <link rel="stylesheet" type="text/css" href="html.css">
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower&display=swap" rel="stylesheet">

this is the indie flower text

CSS file:
#p1{
    font-family: 'Indie Flower', cursive;
}

Using fonts with html


Proving $ \lim_{n\to\infty} \dfrac{ \Phi^{n+1} - (1 - \Phi)^{n+1}}{\Phi^{n} - (1 - \Phi)^n} = \Phi $

Question: $ \Phi = \frac{1 + \sqrt{5}}{2} $ is the golden ratio
I'm having hard time using proving that $$ \lim_{n\to\infty} \dfrac{ \Phi^{n+1} - (1 - \Phi)^{n+1}}{\Phi^{n} - (1 - \Phi)^n} = \Phi $$ dividing both the numerator and denominator by $ \Phi^{n} $ doesn't help, neither does $ \Phi^{n} - (1 - \Phi^{n}) = (2 \Phi +1 ) \sum\limits_{i=0}^{n-1} \Phi^i (1 - \Phi)^{n-1-i} $
Where is the trick?
Comment: I think that dividing the numerator and denominator by $\Phi^n$ is helpful.
Answer: Hint:
$\Phi-1=\dfrac{\sqrt5-1}2=\dfrac{5-1}{2(\sqrt5+1)}=\dfrac2{\sqrt5+1}<1$ and $>0$
$$\implies|1-\Phi|<1\text{ and }\left|\dfrac{1-\Phi}\Phi\right|<1$$
Divide the numerator and the denominator by $\Phi^n$
Comment: @user1992, Thanks for the observation
Comment: @user1992, Rectified
Answer: Use How do I prove Binet's Formula?
if $F(m)=\dfrac{\alpha^m-\beta^m}{\alpha-\beta}$ with $\alpha,\beta$ are the roots of $$t^2-t-1=0$$
we can prove $$F_{n+2}=F_{n+1}+F_n$$
$$\dfrac{F_{n+2}}{F_{n+1}}=1+\dfrac1{\dfrac{F_{n+1}}{F_{n}}}$$
If $\lim_{n\to\infty}\dfrac{F_{n+2}}{F_{n+1}}=r>0,$ $$r=1+\dfrac1r\iff r^2-r-1=0, r=?$$


save list box option value into mysql then again display php mysql

Question: I want to save list option values into MySQL then again want to display them as a list.
I need that for a dynamic query.
 <select multiple id="to" size="15" name="to[]">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
 </select>

This is php code to change it into (a,b,c,d):
   $joinedString = array();
   $var1 = $_POST['to'];
   $joinedString = implode(',', $var1);
   $joinedString;

I just change this into a,b,c,d with implode function, and its working fine.
But don't know how to save it in mysql and how to again fetch data from database and  make this as:
 <select multiple id="to" size="15" name="to[]">
    <option value="a">a</option>
    <option value="b">b</option>
    <option value="c">c</option>
    <option value="d">d</option>
</select>

Comment: Your first example is the same as the second, please edit your question so we can better understand.
Comment: Are you storing `comma separated` value within database.
Comment: Save comma separated string into database and fetch using mysql and then again make it into array by using `explode()` function. Iterate on this respective array and display html that you want.
Answer: Now that you have the string a,b,c,d in variable $joinedString, Just use it to insert into your database. Remember you need to insert this string like this 'a,b,c,d' and not simply a,b,c,d. So, first format your string in inverted commas like 'a,b,c,d'. Now, that you have done it, just use insert command.
Insert into Table_name set column_name='".$joinedString."' where some_condition.

After that, you retrieve it if you have to use it again, using "Select" query.
Select column_name from Table_name where Some_condition

It would give you your variable back to you in format, 'a,b,c,d'. Save it in some variable $variable.
Now you use explode function to make an array of this string using comma.
$arr_string  = explode(",",$variable);
This $arr_string would be an array like this

array(0=> a,
      1=> b,
      2=> c,
      3=> d)

Now you loop over this array using foreach and make the select option.
<select multiple id="to" size="15" name="to[]">
<?php
     foreach($variable as $key=>$val)
     {
       echo "<option value='".$val."'>".$val."</option>";
     }
?>
</select>

Answer: If you are storing comma separated value within database you can get the value from database using query and from result you can simply implement that within your file using explode function of PHP as :
<?php
$joinedString = 'a,b,c,d'; // fetched data from database using query if you are storing data within database comma separated
$data = explode(',',$joinedString);
?>
<select multiple id="to" size="15" name="to[]">
    <?php foreach($data as $key => $value){?>
    <option value="<?php echo $value; ?>"><?php echo $value; ?></option>
    <?php } ?>
</select>

I think this might be the expected answer..
Comment: You are welcome @jitu and you can accept it as an answer so it must be considered as solved issue..


How secure are GUIDs in terms of predictability?

Question: We're using .NET's Guid.NewGuid() to generate activation codes and API keys currently. I wonder if that poses a security problem since their algorithm is open.
.NET Guid uses Win32 CoCreateGuid and I don't know its internals (possibly MAC address + timestamp?). Can someone derive a second GUID out of the first one, or can he hit it with some smart guesses or is the randomness good enough so search space becomes too big?
Generating random keys have the problem of collision, they need a double check before adding to a database. That's why we stuck with GUIDs but I'm unsure about their security for these purposes.
Here are the 4 consecutive UUIDGEN outputs:

c44dc549-5d92-4330-b451-b29a87848993
d56d4c8d-bfba-4b95-8332-e86d7f204c1c
63cdf958-9d5a-4b63-ae65-74e4237888ea
6fd09369-0fbd-456d-9c06-27fef4c8eca5

Here are 4 of them by Guid.NewGuid():

0652b193-64c6-4c5e-ad06-9990e1ee3791
374b6313-34a0-4c28-b336-bb2ecd879d0f
3c5a345f-3865-4420-a62c-1cdfd2defed9
5b09d7dc-8546-4ccf-9c85-de0bf4f43bf0

Comment: possible duplicate of [How Random is System.Guid.NewGuid()?](http://stackoverflow.com/questions/467271/how-random-is-system-guid-newguid)
Comment: The Wikipedia on guid is pretty good on guid algorithm: http://en.wikipedia.org/wiki/Globally_unique_identifier
Comment: Cody, it is similar but I'm not strictly looking for randomness per se. For instance GUID could be a VERY high percision timer and still be secure without being random. All I want to know is if the search space between consecutive GUIDs are broad and not-predictable enough for trivial brute force attacks.
Answer: GUIDs are quite random, but they are not intended to be used as random numbers - their sole purpose is to uniquely identify entities, so they can be predictable.
Use System.Security.Cryptography.RandomNumberGenerator instead.
Answer: Any key has a finite space and a sufficiently determined person/group can and will generate all combinations. What's important is not so much the key but how you organise it's validation and what it authorises. If you are operating the validation/authorisation entirely through the Guid then that's probably not appropriate as potentially all Guids are valid, you'd be better off with something like SeriousBit Elipter. If you are using an authentication mechanism that records that a particular Guid has been issued and that it has now been used for activation then Guid isn't such a bad choice as it's a pretty big key space.
Answer: There are multiple mechanisms for generating guids, some using MAC addresses and some just using pure random number generation. iirc the amc address should be obvious in the GUID if it's being used - it's not hashed out in any way.
edit: proviso, slightly lame answer, as here I'm talking about generic guid generation rather than a possible ms algo that does obfuscate it. am looking into it, will delete if it's not useful ..


How to get logonserver name in AD domain programatically

Question: A host which part of Active directory domain does authentication from the logon server (domain controller).
LOGONSERVER env var has its value.
C:>echo %LOGONSERVER%
\PUN5OPSDIRPIN01
Is there any API using which I can retrieve this value?
Comment: This could swing either way, on Stackoverflow or here.  I would propose that we keep it here because of the usefulness in scripting sysadmin tasks.
Answer: Nearly every language or framework will have a method that will let you retrive the values of environment variables.  .NET, Powershell, Java...  What are you coding in?
C#:
System.Environment.GetEnvironmentVariable ()
Powershell:
$env:<name of env variable>, so for example $env:logonserver
WMI (using VBS):
Set colItems = objWMIService.ExecQuery("Select * from Win32_Environment")
Java:
System.getenv("LOGONSERVER")
Comment: Well played, sir
Answer: Assuming you want to retrieve that from the client, you could query "HKCU:\Volatile Environment\LOGONSERVER" or env:LOGONSERVER.


DDD: where to generate url slug of an entity?

Question: how do you deal with url slug generation in DDD?
Inside constructor? But entity relying on other service is not good.
Pass as constructor argument? I think slugs shouldnt be there because they are not business requirements. are they?
or just having a setter?
Comment: Yes, a separate table is probably the best idea. At the end, the slug is just a presentation concern, and if you ever, say, add a mobile-app to your course-system, a slug has no meaning here.
Comment: A slug does not seem like a real concept from your underlying business domain, but rather something to provide nice URLs for web applications. As such slug generation is part of another layer or bounded context and does not belong to the core domain.
Comment: I know it's hard, but I'd think the url slugifier as a service **outside** the domain layer, today you might use an external package to generate it, tomorrow you might consume an external API, I wouldn't put this logic inside domain. Therefore, like @AlexanderLanger said, I'd create a separeted entity with the url slug, and a reference to the owner entity (id and type). So you can store url slug for any kind of entity (images, videos). Putting a property in the entity is something strong, like it's **part** of the entity independently of what application is being used to _consume_ said entity.
Comment: how will you deal with that? We have courses, and I want the title of the course to be the url instead of the id. The url may vary depending on the title if its too long or for other reason so Ive thought its better to save it on database. so you mean by bounded context, I should save it on separate table?
Comment: Thank you. Havent had the chance to play with it yet.
Answer: It seems like the URL slug IS part of your domain model, even though it seems like an infrastructure concern at first.
If you are modeling it as a property of your entity, I see no problem in passing it in the constructor arguments. It is certainly better then having it as a property with a public setter, open to be modified by anyone at anytime.
Create an ISlugGenerator interface and inject it into the appropriate layer (ApplicationService or DomainService, see here for more info), to generate the URL string and pass it in the constructor to the entity.
Implement the ISlugGenerator in the Presentation Layer, the one that actually holds the page/route that is going the be accessed via the URL.

You could argue that the URL really has no place in the domain model, because it is just some info that is related to the entity, but is not used in any decision making process.
Well, then think about Product Description or Product Image in an e-commerce application. It is the same thing. You most certainly have validation logic for these properties and this validation should be part of the Domain, but you probably don't make any other decisions based on them.
So, shouldn't you remove Description and Image from the Product entity? Actually, no. Even though the image is probably a URL just like the slug from your question.
The product will receive the imageUrl as a string parameter in its constructor, or be set via a method in the entity. But the imageUrl will be generated by some ImageUploadService, whose interface will be defined in the Application Layer and implemented in some Infrastructure Layer.


Question Regarding Isolation and Limit Points

Question: I have been self studying real analysis and came across a question regarding isolated vs interior points. I am reading that an isolated point p of a set S is an element of S such that p not a limit point of S; however, a limit point of S is a point such that any neighborhood of p contains a point q not equal to p in S. My question is, wouldn't any point in a set have a neighborhood that contains a different point in that set, and therefore be a limit point?
Thank You
Comment: No. Consider the integers with the subspace topology from $\mathbb{R}$.  For $a \in \mathbb{Z}$, $\{a\}$ is an open neighbourhood of $a$ that has empty intersection with $\mathbb{Z} \setminus \{a\}$.
Answer: No. Or, more accurately, yes, but the thing you wrote after "my question is" is not the same as the definition: for a point $p$ to be a limit point of a set $S$, every neighbourhood of $p$ must contain some element of $S \setminus \{p\}$.
It is then easy to see that not all points have this property: for example, for any $p \in \mathbb{Z}$, there is no point of $\mathbb{Z}$ in the neighbourhood $(p - 1, p + 1)$ of $p$.
Answer: For limit points the requirement is that every neighborhood of that point has a point of set different from that point.
As the result every neighborhood will have infinitely many points of the set  different from that point. Another way of saying it is the limit point is actually the limit of a sequence of distinct points of the set converging to that point.


Rename a taxonomy vocabulary during migration

Question: I'm working on a custom migration for taxonomy vocabulary and I was wondering if there is a way to rename a vocabulary during migration?
my d7 vocabulary name is staff and I wanted to be migrated to d8 as departments
Answer: This could be achieved by using static_map plugin:
plugin: static_map
  bypass: true
  map:
    staff: departments


Migrando do svn para git: tags ganham um '@' com número ao final da tag. O que pode ser?

Question: Estou com uma dúvida. Fiz o clone do projeto com git svn clone. Utilizei o git remote add +url para adicionar o repositório remoto. Quando estou fazendo o git push --tags para o git as tags estão indo em um formato diferente do svn. Por exemplo:

No SVN: tag_all_1.0.0.
No GIT (migrado): tag_all_1.0.0@431

Alguém sabe o que pode ser isso?
Comment: Oi. No meu projeto utilizei o subgit [link](https://www.smartsvn.com/subgit/) e não enfrentei esta dificuldade, todas as tags foram migradas corretamente. Vale o teste?
Answer: Acredito que a explicação para isto ocorrer com as tags seja a mesma com as branches: o Git Svn não foi capaz de encontrar um commit "pai" para o primeiro commit da branch SVN para que ele possa conectar a branch com o histórico das outras branches.
Isto ocorre porque o SVN permite que uma branch possa ser criada de um diretório qualquer que não seja necessariamente uma branch (ou trunk) dentro do SVN. Por exemplo, copiando o diretório /trunk/foo para /branches/bar ao invés de copiar a partir do /trunk dará origem a esta branch.
O formato no qual ele cria a branch (ou tag) é:
<branchname>@<SVN-Revisão>

Agora, explicar a origem desta revisão e por que o Git toma esta decisão é mais complicada. Confesso que li e não entendi muito bem e, para não simplesmente traduzir o que está dito lá, deixo o link para ler a explicação da documentação. Acredito que isto já ajude, pois não é tão simples buscar por informações deste problema no Google :).
Isto acontece com tag também porque no SVN não há muita diferença entre branch e tag: ambos são criados por meio de cópia de diretórios. O Git Svn então reflete o mesmo comportamento para ambas.
Como evitar esta situação
Na clonagem do repositório, esta criação de branch/tag com o sinal de arroba (@) pode ser evitado com o parâmetro --no-follow-branches.


What are these additional white lines on the cricket pitch?

Question: Some cricket pitches have an additional white line, perpendicular to both the bowling crease and popping crease, and joining both of them. One example is of the Eden Garden stadium pitch (2016)
video source

I have highlighted the line in question in a pink box. There are three more lines, a total of two on each side of the pitch. I checked Law 7 - The Creases and Law 6 - the Pitch, and could not find any reference to these lines.
What are they? Are they not standard lines i.e. why are they not on every pitch? What is their purpose?
Comment: Shorthand for *"spelling/grammar/syntax"*. It means fewer characters in the edit summary to get past, for what is usually a small component of the edit.
Answer: The line which you have highlighted in the image is the wide marking. They provide the limits within which bowlers have to bowl and assist umpires in adjudging if a delivery can be called "wide".
Sources:
1) http://premier.cricketvictoria.com.au/files/3/files/premier-match-rules/Crease%20Markings%20Diagram%20and%20Wide%20Ball%20Interpretation%20White%20Ball%20Cricket%20Guidance.pdf
2) http://cricket.rushisbiz.com/cricket-pitch-and-ball-details/
Comment: They're only used in ODI (One-Day International) and Twenty-20 cricket, so they won't be marked for a multi-day game. They're not in the laws because they're defined as regulations for a specific form or forms of cricket, while the items in the Laws are for all forms of cricket.
Comment: As a canonical source, I'd suggest the [T20I Playing Conditions, Appendix C, Section 1](https://pulse-static-files.s3.amazonaws.com/ICC/document/2017/10/05/827e3bdd-6306-404e-8c62-47ae2f0ea223/ICC-Men-s-T20I-Playing-Conditions-2017-Code-FINAL-051017.pdf). (The diagram is identical in the ODI playing conditions).
Comment: Interesting, thanks for your answer! Any idea why these rules are not given in the laws? And why do many pitches _not_ display the wide lines?


How to add a class to more link of a view?

Question: I want to add a class to a views more link available under pager section using template_preprocess_views_view().
Answer: You can do it by implementing template_preprocess_views_view() in your theme under THEMENAME.theme file as shown below:
/**
 * Implements template_preprocess_views_view()
 * @param array $vars
 */
function THEMENAME_preprocess_views_view(&$vars){
  if (YOUR CONDITION FOR ADDING A CLASS){
    $vars['more']['#options']['attributes']['class'] = [
      ENTER YOUR CLASSES AS ARRAY ELEMENTS
    ];
  }
}

Alternatively, if you want to add a class to the .more-link wrapper instead of the link itself, you can use the following code in the same preprocess function as above:
$variables['more']['#theme_wrappers']['container']['#attributes']['class'] = [
  'more-link',
  'my-class',
];

Reference: http://www.drupalthemez.com/blog/d8-adding-class-more-link-view


how do i append in this function?

Question: i have this code:
for (var i = 0; i < data.times.length; ++i) {
    var time = formatTime(data.times[i].time);
    tableContent += '
' + data.times[i].destination.name + '	' + time + '	' + data.times[i].track + '	' + data.times[i].train_type + '	' + data.times[i].company + '
'
    // laat vertragingen zien (BETA)
    if (data.times[i].delay / 60 >= 1) {
        $('#appendLate' + i + '').append("+" + data.times[i].delay / 60).addClass("late");
    }
}
table.html(tableContent);
}

The if statement appends stuff and adds a class. i know it wont work like this.. but i cant seem to get how it WIL work.. Can some one help?
See it live: http://codepen.io/shiva112/pen/JGXoVJ?editors=001
Comment: Your issue is that you're trying to append to a DOM node the doesn't exist yet. You have to insert `tableContent` into the DOM first. Then you can use jQuery to find it.
Comment: i know, my question is. How to do this..
Answer: Well, you're basically almost there. The right way to do it is to build the entire string before doing any DOM manipulation, since DOM operations are very slow (relatively).
Let's say your index.html looks like:

  <title>Cool site!</title>

Then your JavaScript simply becomes:
var tableContent = '';
for (var i = 0; i < data.times.length; ++i) {
  var time = formatTime(data.times[i].time);

  tableContent += '
'
                    + '' + data.times[i].destination.name + '	';

  if (data.times[i].delay / 60 >= 1) {
    tableContent += '' + time + '	' + '+' + (data.times[i].delay / 60);
  } else {
    tableContent += '' + time + '	';
  }

  tableContent += '' + time + '	'
                + '' + data.times[i].track + '	'
                + '' + data.times[i].train_type + '	'
                + '' + data.times[i].company + '	'
                + '
';
}

$('#myCoolTable').html(tableContent);

What this does is build the HTML for the entire table. Then update the table only once. Hope it helps!
Comment: Only had to fix this line:

tableContent += '' + time + '+' + (data.times[i].delay / 60) + '';

how do i append in this function?


Prove $ \lim_{n\to\infty}\sqrt[n]{p(n)}=1 $ for polynomial

Question: Let $ p(x)=\sum\limits_{k=0}^{d}a_kx^k $ polynomial such that $  \forall x>0, p(x)>0 $

Prove that:
  $$ \lim_{n\to\infty}\sqrt[n]{p(n)}=1 $$
Comment: The idea is that for $x$ large we have $p(x)\approx a_d x^d$.
Comment: Please, if you are ok, you can accept the answer and set it as solved. Thanks!
Answer: Hint:
Find a lower and upper bound that converge to 1 and use the squeeze theorem. A possible upper bound would be to use
$$ \lim_{n->\infty}\sqrt[n]{p(n)} \leq \lim_{n->\infty}\sqrt[n]{c n^{k+1}}$$
because
$$ \sqrt[n]{p(n)} \leq \sqrt[n]{c n^{k+1}} $$
where c is some number takes care of the finite increase produced by $a_k$ (since it's a partial sum). The upper bound can be found with L'Hopital's limit rule.
Answer: From the fact that $\forall x>0$ $p(x)>0$ we get that $a_d>0$. Also $p(n)\to +\infty$ as $n\to +\infty$. So $\exists$ $N\ge 1$ such that $p(n)>1$ when $n>N$. Then we get that $\sqrt[n]{p(n)}>1$ when $n>N$.
In the rest of this answer we're assuming that $n>N$ and $n\ge d+1$.
Let $\sqrt[n]{p(n)}=1+\alpha_n$, where $\alpha_n>0$. Then by Binomial theorem:
$$p(n)=(1+\alpha_n)^n=\sum_{i=0}^n \binom{n}{i}\alpha_n^i>\binom{n}{d+1}\alpha_n^{d+1}$$
$$0<\alpha_n^{d+1}<\frac{p(n)}{\binom{n}{d+1}}=\frac{(d+1)!\left(\sum_{i=0}^d a_i n^i\right)}{\prod_{i=0}^d (n-i)}=$$
$$=\frac{(d+1)!\left(\sum_{i=0}^d a_i n^{i-d-1}\right)}{\prod_{i=0}^d (1-\frac{i}{n})}\to \frac{(d+1)!\left(\sum_{i=0}^d a_i \cdot 0\right)}{\prod_{i=0}^d (1-0)}=0$$
as $n\to +\infty$. By Squeeze theorem $\alpha_n^{d+1}\to 0$, so $\alpha_n\to 0$, so $\sqrt[n]{p(n)}\to 1$ as $n\to +\infty$.
Answer: That polynomials will strictly increase after some point and you will have after some $n_0$ $$a_0<p(n)<a_dn^{2d}$$
In the limit...
Answer: Since $p(x)>0$ for $x>0$ necessary we have $a_d>0$  then,
$$ p(n)=\sum_{k=0}^{d}a_kn^k  =  n^d \left( a_d+  \sum_{k=0}^{d-1}a_k n^{k-d}\right) ~~~~~~and~~~~~\sum_{k=0}^{d-1}a_k n^{k-d}\to 0$$
Hence, since  $n^{1/n}\to1 $  it follows that, $$ \lim_{n\to\infty}\sqrt[n]{p(n)} = \lim_{n\to\infty}n^{d/n} \left( a_d+  \sum_{k=0}^{d-1}a_k n^{k-d}\right)^{1/n}=\lim_{n\to\infty}n^{d/n} \left( a_d\right)^{1/n}=1$$
Answer: Note that
$$\sqrt[n]{p(n)}=e^{\frac{\log p(n)}{n}}\to1$$
indeed
$$\frac{\log p(n)}{n}=\frac{\log \left(a_dn^d+a_{d-1}n^{d-1}+...a_0\right)}{n}=\frac{\log \left(n^d\right)+\log \left(a_d+a_{d-1}n^{-1}+...a_0n^{-d}\right)}{n}=\frac{d\log n}{n}+\frac{\log \left(a_d+a_{d-1}n^{-1}+...a_0n^{-n}\right)}{n}\to0+0=0$$


What are the poly-fills to be used to work Angular 10 in opera mini?

Question: Is there any poly-fills to be added to make angular 10 works in opera mini?
Comment: https://stackoverflow.com/questions/34948658/does-angular-2-0-support-opera-mini
Answer: After few hours of investigation, i found a solution. we can modify target to es5 in tsconfig.base.json because es6 will not work in opera mini.
tsconfig.base.json
/* To learn more about this file see: https://angular.io/config/tsconfig. */
<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>
Modified one
/* To learn more about this file see: https://angular.io/config/tsconfig. */
<code>{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es5",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
</code>
For reference, please go through below links
https://angular.io/guide/typescript-configuration
https://angular.io/cli/build


Custom module to delete webform entries working but receiving notices and warnings

Question: I have a little webform to collect email addresses for a newsletter (not handled by my website) with a user language preference and an option to either "subscribe" or "unsubscribe" the email that's being submitted.
I want to delete all submissions for a given email if it is submitted with the "unsubscribe" option. So I wrote a module using some webform APIs to do that. It works and deletes the already submitted entries of the webform with an "unsubscribed" email. However I keep receiving these errors:

Notice: Trying to get property of non-object in
  _webform_filter_values() (line 2946 in /home/test/public_html/sites/all/modules/webform/webform.module).
Notice: Trying to get property of non-object in
  _webform_filter_values() (line 2952 in /home/test/public_html/sites/all/modules/webform/webform.module).
Warning: Invalid argument supplied for foreach() in
  _webform_filter_values() (line 2952 in /home/test/public_html/sites/all/modules/webform/webform.module).
Notice: Trying to get property of non-object in
  _webform_filter_values() (line 2975 in /home/test/public_html/sites/all/modules/webform/webform.module).
Warning: array_diff_key(): Argument #2 is not an array in
  _webform_filter_values() (line 2975 in /home/test/public_html/sites/all/modules/webform/webform.module).
Warning: Invalid argument supplied for foreach() in
  _webform_filter_values() (line 2976 in /home/test/public_html/sites/all/modules/webform/webform.module).
Notice: Trying to get property of non-object in
  _webform_filter_values() (line 2984 in /home/test/public_html/sites/all/modules/webform/webform.module).

This is my module's code:
function unsubscriber_webform_submission_insert($node, $submission) {
    if ($node->nid == 49) {
        // Find the keys of the components
        foreach ($node->webform['components'] as $key => $value) {
            if ($value['form_key'] == 'email') {
                $email_key = $key;
            }
            if ($value['form_key'] == 'opzione') { // this is the unsubscribe option
                $opzione_key = $key;
            }
        }
        // Get the submitted email
        $usermail = $submission->data[$email_key]['value'][0];

        if ($submission->data[$opzione_key]['value'][0] == 'unsubscribe') {

            $submissions = webform_get_submissions($node->nid);

            foreach ($submissions as $sub) {
                if ($sub->data[$email_key]['value'][0] == $usermail) {
                    webform_submission_delete($node, $sub);
                }
            }
        }

    }
}

I'd like some advice about what could be wrong.
Comment: The way this is written, it looks like you'll also be deleting the same webform submission that triggers the hook, while it's still being processed. It's hard to say if that's what's causing your issues without doing some debugging, though.
Comment: Yes that was my purpose and finally I understood that deleting the last entry triggers the errors.
The hook_webform_submission_insert should fire after the submissions are already written to the database, but for some reason deleting the last one triggers those errors. I ended up hacking the webform.module adding some (hopefully harmless) if conditions in places where the webform code wants to act on some arguments, but they are empty after my module deletes the last entry.
Everything seems to work properly and I even implemented another function that clears up duplicates.
Any advice welcome.
Answer: You shouldn't have to resort to hacking webform module. Instead, adjust the hook_webform_submission_insert() implementation so that you're only deleting submissions where $opzione_key == "subscribe".  That means you won't have to worry about deleting the current submission.  If you need to clean out "unsubscribe" submissions too, write a hook_cron() implementation to do that.


Optimal threshold from a uni-variate continuous variable without target

Question: I have a univariate continuous variable. Now I would like to know is there any objective approach that can give me the optimal threshold that can help me make it a dichotomous variable with values as low and high. Please note that I have only variable (one column) and there isn't any dependent variable. The data looks like as shown below
Freq
 31124
 57643
 70
 13
 1000

So now based on the data, I feel that terms occurring like 70 or 13 should be put under the "low" category because they can't really influence my output with such a little data whereas putting 1000 under low category may not be right because 1000 is a huge number and can influence the output.
Later, I might decide to exclude records from low category but that's a different discussion altogether.
Can help me how can we get an optimal threshold without having target variable?
Comment: Dichotomization throws away a lot of information and is almost always a bad idea. (For instance, if you put your threshold below 1000, then you will treat 1000 and 31124 equally, since both are "high", although there is a much larger difference between the two than between 1000 and 70.) That said, to answer your question, you will need to think about how you can deduce whether one threshold is "better" than another one, so you will need to think about how you plan on using your thresholds.
Comment: Exactly. Based on your experience, can you let me know whether there is any theory/staistical approach which can let us know that any data that occurs only like 1 or 2% in your data, they can be removed.  For ex: while dealing with missing data, we know that any variable which has around 70-80% of missing data can be removed without any second thought because they don't add any value to the output
Comment: You don't have sufficient basis for answering this question: the meaning of "optimal" implies you will use the data in some way in some analysis.  If you could describe that intended analysis, it might be possible to supply objective answers.
Comment: @whuber - Basically I am trying to minimize the manual effort spent by reviewers ... I don't want them to review items which occurs very rarely and has very little importance ....I want the reviewers to focus only on terms which occur most, hence it's worth reviewing....
Comment: IMHO, your current question has abstracted away the essence of that problem, making it impossible for the answers here to have any useful bearing on your original problem.
Comment: @whuber - Thanks for the feedback. Hence I broke it into two questions.. Hence I feel this post   https://stats.stackexchange.com/questions/469875/statistical-proof-to-exclude-less-frequent-records-from-data-during-analysis  has the relevant info and your inputs would be helpful
Answer: This is the classic "thresholding" problem as it occurs, e.g., in image processing. There the two classes are not "low" and "high", but "background" and "foreground". From a more general point of view, it is a clustering problem: how to divide the data into two groups by means of a threshold.
In your case, it seems to me that Otsu's method should work well, which minimizes the within group variances, i.e.
$$\sigma_{within}^2(t)=n_{low}(t)\cdot\sigma_{low}^2(t) + n_{high}(t)\cdot\sigma_{high}^2(t)$$
where $t$ is the threshold and "low" are the data values less than $t$ and "high" the data values greater than $t$. When you have $n$ data points, there are $n-1$ different possible values for $t$ and you can compute $\sigma_{within}^2(t)$ for each of them and pick the $t$ that minimizes it.
Comment: @whuber Yes, this is a good point: for any clustering algorithm with a fixed number of clusters *k*, it should be tested whether the choice for *k* is indeed appropriate. When,e.g., *k* = 2, the distribution should be tested for bimodality. I understood the question in such a way that there are good reasons, in this use case, to assume that there are two classes (*low* and *high*).
Comment: In many applications this would be good advice, but it's not hard to identify situations where this approach is irrelevant or worse.
Comment: Hi Thanks for the response. Upvoted.


Pop Music Chord Choices

Question: I am a piano player and I can play by ear. I've done a lot of theory and I understand chord progressions quite well. However, when it comes to teaching people how to choose chord progressions what is a good method to string together chords for a simple loop-based phrase? I've discovered a couple of rules: starting on III or V chord will cause the phrase to sound modal. For some of my students their choices just seem random...because they are.
Note: I am asking this NOT from the point of view where you have a given melody and you are trying to match chords to it.
Answer: Generally speaking, and particularly for students with no great knowledge or experience, start with the home key chord. This sets the scene. And finish with it as well. This gives the piece more shape. 'I started from home, and now I'm back'.
The majority of pieces do this, because it works. You're right in that if you start somewhere else, it sounds modal. That's because you've stated a start chord, which most of us translate as 'this is the key of the piece'.
The penultimate chord is also important, often being the IV or V of the key.Cadences give a feel that something is at an end, or at least the end of that part.If, in C, for example, you played .....F, Em at the end, it really wouldn't feel like the end.
Comment: Actually, in pop music, it's fairly common to end on chords that are not the I chord. This is my dilemma. You can start on anything except for III and V. Frank Ocean's "Thinkin' Bout You" starts on the II chord and has the progression II I V VI. I guess when I'm talking about pop music, I'm referring more to loop-based songs as opposed to country or folk music, which generally use I, IV and V mainly.
Comment: In pop music, it's fairly common to fade out. Saves coming up with an ending !  An awful lot of all kinds of music uses I,IV and V mainly. We've got used to it in the Western world.
Comment: Yeah, that is true...I guess I'm referring to top 40 type songs more. I've been trying to come to some sort of consensus, but I think perhaps there is no cut and dried method to this because there are simply too many possibilities.

Pop Music Chord Choices


how to use OpenMP in CodeLite?

Question: I want to use OpenMP in CodeLite, but it doesn't work.
I have already choose -fopenmp in compile setting(actually it's the default setting).
My program is as follows:
#include <stdio.h>
#include <omp.h>
int main()
{
    #pragma omp parallel
    {
        printf("Hello World!");
    }
    return 0;
}

The result of this program shows that "#include " doesn't work, and the "#pragma omp parallel" is ignored.
Comment: You need to explain what "doesn't work" means. It works fine for me.
Answer: Make sure the openmp support library is installed, for example, on Linux with gcc, you should install the libgomp package, for example if you are on fedora, run dnf install libgomp, then try compile again.
Answer: It is necessary to pass -fopenmp to the linker to enable OpenMP features. The following steps should help you achieve that:

Right click on the project in the workspace view.
Select "Settings" near the bottom of this pop-up menu. Settings...->Linker->Linker Options.
Click into the semicolon delimited list to reveal ellipses and click on the ellipses.
Click the checkbox for "Enable OpenMP (linkage) [-fopenmp]"
Re-compile the code - It should work!

how to use OpenMP in CodeLite?


Simple question on graphical representation of minmax decision rule

Question: In the picture below, I cannot understand why the minmax decision rule is on the line $R_1=R_2$.
$R_i=R(\theta_i,d)$, where $\theta_i$ is the parameter and $d$ is the decision rule. $S$ is the risk set. The thickened black line is the set of admissible decision rules; the points (black dots) on set $S$ are non-randomised decision rules.

Source: Essentials of Statistical Inference by Young, Smith.
Comment: The minimax solution does not have to lie along the line of equal risk unless the line of admissible procedures is concave.  You might want to sketch some of the contours of maximal risk on this plot: that is, draw contours of the function $f(R_1,R_2)=\max(R_1,R_2)$. Where in $S$ is the lowest contour going to be?
Comment: @whuber I'm don't think they give me a way to compare different risks. This example was taken from the following book in page 12.

http://faculty.ksu.edu.sa/mahdy/stat%20cources/Cambridge%20University%20Press%20-%20Essentials%20of%20statistical%20inference.pdf
Comment: I don't understand that comment.  If the coordinate axes in this image aren't risks, then what do you take them to be?
Comment: @whubber Please disregard my last comment. I now understand that the lowest contour is going to be on the line, at the cross. Many Thanks ;)
Answer: This warrants delving into an elaboration in a general setup:
$\delta_0$ is minimax if
$$\sup_{\theta\in\Theta} R(\theta, \delta_0) = \inf_{\delta\in D^\ast}\sup_{\theta\in\Theta}R(\theta, \delta).\tag 1\label 1 $$
Let $\Theta := \{\theta_1, \ldots, \theta_k\} ;$ let $S\subset \mathbb R^k.$ So,  each component of a point $\langle y_i\rangle_{i=1}^k\in S$ would correspond to $y_i = R(\theta_i, \delta) $ for some $\delta\in D^\ast.$
Assume $S$ does have its boundary points.
Define for $c\in \mathbb R,~Q_c:= \{\mathbf y: y_i\leq c\};$ all $\delta$'s corresponding to $S\cap Q_c$ are equivalent in the sense that $\max_i R(\theta, \delta) = c.$
The minimax risk is the infimum of such $c$'s, say, $c_0.$ Then the minimax rules would be associated with $S\cap Q_{c_0}.$ The diagonal $y_1 = \cdots=y_k$ is not special; minimax point might or might not lie on it:
$\bullet$ Minimax point on diagonal line:

Notice the minimax risk $c_0$ and the corresponding decision rule $\delta_0$'s minimax point is a boundary point of $S$ and lies on the diagonal line.
$\bullet$ Minimax points not on diagonal line:

Notice the minimax points are not lying on the diagonal line. There is nothing special about this line.

Reference/Figure Source:
$\rm [I]$ Mathematical Statistics: A Decision theoretic Approach, Thomas S. Ferguson, Academic Press, $1967,$ sec. $1.7,$ pp. $38-39.$


FragmentActivity em tab swiper

Question: Eu não estou conseguindo inserir um FragmentActivity para tab swiper:
@Override
    public Fragment getItem(int position) {
        switch (position) {case 0:
            return new HomeActivity();
        case 1:
            return new ListaBancada();

        }
        return null;

    }

a classe é HomeActivity herda de Fragment, a ListaBancada FragmentActivity e a ListaBancada dá erro no código acima, porque?
Como chamar uma Activity aí?
Comment: Não dá pra chamar. O método `getItem()` retorna um `Fragment`, o que é diferente de `FragmentActivity`, que apesar de ser uma activity que suporta conter fragments, ainda assim é uma activity e não um fragment. Fragments são uma coisa, activities são outra.
Comment: Uma activity pode conter fragments, não o contrário. Você terá que converter sua activity em um fragment e usá-lo no switch.
Comment: E eu posso chamar essa activity dentro do fragment. o fato todo é que eu tenho uma Activity pronta e quero colocar no lugar desse fragment
Comment: Ok Piovezan! vou ter que me aprofundar mais nisso muito obrigado mais uma vez.
Comment: Sem problemas. Postei uma resposta à sua pergunta para você aceitar.
Answer: Não dá pra chamar. O método getItem() retorna um Fragment, o que é diferente de FragmentActivity, que apesar de ser uma activity própria para conter fragments, ainda assim é uma Activity e não um Fragment. Fragments são uma coisa, activities são outra.
Uma activity pode conter fragments, não o contrário. Você terá que converter sua activity em um fragment e usá-lo no switch.

FragmentActivity em tab swiper


Show old price with line-through

Question: I have Drupal 7, without Drupal Commerce modules installed, because we are nor e-commerce place. For some items, we need to show up two prices (old_price and new_price). Only for items for new_price filled I need to show up old_price line-trough or with an X on top. I suppose that I need to put some code in someplace, but where?
I have been looking for a module, but all modules are for commerce. I do not want to install commerce and all the pile of commerce modules just to add this feature.
Answer: First, create two fields-"Old price" and "new price". Second, use css text-decoration:line-through; on the old price field.
Edit:
Based on your comment and clarification, I would suggest using rules and rules bonus pack to look for the "new price field", then have it add a body class to the node.
Your rule will look something like

Event #1: "when content is created"
Event #2: "when content is updated"
Condition #1: "entity has field", then select your "new price" field
Condition #2: "Data value is empty" and enable "negate"
Action: "Add body class"

Then in your css add the strikethough based on the extra body class.
This is essentially how the Commerce price savings formatter module works, but without the overhead of using commerce.
Comment: yes I know ...I did it, But I need old-price line-through only if we have new price.
Comment: It works, except the line-through, the color works but not the line,   .field-name-field-price{
 text-decoration: line-through;
 color: red;
}
weird... any ideas?
Comment: I would have a link to see the site to determine it.
Comment: well is modernism.com,  but I am working on a test site.. not real site.. but if you go to modernism.com we would like this action at  item price... just click on an item with price..
Comment: this is a good example... but the rule is not in production..  http://modernism.com/items/39/chandeliers/150-93-french-art-deco-wrought-iron-twist-chandelier
Comment: I'll need to see it with the rule in place to inspect the html
Comment: 184.108.40.206    test.modernism.com
add this line to your hosts file and go to test.modernism.com
Comment: take a look here   http://test.modernism.com/items/84/architectural/1510-1308-vintage-advertising-metal-neon-sign-letters-grace
Comment: I can see but you'll need to either allow anonymous users to see prices or give me a password. it prompts me to login to see the price.
Comment: it's ok I just created an acccount
Comment: just log in as a visitor..
Comment: what is the body class that is being added by rules?
Comment: I can't see an newly added body class from rules, so I am not sure it is firing. but your css should be .rules-body-class .field-name-field-price .field-item{text-decoration:line-through;}
Comment: ok.. so  I need to add .rules-body-class to the css... let me see if works
Comment: Whatever you added through rules to apply the body class. However I see that rules isn't doing that as I don't see any custom body classes added
Comment: yes...  please, let me know how can I add this classes? special css file name? my theme is adaptivetheme..  I have no style.css file, I have been doing this on field.css file... well I am lost now.. thanks for your help..
Comment: Did you even create the rule? Assign me admin rights to my recently created account and ill take a look on the back end.
Comment: rule is done... see the message on top "... BE CAREFULL....This Item is ON SALE" it come from the rule...
Comment: you are right, I have no added body class,  so I just added.. the name is strike-out-price,,, for now only strikeout is a message on top... so how can I redirect strikeout the old-price?
Comment: my email is email@example.com if you want to cntinue your help.... Thanks!!!
Comment: now I see the body class by rules. now just add .strike-out-price .field-name-field-price .field-item{text-decoration:line-through;} in your css
Comment: NICE  !!!! WORKS!!! almost Done... finally the price is strikeout, but shows up all prices strikeout even prices without sale price..
Comment: Then your rule is setup incorrectly. I'll need access to edit the rule on the backend
Answer: Or you could use the module that does this formatting for you.

Show old price with line-through


Why is this span column being offset?

Question: I'm developing a website with Twitter bootstrap, a screenshot is
This sometimes happens and I've not managed yet to nail the exact circumstances... Sometimes I try to nest a
 using row-fluid but I get the results shown in the screenshot.
The child span6 div has a left-margin I can't seem to get rid of.
I would like to be able to nest two span6
 inside that row-fluid
... It should be possible, no?
Comment: Do you want the community to debug your markup by the screenshot? Provide a fiddle or the code at least.
Comment: I thought it would be some simple silly mistake I was making... but ok.
Comment: I'll try and reproduce the issue on a simple jsfiddle... But I was really this was a very common mistake a lot of people do and **someone would come over and say**: *ah, I've had it happen to me many times, you just need to blah blah blah*
Answer: To build the layout inside a .row-fluid, Bootstraps applies to every .spanN a margin-left:
.row-fluid [class*="span"] {
    margin-left: 2.76243%;
}

And then, it overrides this property to the :first-child:
.row-fluid [class*="span"]:first-child {
    margin-left: 0;
}

As you are including that
 before the first .span6, it becomes the second element and :first-child selector doesn't affect it.
So, to solve your issue, get that heading out of the .row-fluid where you place your spans.
Answer: I think I've found out the answer.
The culprit was that
 heading within the parent div but outside the children divs.

Why is this span column being offset?


Thumbnail Control

Question: Hi all i need to design a control that has a thumbnail views of picture.it can take list of pictures.i need it in wpf.is there any pre existed library of control?
if no how can i design i have no idea
Thanks
was looking something like http://www.codeproject.com/KB/graphics/crystal_image_grid_viewer.aspx?msg=3290254
Answer: do you want to show all the images of the list at the same time? I believe you can use the grid and put a picture control in any cell of the grid, you can start with this approach, post your results and ask more specific questions once you have it at least partly done.
Comment: was looking something like http://www.codeproject.com/KB/graphics/crystal_image_grid_viewer.aspx?msg=3290254
Answer: If you have a list of pictures you can place a panel (StackPanel, WrapPanel, etc., depends on the behaviour you want) inside a ListBox. Set the panel to be the items host, and set the list of pictures as the ItemsSource.  Something like this:
<ListBox x:Name="_listBox" >
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Horizontal" IsItemsHost="true" />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
</ListBox>

and then in the code behind set _listBox.ItemsSource to your list of pictures.
(or you can have your list of pictures in an ObservableCollection and bind the ListBox to it)
EDIT: as for the thumbnails you can use something like:
BitmapImage Picture = new BitmapImage();
Picture.BeginInit();
Picture.UriSource = ... // your picture
Picture.DecodePixelWidth = ... //how big you want your pic
Picture.EndInit();

Comment: that is really helping.i need user to be able to click them and when they click them the other control shows it in bigger size.
Secondly ItemsSource requires collection how to make it?
Comment: if you have a List _imageList = new List(); with your pictures all you need is to set _listBox.ItemsSoure = _imageList;
Comment: as for the other control to show the bigger sized image, you'll need to check the ListBox.SelectedItem ou ListBox.SelectedIndex to find which picture was selected, and display its full size

Thumbnail Control


Converting JSON object to dictionary

Question: I'm calling the ethplorer.io api, and it returns the below json. I have generated the classes in visual studio via 'paste special -> paste json as classes'. My problem is that Tokeninfo declares price as an object, this is because it can either be false if it has no price information, or a dictionary if it has values. While I have successfully deserialised the response using JsonConvert.DeserializeObject(rawJSON),  I'm struggling to convert price in to c# dictionary if it has values.
public class Tokeninfo
{
    public string address { get; set; }
    public string name { get; set; }
    public object decimals { get; set; }
    public string symbol { get; set; }
    public string totalSupply { get; set; }
    public string owner { get; set; }
    public long lastUpdated { get; set; }
    public int issuancesCount { get; set; }
    public int holdersCount { get; set; }
    public object price { get; set; }
    public string description { get; set; }
    public float totalIn { get; set; }
    public float totalOut { get; set; }
}

JSON response:
{
  "address": "0xd8f41f341afe2c411b21b3f96263c6584b69baeb", //Not my address
  "ETH": {
    "balance": 762.13611095505,
    "totalIn": 1040.0907032491,
    "totalOut": 277.954592294
  },
  "countTxs": 22,
  "tokens": [
    {
      "tokenInfo": {
        "address": "0x355a458d555151d3b27f94227960ade1504e526a",
        "name": "StockChain Coin",
        "decimals": "18",
        "symbol": "SCC",
        "totalSupply": "10000000000000000000000000000",
        "owner": "0x",
        "lastUpdated": 1524401998,
        "issuancesCount": 0,
        "holdersCount": 86520,
        "price": {
          "rate": "0.0531126",
          "diff": 4.8,
          "diff7d": 19.82,
          "ts": "1524400762",
          "marketCapUsd": null,
          "availableSupply": null,
          "volume24h": "622004.0",
          "currency": "USD"
        }
      },
      "balance": 5000000000000000000,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0xb679afd97bcbc7448c1b327795c3ef226b39f0e9",
        "name": "Win Last Mile",
        "decimals": "6",
        "symbol": "WLM",
        "totalSupply": "2000000000000000",
        "owner": "0x8e7a75d5e7efe2981ac06a2c6d4ca8a987a44492",
        "lastUpdated": 1524362946,
        "issuancesCount": 0,
        "holdersCount": 10945,
        "price": false
      },
      "balance": 66000000,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0xae66d00496aaa25418f829140bb259163c06986e",
        "name": "Super Wallet Token",
        "decimals": "8",
        "symbol": "SW",
        "totalSupply": "8400000000000000",
        "owner": "0xba051682e9dbc40730fcef4a374e3a57a0ce3eff",
        "lastUpdated": 1524401948,
        "issuancesCount": 0,
        "holdersCount": 30276,
        "price": false
      },
      "balance": 11567900,
      "totalIn": 0,
      "totalOut": 0
    },
    {
      "tokenInfo": {
        "address": "0x8e4fbe2673e154fe9399166e03e18f87a5754420",
        "name": "Universal Bonus Token | t.me/bubbletonebot",
        "decimals": "18",
        "symbol": "UBT",
        "totalSupply": "1150000000000000000000000",
        "owner": "0xc2db6e5b96dd22d9870a5ca0909cceac6604e21d",
        "lastUpdated": 1524393745,
        "issuancesCount": 0,
        "holdersCount": 99896,
        "price": false
      },
      "balance": 10000000000000000000,
      "totalIn": 0,
      "totalOut": 0
    }
  ]
}

Comment: Possible duplicate of [How to convert object to Dictionary in C#?](https://stackoverflow.com/questions/11576886/how-to-convert-object-to-dictionarytkey-tvalue-in-c)
Comment: You already used copy-paste option, What code you have tried ?
Answer: You need a custom deserializer to do what you want. It should be straight forward though. Here is some code which checks if the price is not false and then turns it into a Dictionary<string, string>. This code makes the assumption that your root object is named RootObject:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
    var jsonObject = JObject.Load(reader);
    var root = default(Rootobject);

    // Let's go through each tokenInfo and check if price is not false
    // so we can turn it into a dictionary.
    foreach (var thisToken in root.tokens)
    {
        if (thisToken.tokenInfo.price.ToString() != "false")
        {
            thisToken.tokenInfo.price = JsonConvert.DeserializeObject<Dictionary<string, string>>(thisToken.tokenInfo.price.ToString());
        }
    }

    serializer.Populate(jsonObject.CreateReader(), root);
    return root;
}

Please see the full example here and search for ProfessionConverter in that link for the full class.
Answer: I think it is not very good approach to use false in cases when there is no price. If there is no price it should be something like "price" :{} or price element shouldn't be there at all. In other words, it is not good idea to mixup boolean object and dictionaty imho.
I think you can use provided by VisualStudio class where Price is an object. And you can create a custom serializer which will treat false as an null (or object with empty fields) along with standart deserialization mechanism.

Converting JSON object to dictionary