JavaScript hasOwnProperty vs typeof

Question: I've searched a lot on Google but couldn't found where I was looking for:
Benefit of using Object.hasOwnProperty vs testing if Property is undefined
jsperf speedtest
How to determine if Native JavaScript Object has a Property/Method?
.. and a lot of other websites, but this is not where I am looking for. My real question is:
Why does hasOwnProperty not find a method in his super class(prototype)? And why does somebody even use hasOwnProperty? It's much slower than typeof and it doesn't work if you are working with inheritance.
.. second question:
In this question Barney answers that you have to use if ('property' in objectVar) to check if a property exists, but doesn't explain why. Does someone knows why you would use this structure?
var objA = function(){};

objA.prototype.alertMessage = function(){
        return 'Hello A';
};

var objB = function(){
    this.hello = function(){
        return 'hello';
    };
};

// Inheritance
objB.prototype  = Object.create(objA.prototype);
objB.prototype.constructor = objA;

var test = new objB();

if (test.hasOwnProperty("alertMessage")){
    console.log("hasOwnProperty: " + test.alertMessage());
}

if (typeof test.alertMessage === "function"){
    console.log("typeof: " + test.alertMessage());
}

if (test.hasOwnProperty("hello")){
    console.log("hasOwnProperty: " + test.hello());
}

if (typeof test.hello === "function"){
    console.log("typeof: " + test.hello());
}

Check out the jsFiddle
Comment: `typeof` and `hasOwnProperty` are not related. The `in` operator is used to check for properties in the prototype chain, while `hasOwnProperty` checks only directly on that object. If you care about performance with `typeof`/`hasOwnProperty`, the fastest way is probably to simply use the evaluated value (since `undefined` evaluates to `false`), e.g. `if(test.alertMessage)`
Answer: There are a number of reasons why one uses (and in some cases has to use) hasOwnProperty, and why its behavior is what it is:

As the name suggests, hasOwnProperty checks if the object on which you test owns a property with a given name. If it has inherited a method/property from another object (its prototype), then the owner of that property is not the object, but its prototype. Therefore, the object doesn't have its own property called X
typeof will work most of the time, but an object can look like this: var o = {foo: undefined}. Using typeof on o.foo will yield "undefined", of course, but the object does own a property called foo
using if ('properyname' in object) is a workaround, that combines the best of both worlds: in case of o = {foo: undefined}; it will evaluate to true, without the overhead of a lookup for the hasOwnPropery method (which is a property of Object.prototype), or a function call with context binding and all that. It will also find properties in the prototype chain

So consider these examples:
var o = {foo: undefined,
    toString: undefined};//overwrite inherited method
console.log(typeof o.foo);//undefined
console.log(typeof o.toString);//undefined
console.log(o.hasOwnProperty('toString'));//true
delete(o.toString);
console.log(typeof o.toString);//function
if ('valueOf' in o)
    console.log(o.valueOf === Object.prototype.valueOf);//true
if ('foo' in o)
    console.log(o.foo);//undefined

Another important thing to note is that your statement about hasOwnProperty not working when dealing with inheritance is just plain wrong. Every object you use in JS inherits from at least one prototype. It is important to realize, understand and respect this. If you loop over an object, it is recommended to make sure you're actually iterating over the properties that belong to the object itself. Hence, this is not uncommon to see:
for (p in obj)
{
    if (obj.hasOwnProperty(p))
        //process property
}

This is to avoid having code that iterates over all properties in the prototype chain, an possibly mucking up the super object
if (!Object.prototype.hasProperty)
{//dirty check ;-P
    Object.prototype.hasProperty = (function(OP)
    {
        return function(name)
        {
            //typeof for speed: if value is not undefined, return true
            if (typeof this[name] !== 'undefined' || this.hasOwnProperty(name))
                return true;
            if (this === OP)//we've just checked the Object.prototype, found nothing, so return false
                return false;
            return Object.getPrototypeOf(this).hasProperty(name);//check prototype
        };
    }(Object.prototype));//OP is object prototype
}

Comment: Thank you to clarify this! The first point is clear, but it would make more sense if they would add a `hasProperty` method ;) The rest of you answer seems fine and I wasn't aware of the `undefined` 'trick'. Thank you for pointing that out!
Comment: @GuyT: you could implement a `hasProperty` method, that uses `Object.getPrototypeOf` to traverse through the prototype chain, until `hasOwnProperty` returns true, or `false` at the `Object.prototype` level
Comment: Hmm.. that seems a nice implementation! I will check it out. Thanks.
Comment: @GuyT: Added a possible implementation of `hasProperty` to my answer

JavaScript hasOwnProperty vs typeof


Active Directory - search by specifying a search filter and search controls and no context

Question: I followed this tutorial to search in active directory.
Sample code :
class SearchSubtree {
  public static void main(String[] args) {

    Hashtable<String, Object> env = new Hashtable<String, Object>(11);
    env
        .put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://localhost:389/o=JNDITutorial");

    try {
      DirContext ctx = new InitialDirContext(env);

      String[] attrIDs = { "sn", "telephonenumber", "golfhandicap", "mail" };
      SearchControls ctls = new SearchControls();
      ctls.setReturningAttributes(attrIDs);
      ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

      String filter = "(&(sn=Geisel)(mail=*))";

      NamingEnumeration answer = ctx.search("", filter, ctls);

      // Print the answer
      ctx.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

But NameNotFoundException is thrown at
NamingEnumeration answer = ctx.search("", filter, ctls);
But when I pass, "DC=extldap,DC=com" as first argument, code works fine.
Is there any issue with the tutorial? Can first argument not be empty string? Or is this a limitation with Active Directory?
Answer: Generally speaking, for LDAP servers you always need a root context to start your search from. Basically, you are doing the equivalent of trying to search a SQL database without specifying a database or table name.
Some server implementations may allow an empty context (I know iPlanet used to allow it in some cases) but these are exceptions to the rule.
The javadoc for DirContext.search() says:

Searches in the named context or object for entries that satisfy the
  given search filter. Performs the search as specified by the search
  controls.
See search(Name, String, SearchControls) for details.
Parameters:

name the name of the context or object to search

...

Usually, in Active Directory it is fine to start searching from the domain root, which is always DC=<your>,DC=<domain>.
That is why your second search works.
Comment: But this works for OpenDJ. Is there some difference between OpenDJ and AD?
Comment: OpenDJ is a descendant of iPlanet afaik. That implementation did allow an empty root. Come to think of it, eDirectory also allows that. Maybe AD is more of an exception than I thought.


How to apply Xamarin Platform-Specific EnableTranslucentNavigationBar

Question: I'm testing out Xamarin Forms's new Platform-Specifics features (in 2.3.3). In particular, the EnableTranslucentNavigationBar.
I have a RootPage object that is a MasterDetail. The Detail is a NavigationPage. Here's my relevant App() ctor code:
public App()
{
    InitializeComponent();

    //Note: RootPage is MasterDetail, Detail is NavigationPage
    var rootPage = new RootPage();
    (rootPage.Detail as NavigationPage).On<iOS>().EnableTranslucentNavigationBar();
    MainPage = rootPage;
}

This however is not applying the translucent navigation bar effect on the NavigationPage. It is still a solid color (default white) and the content doesn't scroll up
Is there a specific place/time I need to apply this?
Side Note: While working on this, I also noticed a weird ambiguity between two different NavigationPage objects. One in Xamarin.Forms.NavigationPage and one in Xamarin.Forms.PlatformConfiguration.iOSSpecific.NavigationPage. I eventually got the method to use the former, but it made me think that I might need to cast it first...
UPDATE:
Xamarin reports this should be fixed in 2.3.4-pre1
Comment: An additional side-question: Does the translucency have a "frosted glass" effect and does it extend to the edges of the screen?
Answer: Xamarin has confirmed this is an issue in Xamarin.Forms 2.3.3 and are investigating. Go here to see the Bugzilla report.
I will update this post once I hear back from them regarding a fix or workaround.
UPDATE
Should be fixed in 2.3.4-pre1


Proving that $\lambda$ is not analytic in differential topology.

Question: Let $\lambda : \mathbb{R} \to \mathbb{R}$ be defined by
$\lambda(t) =\begin{cases}
 0, & \text{for } t \leq 0 \\
 e^{-1/t}, & \text{for } t > 0.
\end{cases}$
This is a smooth function with values between zero and one. Note that all derivatives at zero are zero: the McLaurin series fails miserably and $\lambda$ is definitely not analytic.
My question is why the McLaurin series fails miserably? and how this leads to that $\lambda$ is not anaytic? and what does it mean for $\lambda$ to be analytic in this context? Is the notion of analytic function in differential topology different from its meaning in complex analysis?
Answer: If $\lambda$ were to be real-analytic, then there would be $\epsilon>0$ such that $$\lambda(t) = \sum_{k\geq 0} \frac{\lambda^{(k)}(0)}{k!}t^k$$whenever $|t|<\epsilon$, with uniform convergence of that series. But if all derivatives vanish, the series is the zero series. And $\lambda(t)>0$ whenever $t>0$, which would be a contradiction. Being real-analytic is stronger than being $C^\infty$ and this $\lambda$ is the classical example.
Answer: For "analytic", you should read "can be written as a power-series". This is equivalent to being holomorphic (complex-differentiable on an open set) in a complex analysis setting, but is also a sensible definition when you're doing real analysis (or differential topology/geometry).
The Maclaurin series "fails miserably" because all the function's derivatives are zero. Thus the Maclaurin series of the function is the zero series, so it definitely does not converge to $\lambda$. If $\lambda$ has a power series expansion at $x=0$, then that power series must be the Maclaurin series of $\lambda$. So $\lambda$ is not analytic (has no power series expansion) at $x=0$.


Bartle's Modern theory of integration, theorem 9.1

Question: Bartle's book, Modern theory of integration, focuses on Henstock-Kurzweil integrals, where $\mathcal{R}^*(I)$ denotes the set of Henstock-Kurzweil integrable functions on $I = [a, b]$.
Also, $\mathcal{M}(I)$ denotes the Lebesgue measurable functions on $I$, defined as almost sure limits of step functions.
A step function $s:I\to \mathbb{R}$ is a function for which there exists $x_0 = a < x_1 < ... < x_n = b$ such that $s$ is constant on $(x_i, x_{i+1})$ for $i = 0, ..., n-1$. But $s(x_i)$ can be defined however we like.
$\text{mid}(a, b, c)$ for $a, b, c\in\mathbb{R}$ denotes middle value of $a, b, c$, that is if for example $a \leq b \leq c$, then $\text{mid}(a, b, c) = b$.
Similarly, if $f, g, h$ are functions, then $\text{mid}(f, g, h)(x) := \text{mid}(f(x), g(x), h(x))$.
Theorem $9.1.$ If $\alpha \leq f \leq \omega$ and $\alpha, \omega\in\mathcal{R}^*(I)$, $f\in \mathcal{M}(I)$, then $f\in\mathcal{R}^*(I)$.
Proof: Let $s_k\to f$ almost surely and $g_k = \text{mid}(\alpha, s_k, \omega)$. Then $g_k\in\mathcal{R}^*(I)$, $\alpha\leq g_k\leq \omega$ and $g_k\to f$ almost surely, so from dominated convergence theorem $f\in\mathcal{R}^*(I)$. $\square$

My doubts about above proof: How do we know that $g_k\in \mathcal{R}^*(I)$?
In exercise $8.R$ I had the same issue, and Bartle suggested to use this theorem:
Theorem $7.13.$ Suppose $f, g, \alpha, \omega\in\mathcal{R}^*(I)$.

If $f, g\leq \omega$ then $f\land g, f\lor g\in\mathcal{R}^*(I)$.

If $\alpha\leq f, g$ then $f\land g, f\lor g\in\mathcal{R}^*(I)$.

However, I don't see how to apply the above theorem to show that if $\alpha\leq \omega$ and $\alpha, g, \omega\in\mathcal{R}^*(I)$, then $\text{mid}(\alpha, g, \omega)\in\mathcal{R}^*(I)$.
Answer: If $\alpha\leq f \leq \omega$, set $f_1 := f-\alpha$ and $\omega_1 = \omega-\alpha$ so that $0 \leq f_1 \leq \omega_1$ where $\omega_1 \in \mathcal R^*(I)$. Since $f=f_1+\alpha$ it suffices to show that $f_1 \in \mathcal R^*(I)$. Take a sequence $(s_n)$ of step functions with $s_n(x) \to f_1(x)$ for a.e. $x \in I$. Now $0\leq s_n^+(x)$ and $0\leq f_1(x)$ for a.e. $x \in I$ hence, replacing $s_n$ by $s_n^+$ we may assume $s_n\geq 0$ for all $n \in \mathbb N$.
Now it follows that $\omega_1$ and $s_n$ are bounded above by $\omega_1+s_n \in \mathcal R^*(I)$, and so by 7.13, $r_n = \min\{\omega_1,s_n\} \in \mathcal R^*(I)$, and clearly $r_n(x) \to f_1(x)$ as $n\to \infty$ for a.e. $x\in I$. Now since $\omega_1\in \mathcal R^*(I)$, dominated convergence shows that $\lim_{n\to \infty} r_n =f_1 \in \mathcal R^*(I)$.
Comment: Post-commentary: Note that $f_1 \in\mathcal{M}(I)$ since $\alpha\in \mathcal{R}^*(I)\subseteq\mathcal{M}(I)$.


Solving system of equations with fraction

Question: I am having difficulties solving the following system :
$u \neq t$ and $(t, u) \in \mathbf{R} - \{-1, 1\}$
$\frac{t}{t^2-1}-\frac{u}{u^2-1}=0$
$\:\frac{t^2}{t-1}-\frac{u^2}{u-1}=0$
I tried expanding everything, but I still can't achieve anything
$\frac{tu^2-t-ut^2+u}{\left(t^2-1\right)\left(u^2-1\right)}$
$\frac{t^2u-t^2-u^2t+u^2}{\left(t-1\right)\left(u-1\right)}$
also tried the hint below, ending up finding one equation with the two variables $t(t+1) = u(u+1)$ ... and $u \neq t$
Any idea ?
Comment: It is a quadratic equation in $t$, which you can solve.
Comment: @nginx9101 Show please how you made this expanding.
Answer: Hint
$$\dfrac{\dfrac{t^2}{t-1}}{\dfrac t{t^2-1}}=?$$
$$\implies t(t+1)=u(u+1)$$
But $u\ne t$
Comment: I don't get what you are trying to do?.. Details please?
Comment: @nginx9101, replace the values of the numerator and denominator
Comment: well yes, but your reasoning isn't complete yet. What to do after ? I end up having 2 variables which I can't solve
Answer: $$
\begin{cases}
    \frac{t}{t^2-1}-\frac{u}{u^2-1}=0 \\
    \frac{t^2}{t-1}-\frac{u^2}{u-1}=0 \\
\end{cases}
\begin{array}{c}
    \overset{\times(t^2-1)(u^2-1)\ne0}{\longrightarrow} \\
    \overset{\times(t-1)(u-1)\ne0}{\longrightarrow}\\
\end{array}
\begin{cases}
    t(u^2-1)-u(t^2-1)=0 \\
    t^2(u-1)-u^2(t-1)=0 \\
\end{cases}
$$
$$
\Rightarrow
\begin{cases}
    tu^2-t-ut^2+u=0 \\
    t^2u-t^2-u^2t+u^2=0 \\
\end{cases}
\Rightarrow
\begin{cases}
    tu(u-t)+u-t=0 \\
    tu(t-u)-(t-u)(t+u)=0 \\
\end{cases}
$$
$$
\Rightarrow
\begin{cases}
    (u-t)(tu+1)=0
    \begin{cases}
        u-t=0 \Rightarrow u=t \text{ incorrect} \\
        tu+1=0 \Rightarrow tu=-1 \\
    \end{cases}\\
    (t-u)(tu-(t+u))=0
    \begin{cases}
        t-u=0 \Rightarrow u=t \text{ incorrect} \\
        tu-(t+u)=0 \Rightarrow tu=t+u \\
    \end{cases}
\end{cases}
$$
$$
\Rightarrow
\begin{cases}
    tu=-1 \\
    t+u=tu \\
\end{cases}
\Rightarrow
\begin{cases}
    tu=-1 \\
    t+u=-1 \\
\end{cases}
\Rightarrow
u^2+u-1=0
\Rightarrow
\text{...}
$$


In what key signature is singing written in, and how do I adapt for alto saxophone?

Question: Note: I am not that good in general music theory but I will try to get my point across as best as I can.
I am currently in charge of writing/transposing the scores of a little hobby band.
I got the scores written for singing and now I need to transpose it for an Alto-Saxophone. The singing has one ♭ so it is either D-Minor or F-Major.
What accidentals (I hope that is the right word) do I have to use when rewriting it for Saxophone and where can I look up which instruments have what signature?
Answer: TL;DR (the specific answer)
Your voice part's key signature has one flat. The corresponding alto saxophone key signature will have two sharps.

The general answer
Voice is written in what is called "concert pitch". Concert pitch means that when you write an "A" (specifically, the "A" above "middle C") it is tuned to 440Hz. Instruments like voice, piano, and flute — so-called "C instruments" — are all written in concert pitch.
The alto saxophone is an "Eb instrument". This means that its written music and the "concert pitch" sound that results are not the same. When "C" is written in an alto saxophone part, the resulting concert pitch — the note a singer would sing to match the alto saxophone's "C" — is the Eb below.
Put another way, concert pitch — the actual sound produced in response to a written saxophone part — is a "major sixth" lower than the written note. And to produce a given concert pitch, the saxophone part must be written a major sixth higher.
Thus: D minor / F major becomes B minor / D major.
Comment: @gurkensaas Other way around: A written "C" for alto sax produces an "Eb" concert pitch. A "C" concert pitch would be a written "A" on the alto. (My answer before editing got the language backwards. My apologies for the confusion.)
Comment: @nuggethead Thanks. I got my "highers" and "lowers" swapped around halfway through the answer. Gets me every time.
Comment: @gurkensaas Yes. A concert Eb sounding pitch would be written as a C in the saxophone part. Said another way, if the singer is singing an Eb, then the alto sax would play its written C to match the singer.
Comment: If I change the key, do I also need to change the pitch the notes are at? So e.g. a C from concert pitch becomes an E♭ for the Saxophon or is that completely wrong?
Comment: The OP is not asking what reading F major sounds like when played on alto, rather how to write alto sax to GET it to sound in F major.
Comment: Some voice parts are written as an octave transposing instrument (Tenor voice reading treble clef)
Comment: @Edward I was going to say that! Although it never changes the key, obviously. Same as guitar and bass.
Comment: @Edward Separate tenor voice parts use (or at least, _should_ use) a [_suboctave_](https://en.wikipedia.org/wiki/Clef#Octave_clefs) treble clef — written with a subscript '8' to indicate the octave shift.  (Although commonly called a 'tenor clef', that's actually [something else](https://en.wikipedia.org/wiki/Clef#Tenor_clef).)  So not strictly transposing (when properly written).
Comment: @Aaron So do I have to change a "concert" E♭ to a "Saxophone" C?
Comment: *"Play a C, hear the key!"* works for all the transposing instruments @gurkensaas
Answer: The alto sax part needs to be written in the key of D Major (2 sharps).  The alto transposes, and It's sounding pitch is a major sixth below its written pitch.
When the vocals sing do-re-mi in F (notes F-G-A), the alto player must see this in D.  He/she will read D-E-F# and they will sound in F major.
To verify this, look at any concert band score.  The altos will always have three sharps more/three flats less than the flutes, which are in the "concert key."
Look at this score, in Bb with altos showing key of G.
Comment: Glad it proved to be helpful to you.  I'm not easily offended - lest I doubt I'd post on SE!!!
Comment: @David Conrad good point thank you!  I'll edit it.  I began with that because at the time of posting there were three upvoted answers, all incorrect.
Comment: Thanks a lot for your answer. I hope you're not too offended if I don't accept your answer since Aaron's answer is formatted more nicely and also came first.
Comment: Beginning your answer with "Sorry folks, but ..." doesn't make a lot of sense. Who are you apologizing to and why? Your answer would be better and clearer if you got rid of the preamble.
Comment: I think it's helpful that you gave the example of transposing DO RE MI.
Answer: Aaron's answer is correct. To simplify any future writing, the simple formula for E♭ alto is to add 3 sharps to the existing key signature. That's what happens writing for concert F major - add 3 sharps to become D major.
So, if the original concert key is 1 sharp, adding 3 sharps will take the key to that of 4 sharps. Original key 4 flats becomes 1 flat (adding a sharp = subtracting a flat).
Comment: FYI: I got turned around in my original answer. It's corrected now, but yours will need an update as well. Add 3 sharps, not flats.
Comment: @Aaron - thanks so much. I'd just got back from a gig, and spent a bit of time pondering if I'd gone the right way. Obviously not. Would you like to proof-read again? Hope it makes sense. Don't know how it got uv, and dv didn't give a reason...
Answer: If you are going to do this a lot, I strongly suggest you shell out the cash for a music writing software. I won't recommend one, I haven't done this for years.
A good one can scan your sheet music, then you can grab the notes with the mouse and transpose them by just pushing, or use the built in functions. You still have to adjust it by hand, but it will save you an awful lot of time, and it also formats and prints the music nicely for you.
It is not too much money, and I see the licence for mine is still valid, so it gets updated now and then.
Comment: Most music software will transpose automatically, and there are a variety of very good free programs. I use MuseScore and have been very happy with it.
Comment: Oh, that's good. Maybe I need a new one. but I haven't used it for so long. These days I manage to transpose in my head...
Comment: I already have Logic Pro X(200$), where I already learned most of the score UI. I have no real interest in spending more money on something that can do the job a little better and then I have to relearn its UI.


I can't use strong tag in wysiwyg

Question: I watch Introduction Advanced Theming in Drupal 7 (drupalize.me), and I create custom theme frot that video tutorial. I can't use  and  in CkEditor. I can use only  and <l>, but CkEditor create  and . That tags has no effect when I save my node.
Why? What is wrong? When I change the theme to Bartic, everything works OK, but in the custom theme from that video tutorial, those two tags are not rendered as I would expect.
Answer: CSS resets usually take the emphasis off of  and  tags by default.
All you need to do is add a rule like this to your main style sheet (main.css):
strong {font-weight: bold;}
em {font-style: italic;}

That will re-reset the  and  tags to display as you'd normally expect.
Comment: Tnx Clive!!!!!!
Comment: @Martins Happy to help :)

I can't use strong tag in wysiwyg


Passar valores de uma classe ao gerar um pdf em JavaFX

Question: Boa tarde, criei um PDF.java, que tem como função gerar um pdf, e em outro arquivo(FormularioHoteleriosController.java) ao clicar em um determinado botão, eu instancio o arquivo PDF.java para poder gerar e abrir o pdf, porém, eu necessito que quando eu clicar no botão que encontra-se no FormularioHoteleriosControler.java, resgate valores de EditText's localizados no mesmo, e então, imprimir os resultados no PDF. Obrigado!!
ARQUIVO QUE GERA O PDF:
public class Pdf {
public static final String IMAGE = "imagens/boleto.png";
public static final String DEST = "results/images/boleto.pdf";

public static void main(String[] args) throws IOException, DocumentException {
    File file = new File(DEST);
    file.getParentFile().mkdirs();
    new Pdf().createPdf(DEST);
}
public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document(PageSize.A4.rotate());
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();

    PdfContentByte canvas = writer.getDirectContentUnder();
    Image image = Image.getInstance(IMAGE);
    image.scaleAbsolute(PageSize.A4.rotate());
    image.setAbsolutePosition(0, 0);
    canvas.addImage(image);
    document.close();

    Desktop.getDesktop().open(new File("results/images/boleto.pdf"));
}

}
ARQUIVO QUE CHAMA INSTANCIA O PDF.AJVA AO CLICAR NO BOTÃO:
@FXML public void gerarPdf(){

    try {
        Pdf.main(null);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Comment: Sua pergunta está confusa, mais uma coisa me confunde mais ainda: seu código tem duas classes com main?? Porque o JavaFX cria uma Classe main e um Controlador.
Comment: olá Gustavo, eu não entendi sua observação, duas classes com main?
Comment: Estou tentando resgatar valores preenchidos em um EditText, localizado no arquivo que instancia o pdf para ser gerado. E então, apresentá-los no pdf gerado.
Comment: Sua classe PDF tem um public static void main(String[] args) e a classe do principal do javafx tem outra public static void main(String[] args) {
        launch(args);
    }
Comment: Entendi, mas isso impedi que eu consiga realizar o esclarecido?
Comment: Do ponto de vista da programação é incorreto.
Answer: Sugiro que você crie uma janela modal para exibir seu PDF. Primeiro vamos corrigir sua classe de geração de PDF seguindo as boas práticas de programação em Java:
public class GeradorPdf {

    private String source;
    private String destination;

    // Construtor da Classe
    public GeradorPdf(String source, String destination) {
        this.source = source;
        this.destination = destination;
    }

    // Não mexi neste método mas você poderia retornar a Image gerada
    // para uma classe VisualizadorPdf
    public void createPdf() throws IOException, DocumentException {
        Document document = new Document(PageSize.A4.rotate());
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(destination));
        document.open();

        PdfContentByte canvas = writer.getDirectContentUnder();
        Image image = Image.getInstance(source);
        image.scaleAbsolute(PageSize.A4.rotate());
        image.setAbsolutePosition(0, 0);
        canvas.addImage(image);
        document.close();

        Desktop.getDesktop().open(new File("results/images/boleto.pdf"));
   }

   // Encapsulamento dos atributos
   public String getSource(){
       return this.source;
   }

   public String getDestination(){
       return this.destination;
   }

   public void setSource(String newSource){
       this.source = newSource;
   }

   public void setDestination(String newDestination){
       this.destination = newDestination;
   }

Agora vou mostrar como se cria uma janela modal em JavaFX usando o FXML. Primeiramente vamos ter que criar uma variável global para seu Stage no método start da sua classe principal:
public static Stage stage;

@Override
public void start(Stage primaryStage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

    Scene scene = new Scene(root);
    stage = primaryStage;
    stage.setScene(scene);
    stage.show();
}

Agora a classe VisualizadorPdf (Janela Modal):
public class VisualizadorPdf {

    private final Stage dialog;
    private final Image image;
    // O resto de seus atributos (botões, paineis, etc);

    public VisualizadorPdf(Stage owner, Image image){
        this.image = image;

        dialog = new Stage();
        dialog.initModality(Modality.WINDOW_MODAL);
        dialog.initOwner(owner);
        dialog.setScene(createScene());
        dialog.setTitle("Título da minha janela");
    }

    public Scene createScene() {
        // Crie sua cena aqui
    }

    // Método para exibir sua janela
    public void show() {
        dialog.show();
    }
}

Se estiver sem ideias de como criar uma scene pode olhar este visualizador de pdf. Seria interessante passar a imagem do Gerador para o Visualizador, ou você pode unir os dois em uma classe só, isso depende de você.
Por fim o uso seria dessa forma:
@FXML
private TextField meutextfield;

// ...

@FXML
public void gerarPdf(){

    try {

        // Pegando valores dos TextField
        String valor = meutextfield.getText();

        GeradorPdf gerador = new GeradorPdf("imagens/boleto.png", "results/images/boleto.pdf");
        Image image = gerador.createPdf(); // Supondo que seguiu minha sugestão
        VisualizadorPdf visualizador = new VisualizadorPdf(SuaClasse.stage, image);
        visualizador.show();

    } catch (IOException | DocumentException e) {
        e.printStackTrace();
    }
}


How to disable the submit button after clicking?

Question: Drupal doesn't seem to prevent multiple form submits, even on node pages. This QA suggests fixing it on the server side.
How could I disable the submit button after clicking?
Any other solutions?
Comment: Doesn't Drupal's Form API prevent double-submitting thanks to its form token value check?  Can't submit a form with the same token twice?
Answer: It's only in dev but the Hide Submit module would do the trick. One of the features is:

Hide (or disable) the submit button after it has been clicked

I've just installed it on a dev site and it seems to work well for node add forms; when you click the submit button it's hidden and replaced with a loading image and a 'Please wait...' message, before the form is finally submitted. I haven't tried it on any other forms though.
Comment: Any idea on how to get the hide submit module to work on forms in your own custom modules?  I was hoping it would be site wide, but that doesn't appear to be the case.
Comment: @user785179 look how it implements `hook_form_alter()` - if it's using `hook_form_FORMID_alter()`, switch it to generic `hook_form_alter()`. If it is generic `hook_form_alter()` with if inside, add some `or`'s in this `if`.
Comment: Be careful with this solution - the hide submit module breaks ajax uploads, causes autocomplete problems, and in some cases causes the submit button to do nothing at all on the first click. I just had to uninstall it from a site.
Comment: @Jen Strange, I've been using it in dozens of sites for years without seeing any problems like that. Perhaps you have another module installed that interferes with it
Answer: Here is solution for Drupal 7. Code is simplified version of Hide Submit module.
This code works fine even with "Add more" buttons and AJAX forms.
Drupal.behaviors.hideSubmitButton = {
  attach: function(context) {
    $('form.node-form', context).once('hideSubmitButton', function () {
      var $form = $(this);
      $form.find('input.form-submit').click(function (e) {
        var el = $(this);
        el.after('<input type="hidden" name="' + el.attr('name') + '" value="' + el.attr('value') + '" />');
        return true;
      });
      $form.submit(function (e) {
        if (!e.isPropagationStopped()) {
          $('input.form-submit', $(this)).attr('disabled', 'disabled');
          return true;
        }
      });
    });
  }
};

Comment: I want to implement this in adminimal theme. Made a file sitename.js and copied above code into it. It is not working. Should I adjust things?
Comment: @Justme where did you put your sitename.js file? If in a module or subtheme you'll need to either add it into the .info file so it's loaded, or call drupal_add_js() somewhere else to get it on the page. Can you see it being added in the page source?
Comment: Thxs solved it. I did not knew that this should be between:  (function($) {   and })(jQuery); in the js file. Works like a sharm !!
Answer: The easiest way is to do a theme based javascript solution to disable the button after form submission. In the theme.info file, put your javascript file so it can be loaded by the theme api.
scripts[] = js/themename-script.js

Now in the themename-script.js add to the Drupal.behaviors.themename section to look like the following:
Drupal.behaviors.themename = function()
{
  $('.node-form').submit(function(){
    $('#edit-submit').attr("disabled", "disabled");
    $('#edit-preview').attr("disabled", "disabled");
  });
}

So the flow is as follows:

Theme loads the javascript
The Drupal.behaviors.themename is
fired on page load
On the form submission of the node add form (class based in the above example, it can be    customized on the type of form) disable the submit buttons (submit and preview) so it    cannot be clicked again

I am sure if there is some ajax processing that the above could be dangerous and the form submission could never be done again if an error is caught in the form_api validation so do test this and customize to meet your needs. I disabled both buttons since you could still click the preview button while the submit button was disabled. Obviously your milage my vary.
Comment: You're using the old `Drupal.behaviors` declaration style; it won't work for Drupal 7. It would need to be `Drupal.behaviors.themename = { attach: function (context, settings) { // ...`. See [Managing JavaScript in Drupal 7](http://drupal.org/node/756722) for more info
Comment: Declaration style fixed
Comment: What values should be replaced from this script 'node-form'?
Comment: I tried to get this working in adminimal theme but no luck. Rename themename with adminimal and copied the complete code in sitename.js and added this to theme info file. Still I get easily more submits of the same form.


How do you find a basis for the set of all $3 \times 3$ matrices whose rows and columns add up to zero?

Question: If $W$ is the set of all $3 \times 3$ matrices whose rows and columns add up to zero, how would you find a basis for this? There seem to be so many scenarios we'd need to cover, I can't find a way to succinctly find the answer / represent it well.
On a related note, how would you extend the basis to be a basis for $M_3(R)$? (I feel like I might be able to get this one, though, once I can clearly find a basis to begin with.)
Thanks in advance for the advice.
Comment: "a basis" in the body is correct; "the basis" in the title is wrong. The only vector space that has only one basis is $\mathbb F_2$.
Comment: Of course! Sorry - I just fixed that.
Answer: Douglas' observation that the upper left $2\times2$ submatrix determines the remaining values suggests another solution: We can take the canonical basis for $2\times2$ matrices and fill in the third row and column for each of its elements; the result is
$$
\pmatrix{
1&0&-1\\
0&0&0\\
-1&0&1},
\pmatrix{
0&1&-1\\
0&0&0\\
0&-1&1},
\pmatrix{
0&0&0\\
1&0&-1\\
-1&0&1},
\pmatrix{
0&0&0\\
0&1&-1\\
0&-1&1}\;.
$$
Comment: @Douglas: It also shows that your guess generalizes, since we can build all these by adding up some of your matrices.
Comment: It's kind of like sudoku.... neat. I guess you just need the intuition to see these things. Thanks!
Comment: That's even better!  In fact, this easily generalises to $n \times n$.
Answer: Guess: I guess this is a basis: $$
\left(
\begin{array}{ccc}
1 & -1 & 0 \\
-1 & 1 & 0 \\
0 & 0 & 0 \\
\end{array}
\right),
\left(
\begin{array}{ccc}
0 & 0 & 0 \\
1 & -1 & 0 \\
-1 & 1 & 0 \\
\end{array}
\right),
\left(
\begin{array}{ccc}
0 & 1 & -1 \\
0 & -1 & 1 \\
0 & 0 & 0 \\
\end{array}
\right),
\left(
\begin{array}{ccc}
0 & 0 & 0 \\
0 & 1 & -1 \\
0 & -1 & 1 \\
\end{array}
\right).
$$
Check:  We know the vector space has dimension $4$ over $\mathbb{R}$, (or $\mathbb{Z}$), since once you fill in cells (1,1), (1,2), (2,1) (2,2), the rest is determined.
So, it is sufficient to show that
$$\left(\begin{array}{ccccccccc} 1 & -1 & 0 & -1 & 1 & 0 & 0 & 0 & 0 \\ 0 &
0 & 0 & 1 & -1 & 0 & -1 & 1 & 0 \\ 0 & 1 & -1 & 0 & -1 & 1 & 0 & 0 & 0 \\ 0 &
0 & 0 & 0 & 1 & -1 & 0 & -1 & 1 \\ \end{array}\right)$$
has full rank (which I did on a computer).
Comment: Ah, a better guess than mine :-) (but also affording less opportunity to apply some linear algebra :-)
Answer: You have six constraints, one for each row and column, but the sum of the row constraints and the sum of the column constraints are the same, so at most $5$ of the constraints are linearly independent, so the space is at least $4$-dimensional. The matrix of the first five constraints is
$$
\pmatrix{
1&1&1&0&0&0&0&0&0\\
0&0&0&1&1&1&0&0&0\\
0&0&0&0&0&0&1&1&1\\
1&0&0&1&0&0&1&0&0\\
0&1&0&0&1&0&0&1&0\\
}\;.
$$
We can guess three basis vectors by taking the three pairs of indices and placing a $\pmatrix{1&-1\\-1&1}$ matrix in the corresponding entries; that yields
$$
\pmatrix{
1&-1&0&-1&1&0&0&0&0\\
1&0&-1&0&0&0&-1&0&1\\
0&0&0&0&1&-1&0&-1&1
}
\;.
$$
Now we can take the generalized cross product of these $8$ vectors, both to check that they're all linearly independent and to find the fourth basis vector that's orthogonal to all of them. According to Wolfram|Alpha, the result is (proportional to)
$$
\pmatrix{0&1&-1&-1&0&1&1&-1&0}\;,
$$
so the matrix for one possible basis is
$$
\pmatrix{
1&-1&0&-1&1&0&0&0&0\\
1&0&-1&0&0&0&-1&0&1\\
0&0&0&0&1&-1&0&-1&1\\
0&1&-1&-1&0&1&1&-1&0
}
\;.
$$


ANOVA degrees of freedom

Question: I'm running the following test
anova(fixed_model, random_model, test="LRT")

and I get the following results.
Data: review_data
Models:
fixed_model: y ~ (1 | x1)
random_model: y ~ (1 + x2 | x1)
             npar   AIC   BIC  logLik deviance  Chisq Df Pr(>Chisq)
fixed_model     3 13591 13610 -6792.5    13585
random_model    5 13590 13622 -6790.1    13580 4.8949  2    0.08651 .

Why are the degrees of freedom 2 and not 1 if random_model only adds a random slope?
Answer: The larger model adds both a variance of random slopes across groups and the covariance between the slope and the intercept.  If you look at summary(random_model) (or VarCorr(random_model)) you should see estimates for both parameters.
If you want the intercept and slope to be independent you can probably use (1 + x2 || x1) (although this depends on what package you're using, which you haven't shown us).
If this is your actual model and not a simplified example, you should consider including x2 as a fixed effect as well, because random effects are zero-centered (i.e., your random_model assumes that the population average slope is exactly zero).

ANOVA degrees of freedom


Qual é a relação da tag  com o fluxo principal no HTML?

Question: Lendo sobre a tag
 encontrei esse texto na documentação MDN:

O Elemento HTML
 representa o conteúdo independente,
  frequentemente com uma legenda (
), e é normalmente
  referido como uma única unidade. Enquanto ela está relacionada com o
  fluxo principal, sua posição é independente do fluxo principal.
  Normalmente, isso é uma imagem, uma ilustração, um diagrama, um trecho
  de código ou uma esquema que é referenciado no texto principal, mas
  que pode ser movido para outra página ou para um apêndice, sem afetar
  o fluxo principal.

A aplicação do elemento em si eu compreendi, conforme mostra esta pergunta feita aqui no site, porém não entendi os seguintes trechos do texto acima:

"sua posição é independente do fluxo principal"
"mas que pode ser movido para outra página ou para um apêndice, sem afetar o fluxo principal"

O que significam essas citações enumeradas acima? Pode dar exemplo(s)?
Answer: Como foi dito na pergunta, o
 tem sua aplicação dentro de alguns objetos visuais no documento HTML, sem contar também o seu valor semântico.
No entanto, esses recursos não devem ser incorporados sempre em elementos
. Aí que entra os dois pontos da pergunta que podem ser respondidas diretamente pois uma complementa a outra.
Refere-se ao fato de que se o elemento incorporado pelo
 for movido para outro local, ele não irá comprometer o significado da página.
Por isso é importante analisar qual o comportamento que esse objeto (imagem, vídeo, trecho de código, etc) tem sobre a página.
Mas se o objeto for parte importante do conteúdo daquela página, ela não pode ser incorporada dentro de uma
:
1)Alguns exemplos de quando não utilizar figure:

Quando for uma logotipo;
Quando for um ícone de navegação;
Objetos pertencentes a um artigo;

Esses exemplos são importantes para o conteúdo da página e a posição deles também, portanto não use o figure em objetos desse tipo.
2)Exemplo de quando utilizar figure:
Considere:
- Uma página de consultoria possui uma
 de serviços e dentro dela há vários cards com uma breve descrição e um ícone representando o serviço. Nesse caso é viável usar o
. Veja abaixo uma coluna contendo 1 card informando um serviço e a utilização do figure:

Título do Serviço

             Uma breve descrição do serviço vai aqui

Pois bem, espero ter ajudado um pouco. Qualquer dúvida estamos aí.
Comment: Mt bom jovem! Obg pelas explicações. []s
Answer: Uma observação é que o elemento figure está bem próximo do que temos no mundo impresso, e que é normatizado pela ABNT em textos acadêmicos etc.
Você já deve ter lido em artigos "Veja figura 1 (a figura não está aqui, mas faz parte do contexto)"
Veja o que diz a documentação oficial W3C (já traduzido)

O elemento pode, assim, ser usado para anotar ilustrações, diagramas, fotos, listagens de código, etc., que são referenciados a partir do conteúdo principal do documento, mas que poderiam, sem afetar o fluxo do documento, ser movidos desse conteúdo principal. , por exemplo, para o lado da página, para páginas dedicadas ou para um apêndice.

Fonte: https://www.w3.org/TR/2011/WD-html5-author-20110809/the-figure-element.html
Nesse artigo o @Maujor conta um pouco sobre a história da tab figure, e cita o seguinte

O elemento
 destina-se a marcar uma unidade de conteúdo e opcionalmente uma legenda para o conteúdo que se constituí em uma peça isolada do fluxo principal do documento e pode ser retirada daquele fluxo sem alterar o significado do documento.

Fonte: http://www.maujor.com/blog/2010/04/13/os-elementos-figure-e-figcaption-da-html5/

Veja por exemplo esse parágrafo
" O apêndice do adulto é um longo divertículo, medindo aproximadamente 10 cm de comprimento, com origem na parede póstero-medial do ceco, cerca de 3 cm abaixo da válvula íleo-cecal (Figura 1). "
Em outra página, outra parte do texto, ou em um apêndice vc vai encontrar a Figura 1
Figura 1 na verdade é um link para uma imagem que mesmo estando relacionada ao conteúdo por algum motivo não está exatamente no fluxo do conteúdo, podendo estar em um apêndice...

Veja aqui o modelo original desse text + image
http://www.scielo.br/scielo.php?script=sci_arttext&pid=S0100-39842007000300012#fig1

Resumindo
O que se entende pela tag figure é que ela é independente do fluxo do conteúdo, não tem posição fixa no fluxo do conteúdo. Acredito que na maioria dos casos a posição dela pode variar de acordo com o template, escolhas tipográficas ou mesmo de usabilidade para facilitar a leitura e não quebrar o texto em telas pequenas. Pode ser até uma questão de arquitetura da informação na página.

Informações a parte
Para quem gosta de história... A tag <FIG>
Nos primórdios, antes da tag
 já existia a tag <FIG>, como vc pode ver nessa documentação oficial. https://www.w3.org/MarkUp/html3/figures.html

The FIG element improves on the IMG element by allowing authors to use markup for the description text. The content model allows authors to include headers, which is appropriate when the headers are part of the image data. It also allows graphical hypertext links to be specified in the markup and interpreted by the user agent rather than the server.

Traduzindo "O elemento FIG melhora o elemento IMG, permitindo que os autores usem marcação para o texto de descrição. O modelo de conteúdo permite que os autores incluam cabeçalhos, o que é apropriado quando os cabeçalhos são parte dos dados da imagem. Ele também permite que os links gráficos de hipertexto sejam especificados na marcação e interpretados pelo user agent em vez do servidor."
Veja que em 1993 eles já se preocupavam com semântica e acessibilidade.
Ela era usada dessa forma
<FIG ALIGN=FLOAT SRC="cat.gif">

"Not curried fish again!"

A cartoon of a scrawny cat with its tongue out saying ACK!
</FIG>

The text in the following paragraphs will flow around the figure
if there is enough room. The browser is free to position the caption at
the top, bottom or sides of the figure.

Output

Fonte da imagem: https://www.w3.org/MarkUp/HTMLPlus/htmlplus_35.html
Comment: Boa hugocss! :D
Comment: @Sam valeu mestre! Ficou um pouco mais "acadêmico" rss. Eu fiquei curioso pq eu acho que bem antigamente no HTML4 tinha uma tag chamada `` mas não tenho certeza, não achei nada a respeito
Comment: Achei uma referencia na w3.org, artigo de 1993 ``: https://www.w3.org/MarkUp/HTMLPlus/htmlplus_35.html haha doidera!
Comment: Vigi! Ainda nem tinha internet no Brasil.
Comment: As duas respostas ficaram bem esclarecedoras, mas achei que a sua me deu uma melhor noção da parada.


Dell Poweredge 2950 Hard drive size

Question: I recently purchased a Dell Poweredge 2950 at an auction for a very low price, couldn't pass it up.
It didn't come with any hard drives so I ordered 5 SATA caddy trays and I am curious what the maximum size the hard disks could be.  I plan on doing RAID 6 so I have plenty of redundancy and I would like to have at least 1TB drives installed.  Will the 2950 support 5-6 1TB drives or maybe even 2TB drives?  I'm not concerned whether or not dell "supports it".  I have already tested a WD Green 500GB SATA drive I had lying around and it worked fine in the SAS bay.  Also, will the caddys I ordered still have lights that tell me whether or not a drive is dead or is that just an SAS thing?
Answer: 2TB drives (2.5" and 3.5") will work on the PERC 5, 6, and H700.
3TB drives are only supported on the PERC H700; support was added via firmware update, so if you buy one, make sure to update the controller firmware for 3TB support.
3TB support is controller-specific, not system specific, so an H700 in a 2950 would take 3TB drives and a PERC 6 in an R710 would not.
In order for Windows OS's to use a >2TB, the "disk" must be converted to GPT.  Windows OS's CAN boot to GPT IF using 64-bit Vista/2008 (or later) installed on a UEFI-enabled system (which the R710 is but the 2950 is not).
As far as the lights, I believe the lights on the caddy should work as you would expect, but it's been a while since I had one to play with.
Support Documentation:
http://en.community.dell.com/support-forums/servers/f/906/t/19309039.aspx
Comment: According to DELL after inputting my service tag mine has a "Dell PowerEdge PERC 6/i SAS RAID Controller Card PCI-E H726F"

It looks like I will be using 2TB then?

Dell Poweredge 2950 Hard drive size


Bash script to transfer folder recursively without overwriting via FTP

Question: I would need a bash script to transfer folders recursively via FTP.
Username/password/IP - static defined.

Server where the script runs on: Linux
Source server: Samba (Linux...)
Dest. Server: Linux

As the files to be transferred are big database files (.bak, etc) overwriting should be avoided.
Preferably no prompting because the script has to be 'cronned', to run at night.
(I'm not a hero in bash, but I have the impression it's the easiest for this situation)
Thanks a bunch in advance!
Answer: If the destination server is Linux might I suggest just using rsync with an ssh key?  FTP is unencrypted and doesn't have native support for incremental backups.
A single rsync with a command line such as the below could suffice.
rsync -auv -e "ssh -i /path/to/keyfile" /path/to/source_directory/* \
    user@remotehost:/path/to/destination_directory/

Answer: You can mount FTPfs and cp everything there. Make sure you disable delta-transfer so it doesn't download files from there :)
BTW, how are you going to make these backups without overwriting? you'll have a bunch of old files mixed with some new ones if you don't use date in folder name.
Comment: Possibly by comparing the file names first? But how I'll do that practically...
Comment: Install FTPfs, and mount FTPfs somewhere (for instance, /mnt/backup: `curlftpfs ftp://ftp.sunet.se/ /mnt/backup`). Then set this to cron: `cp -R -n /i/wanna/backup/this /mnt/backup/ > /dev/null`


Deixar apenas data no datatime, sem a parte das horas

Question: Olá, tenho um projeto que chama uma WebApi que traz os dados do banco de dados, porém um dos campos no banco de dados é do tipo DateTime e no meu projeto, declarei como String (posso alterar, não tem problema), o que eu quero é o seguinte: queria que quando traz esse valor, tira a parte das horas e deixe apenas a data
O campo é: Cba_dt_abertura
Como posso fazer uma conversão, ou talvez tirar essa parte, segue imagens:
Como está:

Como devia ser:

Meu projeto:
 public async Task<IActionResult> Index()
    {
        Uri BaseAdress = Services.Token.BaseAdress;
        string strToken = Services.Token.strToken;
        List<ContaBancariaModel> ListaContaBancaria;
        using (HttpClient httpClient = new HttpClient())
        {
            httpClient.BaseAddress = BaseAdress;
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", strToken);
            httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("Application/Json"));
            using (HttpResponseMessage response = await httpClient.GetAsync("/api/ContaBancaria/findAll"))
            {

                response.EnsureSuccessStatusCode();
                string resul = await response.Content.ReadAsStringAsync();
                ListaContaBancaria = JsonConvert.DeserializeObject<List<ContaBancariaModel>>(resul);
            }
        }
        return View(ListaContaBancaria);
    }

Método na WebApi:
[HttpGet]
    [Route("findAll")]
    public HttpResponseMessage findAll()
    {
        try
        {
            var result = new HttpResponseMessage(HttpStatusCode.OK);
            var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                    x => new {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = x.Cba_dt_abertura,
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"
                    }).ToList();
            result.Content = new StringContent(JsonConvert.SerializeObject(bancos));
            result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
            return result;
        }
        catch (Exception)
        {
            return new HttpResponseMessage(HttpStatusCode.BadRequest);
        }
    }

Answer: Altere o tipo do objeto Cba_dt_abertura de string para DateTime, após isso quando for popular a list coloque o código abaixo.
    try
    {
        var result = new HttpResponseMessage(HttpStatusCode.OK);
        var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                x => new {
                    Cba_codigo = x.Cba_codigo,
                    Cba_numero = x.Cba_numero,
                    Cba_tipo_conta = x.Cba_tipo_conta,
                    Cba_dt_abertura = x.Cba_dt_abertura.ToShortDateString(), //Coloque esse método
                    Cba_gerente = x.Cba_gerente,
                    Emp_codigo = x.Emp_codigo,
                    Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"
                }).ToList();
        result.Content = new StringContent(JsonConvert.SerializeObject(bancos));
        result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
        return result;
    }

Comment: A resposta do João está correta, porém é importante observar que, o método ToShortDateString() é aplicado em propriedades do tipo DateTime. O Jeff não conseguiu encontrar o método provavelmente pelo fato de sua propriedade Cba_dt_abertura ser do tipo string. Jeff, conforme você informou, você pode alterar o tipo de sua propriedade. Modifique para DateTime isso provavelmente lhe permitirá acessar ao método ToShortDateString().
Comment: Eu não sei se você testou, mas o visual studio diz que DateTime não contém uma definição para 'ToShortDateString'
Comment: Quando eu acrescento o ponto eu apenas posso usar os seguintes métodos:  "Equals, GetHashCode, GetType, GetValueOrDefault e ToString".
Comment: Documentação do método: https://docs.microsoft.com/pt-br/dotnet/api/system.datetime.toshortdatestring?view=netframework-4.7.2
Comment: Como dito pelo @SérgioLopes, o método está disponivel apenas para o tipo DateTime
Comment: Ah sim, não sabia disso, obrigado pelas resposta
Comment: {"LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression."} recebo este erro ao usar esse método
Comment: Você trocou o atributo x.Cba_dt_abertura para DateTime na sua Entity? pois o erro fala que ele está tentando usar o método em uma string.
Comment: O atributo Cba_dt_abertura  da Entidade precisa ser DateTime, ja o Cba_dt_abertura  da sua model tem que ser string.
Comment: Fiz as alterações que você disse, porém me deu erro novamente, mas encontrei uma solução, o seu método está certo, deve ser algum erro aqui, obrigado pela ajuda, vou postar a solução que encontrei
Answer: Cba_dt_abertura = DateTime.Parse(x.Cba_dt_abertura.ToString()).ToString("dd/MM/yyyy", CultureInfo.InvariantCulture),

Comment: Bom, eu n consigo usar o "parse", mas fiz algo parecido que encontrei
Answer: Encontrei uma solução alternativa na internet:
                var bancos = bdprincipalEntities.Contas_Bancarias.Select(
                    x => new {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = x.Cba_dt_abertura,
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao.Equals("A") ? "ATIVO" : "DESATIVADO"
                    }).ToList().Select(x => new
                    {
                        Cba_codigo = x.Cba_codigo,
                        Cba_numero = x.Cba_numero,
                        Cba_tipo_conta = x.Cba_tipo_conta,
                        Cba_dt_abertura = string.Format("{0:dd-MM-yyyy}", x.Cba_dt_abertura),
                        Cba_gerente = x.Cba_gerente,
                        Emp_codigo = x.Emp_codigo,
                        Cba_situacao = x.Cba_situacao
                    });


Como incluir arquivos em uma View baseado na Rota em Laravel?

Question: Eu criei uma view inicio.blade.php onde coloquei todo o código que se repete em todas as páginas e criei outras views que estendem essa view.
Criei as rotas para as views definindo um nome para elas desta forma:
Route::get('/', 'PainelController@painel')->name('painel');
Route::get('calendario', 'PainelController@calendario')->name('calendario');

Porém na view inicio existem alguns arquivos que só são usados em algumas páginas.
Eu vi que é possível utilizar condicional pra verificar em qual Rota está, porém do jeito que eu estou fazendo não estão funcionando corretamente. Independente da rota em que estou a condição sempre retorna verdadeiro.
Fiz dessa forma (copiei do modelo que o laravel cria):
@if (Route::has('calendario'))
<link rel="stylesheet" href="{{asset('css/owl.carousel.css')}}" type="text/css">
@endif

Até mandei imprimir a rota pra ver se estava correto e ela retorna certo, mas a condição sempre retorna verdadeiro:

Caso essa não seja a forma correta poderiam me dizer como se faz?
Answer: O Route::has verifica se existe uma rota com esse nome nas configurações de rota, não define exatamente qual é a rota atual que está sendo utilizada, pra isso existe o currentRouteName() método que traz o nome da rota utilizada,  adaptando ao seu exemplo:
@if (Route::currentRouteName() === 'calendario')
<link rel="stylesheet" href="{{asset('css/owl.carousel.css')}}" type="text/css">
@endif

Referencia: Accessing The Current Route
Comment: Aeh! Salvou o dia. Eu bem que comecei a desconfiar disso. Tinha tentado usar o RouteName mas deu erro tmb, creio que foi pela quantidade de sinal de igual que usei que tava errado. Mas desse jeito aí agora funcionou.


Cannot update during an existing state transition - whenever a specific state is changed

Question: I have been getting this error in my component. The error occurs whenever the 'completed' state is changed in any way. The source of issue is in getValidationState() when the state is altered. It does not break my app, however, I am interested to know what I am doing wrong in this component and how I can fix it for the future.
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import { FormGroup, ControlLabel, FormControl, HelpBlock } from 'react-bootstrap';

class FormGroupValidation extends Component {

    constructor(props) {
        super(props);
        this.state = {
            value: '',
            completed: false
        };

        this.getValidationState = this.getValidationState.bind(this);
        this.complete = this.complete.bind(this);
        this.unComplete = this.unComplete.bind(this);
        this.toggleComplete = this.toggleComplete.bind(this);
        this.handleChange = this.handleChange.bind(this);
    }
    getValidationState() {
        const length = this.state.value.length;

        if (this.ThresholdType === 'max') {
            if (this.props.errorLen && length <= this.props.errorLen) {
                return 'error';
            } else if (this.props.warnLen && length <= this.props.warnLen) {
                this.unComplete();
                return 'warning';
            } else if (this.props.successLen && length <= this.props.successLen) {
                this.complete();
                return 'success';
            }
        } else {
            if (this.props.successLen && length >= this.props.successLen) {
                this.complete();
                return 'success';
            } else if (this.props.warnLen && length >= this.props.warnLen) {
                return 'warning';
            } else if (this.props.errorLen && length >= this.props.errorLen) {
                this.unComplete();
                return 'error';
            }
        }
    }
    complete() {
        if (!this.state.completed) this.toggleComplete();
    }
    unComplete() {
        if (this.state.completed) this.toggleComplete();
    }
    toggleComplete() {
        this.setState({completed: !this.state.completed});
    }
    handleChange(e) {
        this.setState({ value: e.target.value });
    }
    render() {
        return (
        <form>
            <FormGroup
              controlId="formBasicText"
              validationState={this.getValidationState()}
            >
              <ControlLabel>Working example with validation</ControlLabel>
              <FormControl
                type="text"
                value={this.state.value}
                placeholder="Enter text"
                onChange={this.handleChange}
              />
              <FormControl.Feedback />
              <HelpBlock>Validation is based on string length. </HelpBlock>
            </FormGroup>
        </form>
        );
    }
}

export default FormGroupValidation;

Answer: Looks like you have a cycle going.
In your FormGroup JSX you render, you have this property: validationState={this.getValidationState()} so when you render, it calls that function. Through subsequent function calls you end up changing the state in your toggleComplete() function. When you change the state, it triggers a re-render, and the cycle starts over again (this subsequent render calls getValidationState() to be called and so on)
React is supposed to be reactive ( funnily enough :P ), i.e. the state changes in response so actions.
Comment: Thanks. This answer is a go-er. I'll choose it as an answer when the time limit is up.
Comment: What would be best practice to update the completed state when the input length has exceeded it's limit?
Comment: Do any length checking on FormControl `onChange` functionality so that state changes happen in response to input. Then if their input reaches a certain length, update the state to completed and then stop updating the input on further input (unless they delete stuff)


ASP.Net is not working properly on IIS6

Question: I have an Visual Studio 2010 ASP.Net project. And I want to deploy this project to the my host. I did but my site is not working properly. I can access to Home Page etc. but I can not do my prior job. I have to change some word template which located on the server. I am using IIS 6. Thank you.By the way I did change some access property but it did not work.
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Here is the stack trace
[UnauthorizedAccessException: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).]
System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType objectType) +0
System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType serverType) +79
System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType serverType, Object[] props, Boolean bNewObj) +76
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Activator.CreateInstance(Type type) +6
TemplateModify3.modifyCont.justDoIt() in C:\Users\q\documents\visual studio 2010\Projects\TemplateModify3\TemplateModify3\modifyCont.aspx.cs:120
TemplateModify3.modifyCont.runDelegate(myDelegate dlg) in C:\Users\q\documents\visual studio 2010\Projects\TemplateModify3\TemplateModify3\modifyCont.aspx.cs:92
TemplateModify3.modifyCont.Button1_Click(Object sender, EventArgs e) in C:\Users\q\documents\visual studio 2010\Projects\TemplateModify3\TemplateModify3\modifyCont.aspx.cs:72
System.Web.UI.WebControls.Button.onclick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563

Comment: What is line 120 in the file `modifyCont.aspx.cs`?
Comment: that page try to change word templates in server @Filip
Answer: Try chaning the user that runs the Application Pool, it seems that you are trying to access some COM objects that your IIS_USR don't have access too.
You can also try using Impersonation.
Comment: How can i give access permissions to the COM objects.
Comment: How can i give access permissions to the COM objects. @Filip
Comment: @Güngör, did it work when using Impersonation / Change user for Application pool? You might find this usefull: http://support.microsoft.com/kb/325791
Comment: I tried but it did not help me. I thought I can not use Word dll s on my server @Filip
Answer: Do you use a third party dll like Crystal Reports that may not be installed correctly or at the correct version? It could be that said third party dll is trying to access the windows or .net temp folders or a related dll that does not exist.
Comment: Yes I am using word dll s on my project. But I install word 2010 on my server but it did not work.
Comment: Yes I am using word dll s on my project. But I install word 2010 on my server but it did not work. @Fellmeister
Answer: There is an security issue with COM libraries with Windows Server2008 R2. This security issue prevent to use COM libaries with Server 2008 R2. If the server was 2003 version, it coul be work.

ASP.Net is not working properly on IIS6


Create Android OAUTH client fails with: "An unexpected error occurred. Please try again later. (4800001)"

Question: So I am trying to setup Google Play Games Services in the Google Play Developer Console.
This worked for me yesterday.
Today however, when setting up another app, and trying to link an android app to the games services, I get this error:
<code>An unexpected error occurred. Please try again later. (4800001)
</code>
I got this in:
Google Play Developer Console -> Games Services -> [game] -> Linked Apps -> STEP 2 Authorize your app.
This happens regardless which key I try, my release key, or my debug key.
I don't understand why this would be happening, as it was working yesterday, albeit for an app without real-time multi player. The app I am trying to setup now needs real-time multiplayer, but I'm not sure whether this difference is the cause of it. Maybe servers at google are down?
I get the error each time I try, regardless which browser I use, or which OS. I tried on Ubuntu Firefox and OSX Safari.
Comment: I'm having same problem now. Maybe their server's not working properly ATM?
Comment: Good to know that I am not the only one. If it is infrastructure problems, then I think Google in unaware, because it has not been listed at https://status.cloud.google.com
Answer: This was a temporary breakage in the Google Play Developer Console.
They fixed it today, by rolling back changes to the console, see:
https://github.com/playgameservices/android-basic-samples/issues/153#issuecomment-134749998
Answer: I opened https://console.developers.google.com/ page and successfully registered my app there while I was having same issue as you.
Comment: I found the 'add credentials' in the developers console, but this video specifically warns against using that console to create clientids, as it will not make the known to game services: https://developers.google.com/live/shows/5936979195723776


How to write a keyboard part for an existing song?

Question: I was asked to make a keyboard part for a song somebody else has written. It's probably going to be organ.
I have no idea how to do this. I've been playing for a few years and I can improvise a bit, but I've never done anything like this.
Anyone have any tips for me?
Comment: This is rather broad. The only answer we can give you at this point is to play the song over and over again while improvising keyboard parts, and then write down one that sounds good. Can you be more specific about what exactly you are asking, or with more contextual information about what you're working with?
Answer: That's kind of a hard question to answer and I am assuming the answer is very different for everyone. When I am witting a part for a song I pull out a tape recorder and just play it and see what sounds good.
Answer: One approach I take is to think about a few different things:
1) What is the chord progression of the song?
2) What orchestration will sound good with it?
3) How big/what should my part be?
When I first start trying to write something, I might just play each chord on every beat, or once per measure to get a feel for it. Then I think about which inversions sound good, and how one leads to the next. I also think about how to vary it rhythmically.
Usually I have an idea of what sort of sounds I want to use. In your case, you're already thinking of organ, so I'd start with that. I might also try something that's completely the opposite, just to see how it sounds and give me new ideas. Sometimes I'll record something into the sequencer and just switch patches as it plays back to see what it sounds like, but usually I have some direction I try to take it.
And of course, you don't want to upstage the main performer. Is the piece written to showcase a singer? Guitar? Something else? I usually try to stay out of the range of the lead so as to not overwhelm it.
Answer: You need to listen to the song and decide the; tone, chords and key of the song, then make sure that you stick to these three things. using similar complementary notes and similar chords (maybe a harmony of the song) will make the song have more death and a richer tone. Basically you need to listen and see what the song already sounds like and where there are gaps. This is a tricky question and is not that simple because what i would do to a song is very different to what you would do.
Answer: Personally I would stick it on loop and sing along til something good occurs to you, record any such good ideas on your phone (or your sequencer if you're the hi tech sort) then when you start to dry up, or you have an abundance of ideas to work with, sit down and transcribe them - see which you like best.
Even if you're fluent enough to immediately play what occurs in your head working this way can help keep your fingers from taking over and running down their well worn paths.
If the song has several sections you may find it useful to use an audio editor/sequencer and loop sections of it. Also, you may want to confer with whoever's song it is and ask them what they want and where they want it e.g. upfront/background, bold/subtle, funky/solemn, every section/just chorus/just accents etc.


WPF MVVM Binding Checkbox.IsChecked to a named item in a Dictionary

Question: I have a group of checkboxes that all represent different selections of the same type (for my example, they are all different file types).  I feel like binding each one to an individual property in the ViewModel is overkill, and I'd prefer to bind them all to one collection and use the binding syntax to bind each checkbox to a particular item in the collection by key.  I'm trying to stick to the MVVM pattern, so I don't just want to get lazy and handle the Checked event or something like that.
Is there a way to express a path or key within a collection using WPF binding syntax?  For example, if I expose a Dictionary<string, bool> called FileTypes as a public property in the ViewModel, is there a way for me to bind one of the checkboxes to FileTypes["aspx"]?   What if I had a more complex data structure like Dictionary<string, Dictionary<string, int>>?
Answer: You almost had it -- just drop the quotes around the indexer argument:
{Binding FileTypes[aspx]}

A more complex data structure would just require a sequence of indexers, e.g.
{Binding Foo[aspx][Bar]}

By the way, a good resource for this stuff is in MSDN, under WPF > Data > Data Binding > Binding Declarations Overview -- scroll down to "Binding Path Syntax" for a summary of the notations and conventions you can use in a binding path.


Sorting a view basing on the value of a boolean field

Question: I have a content type X. A view is used to display this content type (X), as a table. The content type has a field called "Preferred" which contains boolean values. I need to sort the table so that the "Preferred:true" items display at the top of the table.
How can I achieve it?
Answer: Add a new Sort Criteria sorter that sorts based on that field. Make sure it's at the top of your list of sort criteria.
If you don't want there to be a column for it in the table, click "exclude from display" in the field settings.
Comment: I tried that but, it doesn't work. I created a new Sort Criteria for Preferred. It sorts them together but, they are not at the top of the table.
Comment: and if my logic gene is in gear today, you'll want to sort descending so that all the 1's come first and then the 0's.
Comment: What exactly did you do when you tried it? What happened when you tried?
Comment: Okay. I added the Sort criteria and now it sorts correctly. But, is there anyway to sort the rest of the columns (that are not preferred true) to be alphabetical?
Comment: Actually, I just added another sort criteria to sort by title and everything works fine. Funny thing is, I tried the same thing earlier and it was not working.

Anyways, Thank You!
Comment: I'm glad you got it working. If my answer was correct for what you wanted, even if you figured it out on your own, you might want to mark it "accepted" because then it tells other people who read the question that it is correct. And it also gives me rep points ;-)


Infimum taken over finite coverings

Question:
For $E \subset \mathbb{R}$, define $J_*(E)=\inf\sum_{j=1}^N |I_j|$, where $I_j$ are intervals and the infimum is taken over all finite coverings of $E \subset \bigcup_{j=1}^N I_j$. Compute $J_*(E_1)$, $J_*(E_2)$, and $J_*(E_1 \cup E_2)$, where $E_1=\mathbb{Q} \cap [0,1]$ and $E_2 = (\mathbb{R} \setminus \mathbb{Q}) \cap [0,1]$.

I would like to understand this conceptually. What does the question mean when it says "the infimum is taken over all finite coverings"? For $E_1 \subset \bigcup_{j=1}^N I_j$, I was thinking, for example, $$E_1=\mathbb{Q} \cap [0,1] \subset [0,1+\frac 1j]$$ as in, $I_j=[0,1+\frac 1j]$.
Comment: Well, it meants that it wants you to consider only finite coverings! There are infinite coverings of the set $E$ by intervals, and you should **not** take these into account when computing the $\inf$.
Answer: A finite covering is just that: a finite collection of sets $I_1,...,I_N$ such that $E\subset \cup_{j=1}^N I_j$. Depending on your definitions, the sets $I_k$ are probably required to be open or closed.
In your example $E_1$ is covered by a single element $[0,1+1/j]$ for any $j$.
As an example, suppose that $E_1=[0,1)$. Then $E_1\subset \cup_{j=1}^\infty [0,1-1/j]$, but this is an infinite cover (and cannot be done in a finite way for that particular set and family of covers).
Comment: So, for example, if $I_j = [0,1+\frac 1j]$, then the cover $\bigcup_{j=1}^N I_j$ for $E_1 \cup E_2 = [0,1]$ is also infinite?
Comment: @dragon: Why would it be infinite if you have $N$ sets you're covering with???? Again the definition of a *finite* cover is when you have a *finite* collection of sets $I_k$ whose union contains your set. In the definition of $J_*$ its sort of redundant since they already wrote $\sum_{i=1}^N I_i$
Comment: I'm sorry, I meant to type $\bigcup_{j=1}^\infty$, not $\bigcup_{j=1}^N$, in my previous comment. Yes, I know that $\bigcup_{j=1}^\infty I_j$ is an *infinite* collection of sets $I_j$ and $\bigcup_{j=1}^N I_j$ is a *finite* collection of sets $I_j$.

Infimum taken over finite coverings


Adding a tab to the login page

Question: On the Login page, there are 3 tabs i.e. "Create new account", "Log in", and "Request new password". Are there modules out there that let us add more? If not, how can I achieve this manually?
Cheers
Answer: You can use hook_menu with type as 'MENU_LOCAL_TASK'. So that your menu path will be like 'user/your_path'.
Ex:
function my_module_menu($items) {
  $items['user/my-path] = array(
    'title' => 'Some title'
    'page callback => 'your callback',
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}
If you are using views to print this page, you can set menu as Menu tab in path options.

Adding a tab to the login page


Fixed Block Position CSS Problems

Question: Hello i was using the floating Block module to keep my right hand main menu in a fixed position as a person scrolls down the page. Then i deceided that maybe its overkill just for one menu and i have tried it with css.
<code>#sidebar-left {
 position: fixed;
    top: 0
float:right;
  right:20px;
  width:110px;
}
</code>
My theme is fixed width but im getting differant results when viewed in differant screen resolutions.  I was wanting the block to just appear to the right of the the 2nd right hand block (with the logo). Try as i might though im struggling to achieve it.
You can view my site (and the right hand menu) here-
http://onlinebanter.com/welcome
Can anyone help me achieve this?
Thanks
Answer: I think ive sorted it with
margin-left: 845px;
    position: fixed;
    top: 0;
    width: 110px;
Thanks

Fixed Block Position CSS Problems


Trombone attachments, bore, and range

Question: Contrast a straight tenor trombone versus a larger-bore tenor trombone with F attachment.  It appears that the larger-bore with F attachment activated will go down to C2 without having to hit any pedal tones.

I find a Bb1 pedal tone hard to play reliably on straight tenor.  Will the nearby note C2 on larger bore tenor with F attachment activated (non-pedal tone) be nearly as hard to play?  After all it's nearly the same note.
Are pedal tones easier to play on a larger bore tenor trombone with F trigger not activated?  If so, do people find that moving from straight tenor to larger bore tenor represents a massive expansion of lower range by gaining luscious pedal tones down to E1 at their disposal?  Or do you really need a bass trombone for that?
Are pedal tones with F trigger activated considered hard to play on a tenor trombone?  Or do you really need a bass trombone to reasonably inherit those spine-tingling pedal tones down to C1 that the F trigger promises?
Would getting a larger bore trombone and maybe larger mouthpiece to gain lower notes mean that I have to sacrifice on the high end of the range, that is, I lose high notes just as fast as I'm gaining low notes?  I'll sadly miss the occasional Ab4 on my straight tenor trombone.
Comment: The last point should probably be a separate question. Overall, it's a very good question, though. +1 and welcome to Music SE!
Answer: TL;DR version:

Will low C be as hard as Bb to play even though it is not a pedal tone?

Nope, harder

Are pedal tones easier to play on large bore?

Kind of, but not to an important degree

Can you get luscious pedal tones down to E1 (no trigger) with a large bore tenor, or do you need a bass?

Depends on your definition of luscious, but listen to Joe Alessi play them on tenor

Pedal tones from trigger F down to C, compare large bore tenor to bass

Same as above, but mostly absent from tenor trombone literature

Range considerations

Practice both ends of the range, play the instrument you want to play, don't choose the instrument based on notes you want to play.

Long Version:
I'm sure you already understand that the bass, small-, and large-bore tenor trombones all play in the same key because the tubing is the same length. Where they differ is in bore size and extra "features" like attachment triggers.
For starters, any time you compare two instruments with the same length of tubing, the lower notes are going to be easier to play on the one with the larger bore. That's just physics at work. However, the pedal tones as they are known are the fundamental notes of the harmonic series that the trombone plays in. For this reason, the pedal Bb is one of the easiest low notes to play on trombone, regardless of bore size!!! A middle schooler with a small-bore instrument can play a pedal Bb if they approach it with the right technique. If you are still having trouble with pedal Bb on the small-bore, buying a larger instrument is not going to help you at all, and will probably make things a lot harder.

That said, if you are still using the stupid tiny 11C/7C mouthpiece that comes with most small-bore trombones, I highly recommend switching to something that will give you a little more breathing room. The only professionals that use mouthpieces of that size are jazz players that need to spend all of their time in the stratosphere. For all-around playing on the small bore, I recommend a Bach 6 1/2 AL small shank.

The low trigger range of F2 to C2 is actually an extension of the non-trigger range from Bb2 to E2. C2 is actually MUCH more difficult to play than Bb1, because even though the notes are only a whole tone away, Bb1 is a pedal tone played with the shortest possible tubing length, and C2 is a 2nd harmonic played with the longest possible tubing length, with the trigger activated and the slide out beyond 7th position (remember the positions get farther apart the lower you go).
The low trigger range is definitely in the large-bore tenor player's toolbox, and he or she has to spend considerable time working on it. The sub-basement below the G1 pedal tone is generally left to bass trombone players, though tenor players can and should practice them since working on both extremes of the playing range improves the facility with the less extreme ranges.
If you want to hear some truly luscious low range on the tenor trombone, listen to Joe Alessi (one example that is coming to mind is his performance of John Mackey's "Harvest" concerto, right near the 6 minute mark... a truly scintillating C2). Alessi is known for playing on very large mouthpieces, and it's been my experience that these can really open up the low trigger range for a tenor trombonist. However, any equipment size change is going to have a tradeoff with endurance or facility in the opposite end of the range.
High Range:
Working on both extremes is advisable. Learning how to relax in the right way to play the lower notes will help you relax more in the middle and upper ranges. Exercising the high range is muscle-building, and should always be followed by playing some pedal tones to relax.
Another great exercise in the low range is to play false tones that don't actually exist on your instrument. With well-enough developed embouchure control, you can play F2 to C2 (notes that normally require a trigger) on a small-bore instrument. They're not going to sound the same, and you won't perform them, but they are good practice. Likewise, you can attempt "double pedal tones" like Bb0 without a trigger.
Like I mentioned before, larger instruments do make the high range more difficult, but Ab4 is not beyond the realm of possibility for a bass trombone player. Professional bass trombone players may practice all the way up to F5, but the highest that will reasonably be asked of them will be around Ab4 or Bb4.
Equipment:
You can already go broke buying mouthpieces, so I wouldn't advise buying different trombones just to expand your range. You should buy the trombone that you would like to play. If you're into jazz, or like playing with your local community band, or have a ska band or something, I can't see why you'd need more than a small or medium-small bore trombone. If you want to play big symphonic music, join an orchestra, play all the newest trombone solos, or study trombone at a conservatory, then you'll need the large bore tenor (and about 5 years to learn to play the damn thing). If you want to play bass trombone and hang out in tuba range all day long, buy a bass trombone!
After all that, it could just be that you need a larger mouthpiece, but that's something a private teacher would have to advise you on for a reliable diagnosis.
Answer: I totally agree with NReilingh's excellent answer on points 2-5.
However, i find myself fundamentally disagreeing regarding Bb1 vs C2 on the F-Trigger trombone, thus I'm writing this separate answer.
First my personal experience:
I've been playing the trombone for about 1.25 years now, I've been playing the Akkordeon and singing in choires for more than 30 years before, so while not my first instrument, it's my first wind instrument. I'm mostly an autodidact via watching Youtube lessons and reading web pages with a few pointers from fellow trombonists thrown into the mix. Apart from 2 hours of band practise every week, I get to practise about once, sometimes twice a week for about an hour, mostly fundamentals.
After initial minor problems getting to the F2 (and not C3) from Bb2 by pressing the trigger, I didn't have a lot of problems extending my range to the C2 within a few weeks. I can reliably produce a resonant C2, the only problem being a sustained air stream, as my breathing is not yet at a level i'm statisfied with.
I only ever learned about Pedal tones about half a year into playing the trombone. I found two different approaches to playing them on various websites, one being a strong air stream and approaching the pedal tone from just air by carefully tightening the lips, the other by producing a slow air stream which should result in playing a Pedal-Bb naturally. The first method worked initially for me, though not reliably and not with a precise timing. The second method seems to work better, but it's still not reliable enough, though that increases about 20-30 minutes into warm-up.
General thoughts:
The C2 is a natural evolution from the F2 simply using slide technique, the F2 a natural evolution from the Bb2 by not letting your embouchure slip to the next overtone series when activating the trigger. Both steps 'only' require to adjust the air stream for the longer tubing.
The relaxation from Bb2 to Bb1 on the other hand is so severe, you could be playing the trombone for years without ever having played a Pedal Bb by chance. (In fact out of 500 scores for trombone i currently own, only one actually features 2 pedal tones as optional notes.)
So while I agree that the Bb1 is physically easier to play than the C2, due to the tubing issue, psychologically the situation is reversed and it requires a good level of experience and a good technique for that physical reality to be true.
IMO it needs to be said, that until that level of expertise is reached, the opposite is true and the C2 is easier played than the Bb1.
Regarding the initial question:
I'd like to make one addition. In my experience, it tends to be easier to find a mouthpiece with a good sound in the low range for large bore horns than for small bore horns.

Trombone attachments, bore, and range


ASP.NET Core API Authentication with JWT breaks built-in authentication for website

Question: I'm working on an ASP.NET Core project that has a website as well as an API. I need the API to be secured by some means, so I implemented JWT authentication. This worked as expected, and the API is only accessible by calls made with a valid token.
The problem is, the built-in login functionality on the website no longer works.
This is the code I added to Startup.cs:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(o =>
    {
        o.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = Configuration["Jwt:Issuer"],
            ValidAudience = Configuration["Jwt:Issuer"],
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
        };
    });

If I remove this code, the built-in login feature works as usual, but the API no longer works.
Is there a way I can make the JWT authentication only apply to the API controllers? Or is there a way I can make the built-in authentication use JWT?
Answer: I had the same problem and resolved it (using Asp.Net Core 3.0).
You can add more than one Authentication schema to your project with code like this.
// Read the token generation data...
var token = Configuration.GetSection("JwtTokenData").Get<JwtTokenData>();

services.AddAuthentication()
        .AddCookie(options =>
        {
            options.LoginPath = $"/Identity/Account/Login";
            options.AccessDeniedPath = $"/Identity/Account/AccessDenied";
        })
        .AddJwtBearer(options => {
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(token.Secret)),
                ValidIssuer = token.Issuer,
                ValidAudience = token.Audience,
                ValidateIssuer = false,
                ValidateAudience = false
            };
        });

Notice how I haven't specified the default authentication schema when I call AddAuthentication. This allows the built-in Authentication to be the default for your pages or controller where you use the [Authorize] attribute.
But when you need to use JWT Authentication then you use this option on the Authorize attribute for your Web API controller or methods
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

Comment: You can also just use `[Authorize(AuthenticationSchemes = "Bearer"]` attribute, it`s shorter.


Peculiar working of '*' in regex expression

Question: While writing a regex pattern for substituting all the continuos '1's and single '1's  as 's'. I found this quite confusing ,usage of '+' (used for matching 1 or more ) gave expected result, but '*' gave strange result
>>> l='100'
>>> import re
>>> j=re.compile(r'(1)*')
>>> m=j.sub('*',l)
>>> m
'*0*0*'

While usage of '+' gave expected result.
>>> l='100'
>>> j=re.compile(r'1+')
>>> m=j.sub('*',l)
>>> m
'*00'

how does '*' in regex gives this, while its behaviour is to match 0 or more.
Comment: Perl, PHP, Java will output `**0*0*` for `/1*/` as regex
Comment: Very interesting question. If someone has the hands dirty in the python regex engine code, feel free to provide an explanation.
Comment: A little care while differing the roles of re.search() and re.sub() is very beneficial for (1)* useful.
Answer: (1)* means "match 0 or more 1's". So for 100 it matches the 1, the empty string between 0 and 0, and the empty string after the last 0. You then replace the empty strings with '*'. 1+ requires at least one 1 in the match, so it won't match the boundary between characters.
For those readers curious, yes the python output is *0*0* and not **0*0*. Here is a test python script to play with. (Regex101 has the wrong output for this, because it does not use an actual python regex engine. Online Regex testers will usually use PCRE (which is provided in PHP and Apache HTTP Server), and fake the target regex engine. Always test your regex in live code!)
Here you can see in JavaScript the output will be **0*0* (it will match the empty string between 1 and 0 as a new match) This is a prime example of why 'regex flavor' is important. Different engines use slightly different rules. (in this case, if the new match starts at 0 or the character boundary)

console.log("100".replace(/(1)*/g, '*'))
Comment: Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/145819/discussion-on-answer-by-tezra-peculiar-working-of-in-regex-expression).
Answer: Beware of patterns that can match nothing. This isn't well-defined, so the behaviour varies by engine. For example, you get a different result in Perl.
$ perl -e'CORE::say "100" =~ s/1*/\*/rg'
**0*0*

At position 0, it matches 1 character.
At position 1, it matches 0 characters.
[Forced to advance to avoid infinite loop]
At position 2, it matches 0 characters.
[Forced to advance to avoid infinite loop]
At position 3, it matches 0 characters.
[Forced to advance to avoid infinite loop]
[Fail to match: Beyond end of string]
Answer: regex = r"1*"
p = re.compile(regex)
test_str = "100"
for m in p.finditer(test_str):
    print(m.start(), m.group())

Outputs 4 matches (that's why regex101 shows 4 matches):
0 1
1
2
3

While re.sub() replaces 3 positions which is a cause of re.sub() advancing after a zero-length match (Python doc):

sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of
  pattern in string by the replacement repl.
...
Empty matches for the pattern are replaced only when not adjacent to a
  previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.

What does a non-overlapping occurrence mean? It means when:

the first match ended at the start of the string, where the first
  match attempt began. The regex engine needs a way to avoid getting
  stuck in an infinite loop that forever finds the same zero-length
  match at the start of the string.
The simplest solution, which is used by most regex engines, is to
  start the next match attempt one character after the end of the
  previous match, if the previous match was zero-length.

In this case, the second match attempt begins at the position between the 1 and the 0 in the string, hence the difference.