Check to see if key,value pair in myArray is in the JSON and if not, add it in

Question: I am trying to check to see if a key,value pair in my array is found in the response JSON and if it is not, then I want to add it to the JSON.
<code>$scope.myArray = [{
  "Product_type": "T"
}, {
  "Product_type": "4NB"
}, {
  "Product_type": "C"
}, {
  "Product_type": "39087NB"
}, {
  "Product_type": "16364NB"
}];
</code>
JSON response array:
<code>$scope.data.obj.Product = [{
  "Count": 28,
  "Product_type": "T"
}, {
  "Count": 88,
  "Product_type": "4NB"
}, {
  "Count": 20,
  "Product_type": "C"
}, {
  "Count": 3,
  "Product_type": "39087NB"
}]
</code>
In this case, the missing key,value pair would be "Product_type": "16364NB". How would I do the check and then add to the response JSON?
Should I iterate through the JSON and then somehow reference myArray to figure out which one is missing, then push it to the JSON?
Answer: <code>

$scope.myArray.forEach(function (a, i) {
    if ($scope.data.obj.Product.find(function(item) { return item.Product_type === a.Product_type }) === undefined) {
        $scope.data.obj.Product.push(a);
    }
});

</code>


Fingerings for root-position Seventh Chords on Piano

Question: I'm aware that there are a multitude of ways to voice a chord - some chord tones can be omitted and other tones can be added, and one does not need to stack in 3rds (although I'm not sure of how to build chords by stacking other intervals yet).
For brevity, though, I'll keep it simple; are there tried and true fingerings to for Major, Minor, or Dominant Seventh Chords in root-position (I know it's up to the players discretion and if extended tones are to be added, but assume no extended tones are added)?
For instance, consider the following root-position chords and fingerings for the right hand. For C7 my hand wants to play C,E,G,Bb with the fingers 1,2,4,5, respectively, and use the same fingers for a CM7 chord as well. This fingering is also reasonable for an Eb7 chord, however, for an EbM7 (again, in root-position using the right hand) it feels more comfortable to use the fingers 1,2,3,5.
This illustrates that when I follow what feels most comfortable to me, the fingering of a root-position Major 7th chord depends on its root, unless I should try and hammer out what doesn't feel comfortable until it's comfortable.
So what, if any, is a typical way of voicing Major, Minor, and Dominant Seventh Chords in root-position? A reference is fine, and my apologies if this is a dumb question with no answer. I just want to move on to building chords by stacking intervals of 4ths, 5ths, and 6ths rather than 3rds, but I first need to establish traditional voicings in muscle memory.
Answer: The fingerings chords are bound to change even on the same chord as you change the root note because your fingers tend to lay differently so it's perfectly natural to have the same chord built on a different root notes have different fingerings.
Personally for the dominant 7th chords in root position closed with the right hand I'll play 1-2-3-4 and for major 7th chords I'll play 1-2-3-5. It's just how my fingers comfortably lay for these chords. Depending on the context and what you're actually doing, you'll most likely find yourself playing many different fingers for the same chord as what chords/notes you're coming from and going to are going to be different thus you may find different fingerings useful at different times.
Answer: I recommend using 1,2,4,5 when you can.  I have larger than normal hands (but not abnormally large).  I've been playing for 9 or 10 years, and I noticed that I used to use 1,2,3,5 but now I find using 1,2,4,5 is much better since overtime it gives you more reach (there are lots of pieces that require a 4->1 finger movement, such as what is required when playing Bb major arpeggio on the keyboard) <- it is good practice.
But then again I haven't had a lesson in years, so maybe this isn't the best way for you (it is for me, that is for sure...).
Answer: A simple answer I can give from experience is yes 1, 2, 3 and 5 in a root position is perfect, but it can change depending on the next note you play. Like if you have an A7 chord but your next note is the A an 8ve above your root note, then I'd play the 7th note with my 4th finger. But normally when playing in chordal accompaniment, IN ROOT POSITION you're okay with 1, 2, 3, 5.
Comment: RH 1,2,3,5 does seem reasonable, if not appropriate, for a major seventh chord in every key, so I can use this fingering as a base. RH 1,2,4,5 works well for major seventh chords in the keys of A, D, and E, so I'll practice both fingerings into muscle memory in those keys. But like you said, context is everything, so hopefully all possible fingerings will eventually enter muscle memory. Grateful!
Answer: First time I've thought about it! However, 1,2,3 fit best for the triad, and for me, the pinky does both dom 7 and M7 with the right hand. It is going to depend on the player's physiology - how long each digit is comparably. Basically it matters not much, but whatever feels most comfortable and convenient, considering the previous and the next chord. Try out different ways - there aren't many combinations for 4 notes and 5 digits! Arpeggiating the notes gives a different perspective, too.


Placement of reminder/courtesy accidentals

Question: I recently downloaded Camille Saint-Saëns' lovely Valse nonchalante—the Durand First Edition (1898)—from IMSLP. All the upper-staff reminder accidentals are placed above the staff. I don't remember seeing this style before.
I don't have that many Durand scores, so I don't know whether they've maintained this policy. On the one hand, I like it because it distinguishes reminders from true accidentals without the clutter of parentheses. On the other, placing them above perhaps makes them a bit too prominent. (I assume reminders in the lower staff would be placed below.)
I'm curious whether any other publishers adopt this style and what others think about it.

_________________________

_________________________

Note that this placement is, of course, practical only when there is a single note. In his Valse canariote (also Durand) we have the usual parentheses (and smaller type) in m. 3 here:

It may be for this reason that we rarely encounter this placement in modern music.
Comment: @Tim The c.a. in bar 8 is because of the LH in bar 7; bar 20 is due to the RH in bar 19. Bar 17 I can't explain, except that perhaps the editor felt the need to clarify the *upcoming* accidental in bar 18. Weird, but, you know, it the French.... :-)
Comment: The courtesy accidentals in bars 8, 17 and 20 seem superfluous - they're  not reminding the reader of any previous changed notes. Only bar 10 seems to be useful. What have I missed? However, it's quite a nice way to remind (when appropriate).
Comment: @Aaron - it's all French to me... but, courtesy accidentals generally *remind* readers of a previously changed note *in the same octave*, surely?
Comment: @Tim Well, that's the usual purpose, but it's note wholly uncommon to see them used otherwise. Durand is being very, very courteous.
Comment: Whenever I need to mark an accidental by hand, either because it was printed wrong or I need a reminder, I do this. I find it easier to notice than if I've tried to scribble over the staff lines and squeeze it between the notes.
Comment: @AndyBonner Yes, I usually put it above, not only for reasons of space, but because it's more visible as a reminder that the eye can catch early, i.e. with enough warning not to make the mistake.
Comment: Good thing there aren't any courtesy double-sharps above the staff.  It might lead to some unintended percussion.
Answer: I can't speak to Durand scores specifically, but I know many publishing houses use this notation to indicate editorial additions. In other words, the courtesy accidentals in the staff are shown in the original manuscript and are thus directly from the composer. The courtesy accidentals above the staff are not in the manuscript and thus are not from the composer, but they are friendly reminders from the editors of that particular score.
Answer: This notation is commonly found for editorial accidentals in renaissance and late medieval music. Note that in that style of music there where common rules of unnotated accidentals, c.f. musica ficta. So in modern editions such unnotated accidentals are commonly played above the staff.
I have not seen this for more modern music and reminders before though.


Mirror chords theory

Question: I was checking a video about this subject and came across a question: when I have a lower chord like C2 G Bb D and as mirror D F# A E what determines that the mirror chord starts in D when the next example is A1 E B C and as mirror we have E F C G ?
Comment: In both examples, it is as if there is a mirror extending vertically from the center of the Ab in between the chords. The other note on a keyboard with this type of visual symmetry is D.
Comment: See also https://music.stackexchange.com/questions/56394/negative-harmony-and-rotating-around-the-axis
Answer: The notion of "mirrored chords" is based around an earlier notion of an axis of symmetry. When we have a pitch (or pitches), we find its mirror image around a given axis of symmetry to find the resultant pitch.
Take, for instance, a C. If our axis of symmetry is the G above it, we see that our C is a perfect fifth below the axis. Therefore, its mirror image would be a perfect fifth above G, which would be a D. We say that C "inverts around G" to D.
(There's a distinction here between pitch inversion and pitch-class inversion, but that's for another time.)
An easy way to determine these inversions/mirror chords is with the twelve pitch classes arranged in a clock:

Now, we look for a mirrored interval. In your original example of C G Bf D, we see an ascending perfect fifth between C and G. To find the axis of symmetry, we look for a descending perfect fifth in the mirror chord: that between E and A. Now we have to find how C inverts to E and how G inverts to A.
Basically, we can just split the difference: find the spot halfway between C and E (D) and connect that to the spot halfway between G and A (A♭):

From this, we see that the axis of symmetry is D/A♭.
Now we can doublecheck your second example of A E B C. A inverts to G, E inverts to C, B inverts to F, and C inverts to E, which gives your collection of E F C G.

Note that not all "mirror chords" use this pitch axis; different pieces use different axes based on various compositional decisions.

Mirror chords theory


Acoustic/Electric Guitars

Question: So I was going to get a new acoustic. I really want to start getting into acoustics but I don't want to lose the ability to jam with friends who are on drums/bass, and have their own electrics plugged in. Does it make sense to get an acoustic/electric?
I've never played one before plugged in. I know they sound okay unplugged but do they sound good plugged in as well?
P.S. I was looking at this one: http://guitars.musiciansfriend.com/product/Ibanez-Exotic-Wood-EW20QMEBBD-Cutaway-AcousticElectric-Guitar?sku=512210
Comment: Only tangentially related, but I would recommend against that guitar. Anything "pretty" for less than a grand is generally junk. Particularly the Ibanez. While the guitars look beautiful, they tend to sound dead. I'd recommend something from fender or yamaha at the cheaper end of things.
Comment: And it's a shame to say, but $450 is the cheaper end of things.
Comment: @yossarian: I have an electric/acoustic (Weird name, it's an acoustic with a mic in it) that I bought for around a 100 bucks (quite a long time ago, but it was dirt cheap even then) including a soft case. Is it a good guitar? No. Is it good enough? Heck yeah! Do I use it? No, not since I bough a $500 Yamaha five years ago, because it's better.
Answer: IMHO, it's generally not a good idea to buy an acoustic/electric that lists for anything less than $1000.  Why?  Because no matter how much the guitar costs, some of what you're paying for in an acoustic/electric are the pickups and electronics.  In other words, a $500 acoustic guitar is a $500 acoustic guitar, but a $500 acoustic/electric is really a $400 acoustic guitar with $100 or so worth of electronics.  At that price point, there's a real difference in quality between a $500 acoustic and a $400 acoustic.
At some price point, the guitars get good enough where the $100 or so dedicated to the electronics doesn't make a huge difference in the quality of the instrument.  In other words, a $1000 acoustic guitar is still a $1000 acoustic guitar while a $1000 acoustic/electric might be a $900 acoustic + $100 of electronics.  At that price point, though, the difference between a $1000 and a $900 guitar isn't too much---it's not as big a difference as between the $500 and the $400 guitars.  Both the $1000 and the $900 guitars are decent quality, and so a $1000 acoustic/electric is probably a pretty good guitar.
So my advice?  Buy the best-quality purely acoustic guitar you can afford.  If that's around $500, great---there are plenty of decent-quality acoustic guitars at that price.  If later you decide that you want to plug it in, that's the time to buy a good acoustic pickup system.  That way, you spread out the cost over a longer period of time, and you can always upgrade the pickup later without throwing away the guitar, and vice-versa.
p.s.  That Ibanez is pretty, but at $450 including the electronics, there's absolutely no way it's made of solid wood.  That's a plywood instrument with quilted maple veneer.  Don't get sucked in by its looks.  For ~$500, you can get a well-made acoustic guitar with a solid-wood top from your choice of a variety of different builders.
Update
It seems the argument I made above is more controversial than I had expected.  Let me try to clarify it a bit.
Suppose you're a guitar maker looking to introduce a new acoustic/electric model to your line.  You pick one of your existing acoustic models and decide to add a pickup and electronics to it.  The Stew Mac catalog offers a variety of acoustic guitar pickups and electronics systems.  The cheapest complete package (acoustic pickup, preamp, endpin jack, wiring) they offer is the L.R. Baggs iBeam Active Pickup System, at $139.  Add in the additional labor to install this system in your guitars, plus the markup, and it'll come to a $200 premium.  Maybe $150 if you're a huge company and can buy enormous volumes.
So now you have a choice: you can either add $150 to the cost of your guitar, or you can try to find $150 worth of corners to cut from your existing model.
Well, if your existing model is around $1000, it's a lot easier to cut $150 worth of corners and still have a great instrument than it is if your existing model is $450.  If you're looking to cut $150 off of a $1000 model, maybe you use A-grade solid wood instead of (prettier but sonically irrelevant) AA-grade.  Maybe you stick with a AA-grade solid top, but go with plywood back and sides.  Maybe you use cheaper tuners and abandon fancy binding.  Either way, you'll cut some corners and still end up with a pretty good guitar.  But if you're cutting $150 off of a $450 model, you were already using pretty cheap tuners, and now you're abandoning solid wood entirely and going with plywood throughout.
So now imagine you're the customer, and you're looking at a $450 acoustic/electric.  Of that $450, you know that $150 is electronics, so you're really looking at a $300 guitar with a pickup tacked on.  The difference in quality between a $300 instrument and a $450 is way way bigger than the difference between a $900 instrument and a $1050 instrument.  It's a 50% difference vs. a 15% difference.
I'm emphatically not saying you've got to buy a $1000 guitar to be happy.  I'm saying, if you've got $450 to spend on a guitar, buy a purely acoustic one with no electronics at all.  Then you know all the money you'll spend has gone into making the best guitar $450 can make.  Later, if you decide you simply need to plug it in, you can save up for a great acoustic pickup that you can use to amplify your $450 guitar.
Comment: Eh, I think you are going a bit too far here! I bought a low end Ibanez AE acoustic with the electronics and built in tuner, and it would be fine for jamming with friends, or really anything. Used, it was only like $150. I will admit, however, to hating the way it sounds amplified.
Comment: @slandau: Personally, I'm partial to Seagull.  It's a Canadian maker with very well-built, solid-top instruments at reasonable prices.  But there are certainly others that are well worth looking at.  At that price point, though, don't settle for anything less than a solid-top instrument.
Comment: Well thought out I really appreciate it. Thanks! What acoustic only brands do you recommend? I've been hearing you can't go wrong with Martin or Taylor. But I've found some nice Fenders and Ibanez for the price as well.
Comment: @slandau; Lag also do some excellent less expensive but high quality acoustics
Comment: @Alex Basson: $1000? Not everyone has that kind of dough to shell out :) I got a middle-of-the-range acousto-electric Alvarez for about $400. Spent another $250 at the shop fixing it up and now it plays like a dream.
Comment: @Jimi Oke: You're right, not everyone (including myself) has $1000 to spend on an acoustic/electric, which is exactly why I gave the advice I did (did you read the third paragraph)?  As for your Alvarez, either you bought it used (in which case it was more expensive when new) or you spent $250 to *fix up a new guitar*---either way, your story reinforces the point I was trying to make.
Comment: @Alex Basson: Oh, of course, I read your answer in its entirety. Mine was only a lighthearted comment! No, it wasn't used; it was a blem, so I got it $100 cheaper. I had to fix up for reinforcements, partly due to poor care over a humid summer and some defects (yeah, it was a blem:)) but, overall, it's still a reasonably decent piece of work. I should also point out that I'm primarily a bassist, then a classical guitarist. When the right time comes, I hope to get one of those $1000 Taylors or the like. I seriously envy those people but one has to make the best of what one has.
Comment: I'm not sure I agree. At that price point, you're more likely to find a guitar with electronics than without. Pretty much everything at guitar center in the 200-500 range has it. Although, it's hard to argue with the advice "best sounding guitar in your price range"!
Answer: I have an A/E guitar. A Fender cutaway dreadnought. I'm largely happy with it, but here are some words of wisdom.
1) Dreads and other big guitars are big guitars so they can project in acoustic environments. If you're going to be plugging in, you don't need the big fat guitar. Same thing with heavy strings. If you have something backing you up, no need to go fat with strings.
2) Not every dime you can spend on a guitar comes out the soundhole. And with CNC systems, the cost of perfectly-good guitars is dropping. Yeah, you can get a fantastic guitar for $1000, but you can also get a gold-plated dog for that cost. Don't stress about not getting the perfect thing at $450, but rather get the best your $450 can buy, and build up a list of things you want your next guitar to have.
3) Current onboard pre-amps have built-in tuners. You want that. And, upon following the link, I see you have that.
4) A solid top is good, probably what you want, but solid back and sides are less essential. Laminate parts will be more resistant to the damages of heat and humidity fluctuation than real wood, but you'll never get the aging process that can make solid wood guitars sound wonderful.
5) In a full rock band, the acoustic guitar is a chording snare drum. Trying to get beyond that means that EVERYONE must drop out, or you goose your juice and tempt the feedback gods.
Good luck.
Answer: Some of the low-end guitars can be surprising... Depends what you're looking for.   I bought a decidedly-low-end Yamaha (APX500) for 300 bucks a couple of years ago.
An inexpensive guitar to be sure, I bought it mostly because that's what I could afford and it had a small body so it didn't hurt my aging shoulders.
Sound was surprisingly good.  The Yamaha electrics in this APX line are pretty decent, more advanced than many you see in this price range.
As for the guitar's acoustic sound... Not stellar but credible.  I jam with a Folk-school sort of weekend jam group and this little instrument held up well both in terms of volume and tone.
So don't be entirely dismissive of the under-a-grand models... Just have realistic expectations and make sure you play 'em first!
Plugging in and modeling your volume and tone from the guitar is definitely handy.
Of course, you can always buy a non-electrified acoustic and just add an after-market pickup....
Answer: The most important thing is to try the guitar before you buy. Only you know how you want it to feel, and how you want it to sound. Never buy a guitar you haven't played. Online prices may seem attractive - but it's worth paying $50 extra to know what you're getting.
Go to a reputable shop, on a weekday, when the shopkeeper has time to advise you, and the shop's quiet, and give yourself time to try out a few guitars. Try them both plugged in and unplugged. To give you an idea of the level of service you should expect from a guitar shop - when I bought my modestly priced acoustic, I spent forty minutes unattended, free to try out the range he'd picked.
A good shop will have a budget range they can get behind, as well as more expensive high-end brands. The best guitar dealer local to me recommends Cort acoustics, for example.
Bear in mind that electric-acoustics, plugged in, will only sound their best through acoustic amps - or PA amps with appropriate EQ. Using an amp intended for a solid body guitar won't get the best from the instrument. If you have a small amp you intend to use, take it to the shop. If you don't / can't, make sure you use something similar in the shop to what you'll use when the guitar's yours.
Comment: This is a really important point. If you don't have the right EQ then your guitar will sound like a crummy version of an electric guitar. But with an acoustic amp or properly equalized PA, you can get good sound. I tried a bunch of Martins and Taylors and really would have left with one of the least expensive Taylors but I made my fatal mistake: I tried the one in the glass case. Oh, sigh. But if you stay away from the guitars high on the wall or behind glass, I think you could find a Fender, Taylor or even Ovation you'd like. Just save a bit extra for the right amp.
Answer: That's a nice looking guitar.
It depends on the type of music you and your friends are jamming and the type of gear your all using.  You may find that you are drowned out by the other instrument if there is a full drum kit and the other guitars/bass are all electric and going through pretty powerful amps.
The other instruments have to be at a certain volume to meet the drums; electro-acoustics sound good amplified; but in my experience lower end models don't sound very well at high volume.
Comment: It's also much harder to control feedback as the volume goes up and you're in a small space. And acoustic guitar feedback is generally not the good kind.
Answer: These answers have really focused on quality vs cost but I think there's an entirely separate issue here.
You asked
<code>I know they sound okay unplugged but do they sound good plugged in as well?
</code>
I would say they can sound good plugged in, but they will almost definitely not sound like they do acoustically. There is a significant market for pickups for acoustic guitars, a ton of options, and a long signal chain from pickup to pre-amp to effects & eq to an amp or mixer. Some people spend years trying to get the perfect sound they desire. Yes, generally speaking, more expensive acoustic-electrics sound better, but I almost guarantee they will not sound the SAME acoustically as they do plugged in.
My advice would be to go a music store and ask to try out some acoustic-electric guitars, both acoustically and through an acoustic guitar amp (or some other setup). That will really give you an idea of the sound differences between the two, even if you're not playing models you intend to buy.

Acoustic/Electric Guitars


Porque meu ajax só funciona quando quer?

Question: Tenho uma página que é mistura de HTML com php que quando clico no botão submit, o JavaScript é acionado, pega todas as informações e chama uma função que ativa um ajax pra chamar um arquivo php.
Parece muito simples, porém, ela simplesmente funciona só quando quer! Eu já não sei mais o que pensar ou fazer, simplesmente tem vezes que o ajax chama a classe, ela executa tudo certinho e retorna para a request.done para executar outra função, e outra vezes ele simplesmente retorna para a request.fail por nenhum motivo aparente.
Não sei se é relevante, mas algumas informações eu passo por session da página HTML para o arquivo php. E observei que nas vezes que funciona, as sessions não conseguem chegar a última página. Essa última página é chamada quando o ajax consegue executar e entra no request.done.
Código JavaScript para pegar as informações:
window.cartao = 0;
data= new Date();
ano = data.getFullYear();
mes = data.getMonth() + 1;
var form = document.getElementById('caixa');
var cardNum = document.getElementById('cardNumber');
var expMes = document.getElementById('selectExpData');
var expAno = document.getElementById('InputAno');

var verifCod = document.getElementById('verifCode');
var nameCard = document.getElementById('nomeBox');

form.addEventListener('submit', function(e) {
    var resultado = verificaCampos(ano, mes, cardNum, expMes, expAno, verifCod, nameCard);
    if(resultado == false) {
        e.preventDefault();
    } else {

        transacaoCredito(cardNum.value, expAno.value, expMes.value, verifCod.value, nameCard.value, window.cartao, <?php echo "$totalReal";?>, <?php echo "$Amount" ?> );

    }

});

a função que contém o ajax
function transacaoCredito(cardNum, expAno, expMes, verifCod, nameCard, cartao, valorReal, amount) {
var request = $.ajax({
 type: "post",
 url: "_classes/creditoTransacao.php",
 data:
 {
 "cardNum":cardNum,
 "expAno":expAno,
 "expMes":expMes,
 "verifCod":verifCod,
 "nameCard":nameCard,
 "cartao":cartao,
 "valorReal":valorReal,
 "amount":amount
 }
 });

 request.done(function (result) {
     mudaPagina(result);
 });

 request.fail(function () {
    alert('Ocorreu um erro, por favor tente novamente mais tarde');
 });
}

E o arquivo php:
<?php
session_start();
$cardNum = $_POST['cardNum'];
$expAno = $_POST['expAno'];
$expMes = $_POST['expMes'];
$verifCod = $_POST['verifCod'];
$nameCard = $_POST['nameCard'];
$cartao = $_POST['cartao'];
$valorReal = $_POST['valorReal'];
$valorReal = number_format($valorReal, 2, "", "");
$valorReal = (integer) $valorReal;
$Amount = $_POST['amount'];
/*teste
$Amount = number_format($Amount, 2, "", "");
$Amount = (integer) $Amount;
//teste*/

$ourOrderId = $_SESSION['ourOrderId'];
$ourReturnUrl = $_SESSION['ourReturnUrl'];
$ourNotifyUrl = $_SESSION['ourNotifyUrl'];
$CurrencyCode = $_SESSION['CurrencyCode'];

/*$ourOrderId = $_POST['ourOrderId'];
$ourReturnUrl = $_POST['ourReturnUrl'];
$ourNotifyUrl = $_POST['ourNotifyUrl'];
$CurrencyCode = $_POST['CurrencyCode'];*/

require_once ('../vendor/autoload.php');
require_once ('../_classes/conexaoBanco.php');
use Cielo\Cielo;
use Cielo\CieloException;
use Cielo\Transaction;
use Cielo\Holder;
use Cielo\PaymentMethod;
use Cielo\Consultation;
$merchantId = '1111111111';
$merchantKey = '11111111111111111111111111111111111111111111111111111';
$cielo = new Cielo($merchantId, $merchantKey, Cielo::TEST);
$holder = $cielo->holder($cardNum, $expAno, $expMes, Holder::CVV_INFORMED, $verifCod);
$order = $cielo->order($ourOrderId, $valorReal);//$valorReal
switch ($cartao) {
    case 'visa':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::VISA, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'master':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::MASTERCARD, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'discover':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::DISCOVER, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'amex':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::AMEX, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'diners':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::DINERS, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'jcb':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::JCB, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'elo':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::ELO, PaymentMethod::CREDITO_A_VISTA);
        break;
    case 'aura':
        $paymentMethod = $cielo->paymentMethod(PaymentMethod::AURA, PaymentMethod::CREDITO_A_VISTA);
        break;
}

$transaction = $cielo->transaction($holder, $order, $paymentMethod, $ourReturnUrl, Transaction::AUTHORIZE_WITHOUT_AUTHENTICATION, true);

try {
    $transaction = $cielo->transactionRequest($transaction);
    if ($transaction->getAuthorization()->getLr()==0){
        $tid = $transaction->getTid();
        $consultation = $cielo->consultation($tid);
        try {
            $consultationResponse = $cielo->consultationRequest($consultation);
            if (is_object($consultationResponse)) {
                $status = $consultationResponse->getStatus();

                switch ($status) {
                    case 0:
                        $statusBanco = "Transação criada com sucesso";
                        break;
                    case 1:
                        $statusBanco = "Transação em Andamento";
                        break;
                    case 2:
                        $statusBanco = "Transação Autenticada";
                        break;
                    case 3:
                        $statusBanco = "Transação não Autenticada";
                        break;
                    case 4:
                        $statusBanco = "Transação Autorizada";
                        break;
                    case 5:
                        $statusBanco = "Transação não Autorizada";
                        break;
                    case 6:
                        $statusBanco = "Transação Capturada";
                        break;
                    case 9:
                        $statusBanco = "Transação Cancelada";
                        break;
                    case 10:
                        $statusBanco = "Transação em Autenticação";
                        break;
                    case 12:
                        $statusBanco = "Transação em Cancelamento";
                        break;
                    default:
                        $statusBanco = "Não há status da transação";
                }
                $mensagem = $consultationResponse->getAuthorization()->getMessage();
                $data = $consultationResponse->getAuthorization()->getDateTime();
                $data = new DateTime($data);
                $valorTotal = $consultationResponse->getAuthorization()->getTotal();
                $array = str_split($valorTotal);
                $antes = substr($valorTotal, 0
                    , count($array) - 2);
                $depois = substr($valorTotal, (count($array) - 2));
                $valorTotal = $antes . "." . $depois;

                $banco = new conexaoBanco();
                $banco->salvaBanco($tid,$cardNum,$nameCard,$valorTotal,$Amount,$statusBanco,$mensagem,$data->format('Y-m-d H:i:s'), $ourOrderId);

            }
        } catch (CieloException $ex) {
            echo "Erro[" . $ex->getCode() . "]: " . $ex->getMessage();
        }

        echo $status;

    } else {
        throw new CieloException($transaction->getAuthorization()->getLr());
    }
} catch(CieloException $ex) {
    echo "Erro[".$ex->getCode()."]: ".$ex->getMessage();
}
?>

Edit::
Pessoal, eu sei que não existe isso de "funciona quando quer", afinal eu também sou programador. O que eu quis dizer é que uma hora funciona e outra não. Achei que tinha ficado fácil de entender.
Comment: Seja Bem-Vindo ao SOpt, você já tentou usar o `Firebug` para ver o que está acontecendo?
Comment: Vou testar para averiguar, obrigado pela contribuição!
Comment: Cara, não existe esse negócio de ta funcionando quando quer.
Comment: Quando falha, no primeiro argumento do `request.fail` tem uma propriedade `responseText` o que tem lá?, ali tem o retorno do erro que aconteceu no PHP.
Comment: Tentei dar um alert no request.fail para exibir this.responseText e ele retornou undefined. Me ajude se tiver fazendo errado, por favor.
Answer: Essa é boa funciona quando quer, se faz errado como vai funcionar.
Isso acontece por três motivos.

Primeiro não sabem direito o conceito de ajax.
(Conceito: Ajax é uma chamada assincrona que atualiza parte do DOM)
Segundo motivo, uma chamada pode funcionar, hora sim, hora não, quando! A arvore do DOM esta desatualizada, então ela(função) tenta atualizar determinada parte e a instrução que atualiza, não sabe que aquela parte nem mesmo existe, para evitar isso use tags container, onde ela vai sempre estar presente.
Terceiro motivo, a própria tag da função não existe, ou seja a imagem, botão formulario, ainda nem criou o evento como pode usar.

Seguindo essa linha, isso não acontece mais

"funciona quando quer"

Coloquei exemplo, só para tentar ilustar o cenário

<javascript>
    atualize(tag2);
</javascript>
atualize tag no html acima, então chama ajax, quando ajax retorna não acha e não atualiza pois ela não existe

Caso 3.
<javascript>
   atualize(tag2);
</javascript>
script que arma o evento para chamar a função, não esta escutando, mesmo que a tag chamada tag2 exista.

Comment: Pode ser mais claro no segundo motivo, por favor? E como assim a tag da função não existe?

PS: Me desculpe se não possuo os mesmos entendimentos que você.
Comment: Coloquei exemplo, ve se ajuda
Answer: Experimente colocar a verificação de sucesso ou erro dentro do próprio ajax, dessa maneira;
$.ajax({

    //códigos do ajax atual

    success : function(result){

        mudaPagina(result);

    }
});

É interessante fazer os testes com o Inspecionar Elemento aberto, na aba "Rede" ou "Network", para poder ver as requisições que o navegador está fazendo ao vivo, bem como as respostas dessas requisições.


A Countable Well-ordered (w.r.to usual order) subset of $\Bbb{R}$ which is not of same order type with a subset of $\Bbb{N}$

Question:
Problem. Let $A$ be a countable subset of $\mathbb{R}$ which is well-ordered with respect to the usual ordering on $\mathbb{R}$. Then A has an order preserving bijection with a subset of $\mathbb{N}$. (True/False)

My Attempt. I progressed a little in this problem. I try to construct a counterexample to conclude the statement FALSE. But all the examples I figure out don't work. For example...$\{ 1/n|n \in \Bbb{N} \}\cup \{ 0\}$, $\{-1/2^n|n\in \Bbb{N} \}$..though all of them are well ordered and countable is order isomorphic to $\Bbb{N}$.
Also I can't prove the statement.
Can you please help me to conclude the problem? Thank you.
Answer: How about a set with order type $\omega+1$? This well ordered set is
$\{0,1,2,\ldots,\omega\}$. You need to find a sequence of reals $a_0,a_1,a_2,
\ldots$ and a further real $a_\infty$ such that (i) $(a_n)_{n=0}^\infty$
is a strictly increasing sequence, and (ii)
$a_\omega>a_n$ for all $n\in\Bbb N$.
Can you do that?
Comment: Lord.....I choose $a_n=(1+1/n)^n$ and $a_{\infty}=e$...Does it work?
Comment: That works fine. @IndrajitGhosh
Comment: Thank you so much..@LordSharktheUnknown


TimeSpan property in Azure Table Storage

Question: I have an entity with a TimeSpan property I want to save in Azure Table Storage. When I attempt to save the entity I get the error:

Can't cast to unsupported type 'TimeSpan'

Is there some way to do an automatic conversion or some other way to support TimeSpan?
Answer: I store the TimeSpan as ticks in an int or bigint field and convert that. You could also store it as a varchar. I prefer ticks because you can do math on it in the database if you need to and it makes range comparisons easier. If you're using Entity Framework, you can declare an unmapped property that gets and sets a TimeSpan from your database-friendly property.
Have a look at Entities in Azure Tables. Part of it describes how to exclude a property from Azure Table Storage, which should make what I proposed with EF workable for ATS as well.
Comment: @JamieSee - I should have expounded on that explanation.  We use ticks to calculate datetimes based on offsets (e.g. someDateTime.AddTicks(-ticks)).  Nothing to do with timezones in our case.  We want to know what 15 mins ago was from some datetime we have stored.  That causes problems when you don't standardize on UTC times that you store as well.  It was more of an aside as I upvoted the answer.  From what I have seen, most people use Timespans eventually to calculate a datetime...
Comment: I'm using Azure Table Storage (NoSQL storage service), so I don't think I can use EF with that. I've already thought of storing the ticks as a long - that's what I'm doing as a work-around at the moment but wanted to see if there's a better way.
Comment: Have a look at http://convective.wordpress.com/2009/12/30/entities-in-azure-tables/. Part of it describes how to exclude a property from Azure Table Storage, which should make what I proposed with EF workable for ATS as well.
Comment: We use ticks here.  Make sure you standardize any times stored to UTC so that applying the ticks will get you the right offset and time.
Comment: @dunnry UTC doesn't apply to TimeSpan unless you're using it as a hack to store time of day, but it is a good point. DateTimeOffset might be better for that purpose though.
Comment: @dunnry Excellent. Thanks for expanding on your comment. I'm sure people will find it helpful. +1
Comment: @JamieSee - Thanks for the link above, I hadn't noticed the events exposed on the DataServiceContext - that looks like something I might be able to use to do the conversion. I've only just started working with Azure but I've gotta say this stuff is so much easier with Amazon AWS - all you need is an attribute on the property and a custom converter.
Answer: In order to store a TimeSpan into a CloudTable, I'm using a long property that does the translation with the TimeSpan property:
public class MyEntity : Microsoft.WindowsAzure.Storage.Table.TableEntity
{
    public TimeSpan MyDuration { get; set; }

    // Workaround the fact that TableEntity does not automatically store a `TimeSpan`
    public long MyDurationTicks
    {
        get { return MyDuration.Ticks; }
        set { MyDuration = TimeSpan.FromTicks(value); }
    }
}

Answer: TimeSpan type and even nullable TimeSpan? type is supported by Azure Storage SDK > v8.0.0.
Flatten your entity using the static helper method TableEntity.Flatten method and write to table storage:
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.storage.table.tableentity.flatten.aspx
When you read the entity back from table, convert it back to your original entity using TableEntity.Convertback method.
https://msdn.microsoft.com/en-us/library/azure/mt775432.aspx
Flatten and Convertback methods support pretty much any type of property except IEnumerable / ICollection type indexed properties.
I have written an TableEntityAdapter class that underneath calls TableEntity.Flatten and ConvertBack methods and makes it easy for developers to use.
All you need to do is to pass your object to this adapter and that's all.
https://www.nuget.org/packages/TableEntityAdapter/
If you want to learn a bit more how the Flatten and ConvertBack methods  work behind the covers, have a look at the article I wrote.
https://www.nuget.org/packages/ObjectFlattenerRecomposer/
Answer: Because I ran into limitations on the Microsoft client, I have written an alternate Azure table storage client, Lucifure Stash, with many high level abstractions.
Lucifure Stash, supports data columns > 64K, lists, arrays, enumerations, serialization, morphing, public and private properties and fields and more. It is free for personal use and can be downloaded from http://www.lucifure.com  or via NuGet.com (http://nuget.org/packages/LucifureStash).
You can easily use it to morph a TimeSpan into a data type supported by Azure Storage Tables.
Comment: Thanks @Lucifure, I'll take a look at it to see if it fits my needs.
Answer: As JamieSee suggested you can store the TimeSpan as ticks in some long int, what you can also do is serialize the object to a Byte Array.
No matter what complex/unsupported class you have you can always serialize it to a Byte Array and upload it, then retrieve, deserialize it and cast it back to whatever type it was. I did this when I needed to upload a List of KeyValuePairs.
You can create automatic conversions in the properties getter and setter.


Select where json contains

Question: I have a postgres table:
      Column      |          Type
------------------+------------------------+
 id               | bigint                 |
 foo_id           | integer                |
 foo_name         | character varying(255) |
 bar_id           | json                   |

With values
     id |      foo_id    |       foo_name                |             bar_id
--------+----------------+-------------------------------+----------------------------
     17 |         717639 | name 1                        | [910, 5383774, 437, 5350]
     18 |        8442028 | name 2                        | [7274, 6241861, 437, 73669939]
     19 |          77415 | name n                        | [7274, 5513, 249642574, 743181502]

How can I select from this table records ids where bar_id contains value 437?
Comment: please share your attempt
Answer: You can use the operator @> to check if the array contains a specific value.
However that only works with jsonb values, not json values. So you need to cast your column.
select *
from the_table
where bar_id:jsonb @> '[437]';

It would be better to change the column's type to jsonb.

Select where json contains


Show that $\sum_{n=0}^\infty \frac{1}{2^{n!}}$ is irrational

Question: I need to show that $\sum\limits_{n=0}^\infty \frac{1}{2^{n!}}$ is irrational.
Tried the same methods as proving for $e$ and $\sin{1}$ and such but it doesn't work for me as $n$ is in the power.
Would greatly appreciate any help
Comment: Hint: if it were rational, its binary representation would be eventually periodic.
Comment: Look up Liouville numbers: https://en.wikipedia.org/wiki/Liouville_number#Liouville_numbers_and_transcendence - but other hints and solutons suggest  there are easier ways.
Comment: I hope you meant $n!$ at the exponent.
Comment: @IdanDaniel Look at the way b00n he T edited it.  You have to put the exponent in braces.
Comment: Yeah, in the power. Thanks for the edit
Comment: Hint: $|\frac{p}{q}-\frac{m}{n}| \ge \frac{1}{nq}$ for any positive distinct rationals. So if by contradiction you would get a rational $\frac{p}{q}$, cutting the series at high enough $n$ so $2^{(n+1)!}$ overwhelms $q$ should immediately give you the required contradiction
Comment: But this is true in general.  Let $b$ be a positive integer and $b>1$.  A real number $x$ is rational if and only if the base-$b$ representation of $x$ is periodic.
Answer: Hint:
Step 1. Do a proof by contradiction. Assume it's equal to $p/q$,.
Step 2. Multiply both sides by $q$.
Step 3. Multiply both sides by $2^{K!}$, for some fixed $K$. (We will choose $K$ later.)
Step 4. you should have an equation of the form
$$
\text{Integer} = \text{Integer} + \text{infinite sum starting from term $k = K$}.
$$
Ignore the parts that are integers, and so that the remaining infinite sum is between $0$ and sum bound -- for example, try to find an upper bound by noting that $2^{k!}$ is, at the very least, greater than or equal to $2^k$.
Step 5. Now you have a bound on something that is supposed to be an integer. Choose $K$ so that the thing is bounded between $0$ and $1$. Then it can't be an integer, so you are done.


How is Drupal Planet realised?

Question: How is the Drupal Planet realised?
I found the Planet installation profile, but it seems to be dead (the Git instructions tab is empty).
Answer: Drupal planet is built upon the core aggregator module, blogs are required to set up a special feed (generally tagging it drupal-planet) to be imported in the list.
That should be pretty simple to reproduce: What is Planet Drupal and how do I get added?

How is Drupal Planet realised?


Hardy-Littlewood strong type estimate, final equation of proof

Question: I am reading https://en.wikipedia.org/wiki/Hardy–Littlewood_maximal_function proof of strong type estimate and I understand everything but this last equation:
$$2Cp \int_0^\infty \int_{\lvert f \rvert >\frac{1}{2}}t^{p-2} \lvert f \rvert dxdt=C_p \lVert f \rVert_p^p$$ where $C_p$ depends only on $p$ and $d$ where $f$ domain is $R^d$
How can I see it? I think it has to have something in common with the Cavalieri principle : $$\int_{R^d}\lvert f \rvert ^p dx=p\int_0^\infty t^{p-1}m(f>t)dt$$
where $m$ is $d$ dimensional Lebesgue measure, but I can't derive this particular equation.
Comment: I think layer cake representation would be of some help... $f(x)=\int_0^{\infty} \chi_{\{|f|>t \} }dt$.
Answer: Substituting this into our integral gives:
$$
\|Mf\|_p^p \leq p \int_0^\infty t^{p-1} \left( \frac{2(5^d)}{t} \int_{|f| > \frac{t}{2}} |f|\, dx \right) dt.
$$
This simplifies to:
$$
= 2(5^d)p \int_0^\infty \int_{|f| > \frac{t}{2}} t^{p-2} |f|\, dx\, dt.
$$
$$
= 2(5^d)p \int_0^\infty \int_{\mathbb{R}^d} \chi_{\{x:|f(x)| > \frac{t}{2}\}}(x) t^{p-2} |f|\, dx\, dt.
$$
Now, we change the order of integration again (applying Tonelli's theorem):
$$= 2(5^d)p\int_{\mathbb{R}^d}  \int_0^\infty  \chi_{\{x:|f(x)| > \frac{t}{2}\}}(x) t^{p-2} |f| \, dt dx.
$$
Observe that $$\chi_{\{x:|f(x)| > \frac{t}{2}\}}(x) = \chi_{\{t:|f(x)| > \frac{t}{2}\}}(t)$$
then,
$$= 2(5^d)p\int_{\mathbb{R}^d}  \int_0^\infty  \chi_{\{t:|f(x)| > \frac{t}{2}\}}(t) t^{p-2} |f| \, dt \, dx.
$$
$$
= 2(5^d)p \int_{\mathbb{R}^d} \left( \int_0^{2|f(x)|} t^{p-2}\, dt \right) |f(x)|\, dx.
$$
The inner integral evaluates to:
$$
\int_0^{2|f(x)|} t^{p-2}\, dt = \frac{1}{p-1} (2|f(x)|)^{p-1}.
$$
Thus, our expression becomes:
$$
= \frac{2 (5^d)p}{p-1} \int_{\mathbb{R}^d}|f(x)| (2|f(x)|)^{p-1}\, dx.
$$
Simplifying:
$$
= \frac{2^{p}(5^d)p}{p-1} \int_{\mathbb{R}^d}|f(x)|^p\, dx.
$$
Recognizing the right-hand side as $ \|f\|_p^p $, we get:
$$
\|Mf\|_p^p \le \frac{2^{p} (5^d) p}{p-1} \|f\|_p^p.
$$
Finally, defining $ C_p = \frac{2^{p}(5^d)p}{p-1} $, we obtain the desired inequality:
$$
\|Mf\|_p \le (C_p)^{1/p} \|f\|_p.
$$
Answer: I will try to extend my comment to an answer. I will call this integral as $I$. Use Fubini's or Tonelli's Theorem to interchange the integrals, we get
$$I=2C_p\int_{\mathbb{R}^n}|f|\int_0^{\infty}t^{p-2}\chi_{ \{|f|>\frac{t}{2}\} }dtdx.$$
Now put  $t^{p-1}=2^{p-1}u$
$=>(p-1)t^{p-2}dt=2^{p-1}du$. We get
$$I=\frac{2^pC_p}{p-1}\int_{\mathbb{R}^n}|f|dx\int_0^{\infty}\chi_{ \{|f|^{p-1}>u \} }du.$$
Use Layer cake representation of a function i.e.,
$$|f(x)|=\int_0^{\infty}\chi_{ \{|f|>t \} }dt.$$
We have,
$$I=\frac{2^pC_p}{p-1}\int_{\mathbb{R}^n}|f|^pdx.$$
Answer: The  maximal inequality
$$
\lambda(\{M\,f>t\})\leq\frac{3^d}{t}\|f\|_1
$$
for all $f\in L_1$ plays a role here, as well as the fact that
$\|Mf\|_\infty\leq\|f\|_\infty$ for all $f\in L_\infty$. This last inequality is easily established by noticing that
$$\frac{1}{|B(x;r)|}\int_{B(x;r)}|f(x)|\,dx\leq\|f\|_\infty$$
for all $r>0$.
For $f\in L_p$,  $1<p<\infty$, one can use the trick of splitting $f=g+h$ where $g\in L_1$ and $h\in L_\infty$ and use the $L_1$ and $L_\infty$ results along with applications of Fubini's theorem (Cavalieri's principle if you will). This technique is common in getting string bounds in maximal inequalities. One may introduce some additional parameters to find optimal bounds. Here is the general idea at work (from Rudin, W., Real and Complex Analysis, 3rd edition, McGrawHill, 1986, pp. 173-174):
If $1<p<\infty$, then for $0<c<1$ and $t>0$,  let
\begin{align}
g_t= f\mathbb{1}_{\{f>ct\}},\qquad h_t=f\mathbb{1}_{\{f\leq ct\}}.
\end{align}
Clearly $h_t\in L_\infty$ and,
from  Chebyshev's and Hölder's inequalities, we also have  that $g_t\in
L_1$. Hence,
$M\,f\leq M\, g_t + M\, h_t\leq M\, g_t + ct$,
and so,  $\{M\,f>t\}\subset\{M\,g_t>(1-c)t\}$.  By
Hardy--Littlewood's inequality
\begin{align}
\lambda(\{M\,f>t\})\leq \lambda(\{M\,g_t>(1-c)t\})\leq
\frac{3^d}{t(1-c)}\|g_t\|_1=
\frac{3^d}{t(1-c)}\int_{\{f>ct\}} f(x)\,dx
\end{align}
An application of Fubini's theorem shows
\begin{align*}
\|M\,f\|^p_p &= p\int^\infty_0t^{p-1}\lambda(Mf>t)\,dt\\
&\leq \tfrac{3^dp}{1-c} \int^\infty_0 t^{p-2}\int_{\{f>
  ct\}}f(x)\,dx\,dt\\
&=\tfrac{3^dp}{1-c}\int_{\mathbb{R}^d}f(x)\int^{f/c}_0t^{p-2}\,dt\,dx
=
\tfrac{3^dp c^{1-p}}{(p-1)(1-c)}\int_{\mathbb{R}^d} f^p(x)\,dx
\end{align*}
One can minimize the bound $\tfrac{3^dp c^{1-p}}{(p-1)(1-c)}$, as a function of $c$ to get an optimal bound $C_p=(3^dpp'e)^{1/p}$, where $\frac1p+\frac{1}{p'}=1$.


Can i come back to a predefined viewstate of a page after coming back from another page?

Question:
What i've got is a Page1.aspx file, on this page i set some check boxes, some drop down values (a search filter page) that post back.
The search page returns to me a list of records (based on what was selected in the search section of this page).
Each record has a link to a "Details.aspx" page
on Details.aspx page i am able to modify values of the record, once done, i would like to get back to Page1.aspx but have Page1.aspx page in the same state that i left it.
By this i mean, i want the filters to be set as they were before the user navigated to the Details.aspx page

How can i do this?
i can not use history.back or history.go(-1)
Answer: Here is one way to do it: Put everything in a Session.
Load all the page1.aspx stuff into a class object, then add it to a Session (obviously before you go to the next page). Then when you go back check if that session exists, if it does, load the page using that class.
<code>var myClass = new MyPage1Save
{
    // load all the things you want saved
}

Session["Page1"] = myClass;
</code>


Automatic forecasting in R discrepancy

Question: I am new to time series forecasting and I am trying to understand automatic forecasting algorithm in the forecast package in R.
I read http://www.jstatsoft.org/v27/i03 this paper and I tried to run:
forecast(t_series_NOT_MODEL)

However, the results are different from:
e = ets(t_series_NOT_MODEL)
forecast(e)

Apparently, according to the paper:

There is also a method for a ts object. If a time series object is passed as the first argument to
  forecast(), the function will produce forecasts based on the exponential smoothing algorithm
  of Section 2.

Which means that forecast and ets output should be same, or am I make a mistake?
forecast() outputs a model with name -> STL + ETS(A,N,N)
whereas, ets() outputs a model with name -> ETS(A,N,N)
EDIT :

If model=NULL,the function forecast.ts makes forecasts using ets
  models (if the data are non-seasonal or the seasonal period is 12 or
  less) or stlf (if the seasonal period is 13 or more).

So does that mean that since my model is STL + ETS, that means that my data is seasonal? Also if that is the case why does ETS decide on (A,N,N) rather than (A,N,A) or (A,N,M) ?
Answer: You should read the documentation for that specific function by:
library(forecast)
?forecast

The forecast function in the R forecast package will return an ETS model if the frequency is <13 (seasonal or non-seasonal), otherwise it will apply a non-seasonal forecasting method to the seasonally adjusted data (aka STL decomp + non-seasonal ETS model applied), then reseasonalizes the last year of the seasonal component.

Automatic forecasting in R discrepancy


How to display a html page in java using its source code?

Question: I have a PageRead class and methods which will download the html source code from a given url.
public class PageRead {
public static StringBuilder readPage(String pageAddr) {
try {
URL url = new URL(pageAddr);
BufferedReader reader = new BufferedReader(new
InputStreamReader(url.openStream()));

String line;
StringBuilder sb=new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line+"\n");
}
reader.close();
return sb;
}

catch (MalformedURLException e) {
e.printStackTrace();
return new StringBuilder("");
}

catch (IOException e) {
e.printStackTrace();
return new StringBuilder("");
}
}

public static void main(String arg[]){
System.out.println(readPage("http://www.google.com"));
}
}

This will return me the source code in a String soemthing like :
<!doctype html>.......

Is there a way to display this html in something like a JFrame using this source code?
Comment: Swing components have very basic support for html, you may switch to JavaFx's  [WebView](https://docs.oracle.com/javafx/2/webview/jfxpub-webview.htm)
Answer: You can write source code to an file, something like: File file = new File("index.html"); and than open that file with your default browser. Page open can be done with https://docs.oracle.com/javase/7/docs/api/java/awt/Desktop.html.
try {
    Files.write(file.toPath(), content.getBytes());
    Desktop.getDesktop().browse(file.toURI());
} catch (IOException e) {
  // TODO Auto-generated catch block
}

If that is that what you think for :D
Answer: You can have a simple browser in Java, if that was the question. There was a JWebPane until Java6, and now there is a WebKit-based engine as part of JavaFX:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class BrowserTest extends Application {
    @Override
    public void start(Stage stage) throws Exception {
        StackPane root = new StackPane();

        WebView view = new WebView();
        WebEngine engine = view.getEngine();
        engine.load("http://www.google.com");
        root.getChildren().add(view);

        Scene scene = new Scene(root, 800, 600);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) throws Exception {
        Application.launch(args);
    }
}

Example was taken from a gist of GitHub user skrb.
One thing I checked is that WebEngine also has loadContent() method where you can directly feed it with HTML content as a String, so you can write
engine.loadContent(readPage("http://www.google.com").toString());

in place of the current load() call (which takes an URL), just be prepared that the downloaded HTML code is not everything what a webpage needs.
Comment: hi I have tried your codes and it will work! But however I have added a JFrame class inside my java program, and I want to call this show browser method inside the JFrame, is it possible to do that? Right now i cant use the above codes inside the JFrame as JFrame extends JFrame class and does not allow me to extends Application class anymore!
Comment: @JasonWEI I have not tried that, but I think you will need this tutorial: [JavaFX for Swing Developers](https://docs.oracle.com/javafx/2/swing/jfxpub-swing.htm)
Answer: One can open a html page or content within a Swing's JEditorPane. JEditorPane has various constructors including:
JEditorPane(URL initialPage)
JEditorPane(String type, String text) // where type can be a MIME type: text/html

This can be used with simple html content; the limitation is the html version supported is 3.2 only. Optionally, the Swing application can open a JavaFX's WebView within a JFrame using JFXPanel.


How to solve for theta?

Question: $$-12\sinθ-5\cosθ=0$$
Is it possible? or do I need to generate a graph? I heard the Newton Raphson Method can be used...not sure how to proceed please advise.
I'm trying to calculate the minimum and maximum values of: $y=12\cosθ-5\sinθ$
The equation above is a derivitive of $y$.
Comment: You can solve $a\sin \theta+b\cos\theta=c$ in general (see [this question](http://math.stackexchange.com/questions/213545/solving-trigonometric-equations-of-the-form-a-sin-x-b-cos-x-c)).
Comment: @user26486. I am sorry ! I did not go through the link since I was supposing a different approach. I deleted my answer !
Answer: Hint: Check if $\theta=\pi/2,3\pi/2$ (I'm considering the interval $[0,2\pi]$ ) are solutions, and then divide by $\cos$ and solve for $\tan$.
Answer: $$12\sin\theta+5\cos\theta=0\\\implies\frac{12}{13}\sin\theta+\frac5{13}\cos\theta=0$$
Now let $\cos a=\frac{12}{13},\sin a=\frac{5}{13}$. This works because $\sin^2a+\cos^2a=1$. We now have
$$\cos a\sin\theta+\sin a\cos\theta=0\\\implies\sin(\theta+a)=0
\\\implies\theta=\pi n-a$$ for integer $n$.
Answer: Yes, it is possible, though the answer might not look nice. First divide by $-12$: $$\begin{align}&\sin\theta + \frac 5{12}\cos\theta = 0\implies \\ \implies &\sin\theta = -\frac 5{12}\cos\theta \\[2ex] \implies &\sin^2\theta = \frac{25}{144}\cos^2\theta \\[2ex] \implies &1 - \cos^2\theta = \frac{25}{144}\cos^2\theta\end{align}$$
Can you take it from here?
Answer: I don't think you should differentiate.
Your $y$ can be written as
$$
y(\theta)=13 \cos(\theta+\arctan(5/12)).
$$
Can you see from this what the maximum and minimum values are?
Comment: I didn't do it that way, but something like it, I calculated the arctan of -5/12...then I minused that value from 180 and 360 degrees to get the min and max points...then subed those values back into y, and received the answers -13 and 13....I'm mind boggled here but I got the answer at the back of the book anyway!
Answer: y = 12cosx -5sinx
y'= -12sinx -5cosx
put y'=0
-12sinx -5cosx = 0
12sinx + 5cosx =0  (multiplied by -1 both sides )
12sinx = -5cosx
sinx/cosx=-5/12
tanx=-5/12
X = tan inverse (-5/12)
Now can you proceed?
Comment: Please see https://math.meta.stackexchange.com/questions/5020/

How to solve for theta?


Prove $\sum_{k=i}^{n} {k-1 \choose i-1} p^i (1-p)^{k-i} = \sum_{k=i}^{n} {n \choose k} p^k (1-p)^{n-k}$

Question: Prove that the following two summations are equal for any positive integers $i\leq n$, and any real number $p$ between $0$ and $1$:
$$
\sum_{k=i}^{n} {k-1 \choose i-1} p^i (1-p)^{k-i} = \sum_{k=i}^{n} {n \choose k} p^k (1-p)^{n-k}
$$
I know the equation is originated from Binomial distribution and its insight. That is,
$$
P\{X(i,p) > n\} = P\{B(n,p) < i\},
$$
which implies
$$
1 - \sum_{k=i}^{n} {k-1 \choose i-1} p^i (1-p)^{k-i} = \sum_{k=0}^{i-1} {n \choose k} p^k (1-p)^{n-k}.
$$
But I do not know how to prove it mathematically using some transformations in combinatorics.
Comment: Multiply each summand on the LHS with $(p+1-p)^{n-k}$, use binomial expansion and binomial coefficients manipulation
Comment: @RezhaAdrianTanuharja Thanks for your assistance. I implemented your suggestion and arrived at the proof of $\sum_i^n \binom{k-1}{i-1}\sum_{m=0}^{n-k} p^{m+i} (1-p)^{n-(m+i)} = RHS$. When examining the coefficient of $p^{m+i}(1-p)^{n-{m+i}}$, I encountered another obstacle in proving $\sum_{k=i}^{n-m}\binom{k-1}{i-1}\binom{n-k}{m} = \binom{n}{m+i}$. How can I continue my proof in this way?
Answer: We show the identity
\begin{align*}
\color{blue}{\sum_{k=i}^{n} \binom{k-1}{i-1} p^i (1-p)^{k-i} = \sum_{k=i}^{n} \binom{n}{k}p^k (1-p)^{n-k}}\tag{1}
\end{align*}
is valid. We consider (1) as equality of polynomials of order $i$ and degree $n$ in the variable $p$. It is therefore sufficient  to show equality of coefficients $[p^q], i\leq q\leq n$.
We use the coefficient of operator $[z^q]$ to denote the coefficient of series in $z$. We can write this way
\begin{align*}
[z^q](1+z)^n=\binom{n}{q}\tag{2}
\end{align*}

Coefficient left part:
We obtain for $i\leq q\leq n$:
\begin{align*}
\color{blue}{[p^q]}&\color{blue}{\sum_{k=i}^n\binom{k-1}{i-1}p^i(1-p)^{k-i}}\\
&=\sum_{k=i}^{n}\binom{k-1}{i-1}[p^{q-i}](1-p)^{k-i}\tag{3}\\
&=\sum_{k=q}^n\binom{k-1}{i-1}\binom{k-i}{q-i}(-1)^{q-i}\tag{4}\\
&=(-1)^{q-i}\binom{q-1}{i-1}\sum_{k=q}^n\binom{k-1}{k-q}\tag{5}\\
&=(-1)^{q-i}\binom{q-1}{i-1}\sum_{k=0}^{n-q}\binom{k+q-1}{q-1}\tag{6}\\
&=(-1)^{q-i}\binom{q-1}{i-1}\sum_{k=0}^{n-q}[z^{q-1}](1+z)^{k+q-1}\tag{7}\\
&=(-1)^{q-i}\binom{q-1}{i-1}[z^{q-1}](1+z)^{q-1}\sum_{k=0}^{n-q}(1+z)^k\\
&=(-1)^{q-i}\binom{q-1}{i-1}[z^{q-1}](1+z)^{q-1}\left(\frac{(1+z)^{n-q+1}-1}{(1+z)-1}\right)\tag{8}\\
&=(-1)^{q-i}\binom{q-1}{i-1}[z^{q}](1+z)^n\\
&\,\,\color{blue}{=(-1)^{q-i}\binom{q-1}{i-1}\binom{n}{q}}\tag{9}
\end{align*}
Comment:

In (3) we apply the rule $[p^{a-b}]A(p)=[p^a]p^bA(p)$.

In (4) we select the coefficient of $[p^{q-i}]$ according to (2). Note the sum starts with $k=q$ since smaller indices do not contribute due to the factor $\binom{k-1}{k-q}$.

In (5) we use the binomial identity
\begin{align*}
\binom{k-1}{i-1}\binom{k-i}{q-i}=\frac{(k-1)!}{(i-1)!(k-i)!}\,\frac{(k-i)!}{(q-i)!(k-q)!}=\binom{q-1}{i-1}\binom{k-1}{k-q}
\end{align*}

In (6) we shift the index and start with $k=0$. We also use $\binom{n}{k}=\binom{n}{n-k}$.

In (7) we apply (2) again and do some rearrangements in the next step.

In (8) we use the finite geometric series formula and observe that only the left term in parenthesis contributes to $[z^{q-1}]$.

Coefficient right part:
We obtain similarly as above for $i\leq q\leq n$:
\begin{align*}
\color{blue}{[p^q]}&\color{blue}{\sum_{k=i}^n\binom{n}{k}p^k(1-p)^{n-k}}\\
&=\sum_{k=i}^q\binom{n}{k}[p^{q-k}](1-p)^{n-k}\\
&=\sum_{k=i}^q\binom{n}{k}\binom{n-k}{q-k}(-1)^{q-k}\\
&=\binom{n}{q}\sum_{k=i}^{q}\binom{q}{k}(-1)^{q-k}\\
&=(-1)^q\binom{n}{q}\sum_{k=0}^{q-i}\binom{q}{q-k-i}(-1)^{k+i}\\
&=(-1)^{q-i}\binom{n}{q}\sum_{k=0}^{q-i}[z^{q-k-i}](1+z)^q(-1)^{k}\\
&=(-1)^{q-i}\binom{n}{q}[z^{q-i}](1+z)^ q\sum_{k=0}^{q-i}(-z)^k\\
&=(-1)^{q-i}\binom{n}{q}[z^{q-i}](1+z)^q\frac{1-(-z)^{q-i+1}}{1-(-z)}\\
&=(-1)^{q-i}\binom{n}{q}[z^{q-i}](1+z)^{q-1}\\
&=(-1)^{q-i}\binom{n}{q}\binom{q-1}{q-i}\\
&\,\,\color{blue}{=(-1)^{q-i}\binom{n}{q}\binom{q-1}{i-1}}\tag{10}
\end{align*}
Since (9) and (10) are equal the claim (1) follows.
Comment: This is terrific. It should be exactly what OP was looking for. (+1).
Comment: @MarkoRiedel: Many thanks for your nice comment. :-)
Comment: @epi163sqrt Thank you for providing such a detailed answer! It's exactly what I was looking for.
Comment: @YuzhenFeng: You're welcome! :-)
Answer: We seek to prove that with $1\le q\le n$ and $0\le p\le 1$ that
$$\sum_{k=q}^n {k-1\choose q-1} p^q (1-p)^{k-q}
= \sum_{k=q}^n {n\choose k} p^k (1-p)^{n-k}.$$
We start on the LHS with
$$p^q \sum_{k=0}^{n-q} {k+q-1\choose q-1} (1-p)^k
\\ = p^q [z^{n-q}] \frac {1}{1-z}
\sum_{k\ge 0} {k+q-1\choose q-1} (1-p)^k z^k
\\ = p^q [z^{n-q}] \frac {1}{1-z}
\frac{1}{(1-(1-p)z)^q}.$$
This is
$$(-1)^q \frac{p^q}{(1-p)^q}
\; \underset{z}{\mathrm{res}} \;
\frac{1}{z^{n-q+1}} \frac{1}{1-z}
\frac{1}{(z-1/(1-p))^q}.$$
Now residues sum to zero and the residue at infinity is zero so this is
minus the residue at $z=1$ plus  minus the residue at $z=1/(1-p).$ The
former is one by inspection. For the latter we need the Leibniz rule:
$$\frac{1}{(q-1)!}
\left(\frac{1}{z^{n-q+1}} \frac{1}{1-z}\right)^{(q-1)}
\\ = \frac{1}{(q-1)!}
\sum_{k=0}^{q-1} {q-1\choose k}
\frac{(-1)^k}{z^{n-q+1+k}} (n-q+1)^{\overline{k}}
\frac{1}{(1-z)^{1+q-1-k}} 1^{\overline{q-1-k}}
\\ = \frac{1}{(q-1)!}
\sum_{k=0}^{q-1} {q-1\choose k}
\frac{(-1)^k}{z^{n-q+1+k}} {n-q+k\choose k} k!
\frac{1}{(1-z)^{q-k}} (q-1-k)!
\\ = \sum_{k=0}^{q-1}
\frac{(-1)^k}{z^{n-q+1+k}} {n-q+k\choose k}
\frac{1}{(1-z)^{q-k}}.$$
Evaluate at $z=1/(1-p)$ to get
$$\sum_{k=0}^{q-1}
(-1)^k (1-p)^{n-q+1+k} {n-q+k\choose k}
\frac{(1-p)^{q-k}}{(-1)^{q-k} p^{q-k}}.$$
Collecting the two contributions we find
$$1 - (1-p)^{n-(q-1)}
\sum_{k=0}^{q-1} {n-q+k\choose k} p^k
\\ = 1 - (1-p)^{n-(q-1)} [z^{q-1}] \frac{1}{1-z}
\sum_{k\ge 0} {n-q+k\choose k} p^k z^k
\\ = 1 - (1-p)^{n-(q-1)} [z^{q-1}] \frac{1}{1-z}
\frac{1}{(1-pz)^{n-q+1}}$$
On the other hand we get for the RHS
$$1 - \sum_{k=0}^{q-1} {n\choose k} p^k (1-p)^{n-k}$$
so we need to show that the coefficient extractor term is equal to the
sum, which yields
$$[z^{q-1}] \frac{1}{1-z}
\sum_{k\ge 0} {n\choose k} p^k (1-p)^{n-k} z^k
= \; \underset{z}{\mathrm{res}} \;
\frac{1}{z^q} \frac{1}{1-z} (pz+1-p)^n.$$
Now put $z/(pz+1-p) = w$ so that $z = (1-p) w / (1 - pw)$ and
$dz = (1-p)/(1-pw)^2 \; dw$ as well as $pz+1-p = (1-p) / (1-pw)$
to obtain
$$\; \underset{w}{\mathrm{res}} \;
\frac{1}{w^q} \frac{1-pw}{1-w}
\frac{(1-p)^{n-q}}{(1-pw)^{n-q}} \frac{1-p}{(1-pw)^2}
\\ = (1-p)^{n-(q-1)} \; \underset{w}{\mathrm{res}} \;
\frac{1}{w^q} \frac{1}{1-w}
\frac{1}{(1-pw)^{n-q+1}}.$$
This is the claim.
Comment: @MarkoRiedel: Very nice answer and instructive solution. (+1)
Comment: Thanks for your proof. But is there another method without using complex analysis?


Does the VIF make sense for a model with categorical variables?

Question: I'm trying to detect multicollinearity in my model, it has count response variable and some proportional and one categorical explanatory variable called site. In R the model looks like this:
glm(Total ~ percent_flower + Percent_typeofflower +
             Percent_ohtertypeoflower + Site,
        family=poisson, data=pollinator)

I want to know whether I should calculate the vif() without Site, it doesn't seem to make sense to calculate a correlation between a numerical variable and a categorical one.
Also if I have to keep Site in to calculate the vif(), will running a GLMM instead of a GLM take care of the collinearity issue?
Comment: I'm not sure about the conceptual difficulty - if there was a correlation between Site and your other variables it would simply mean that there was a meaningful difference in one or more of your other explanatory variables dependent on changing sites. This seems very plausible and worth checking.
Comment: I don't think I'm saying that - I'm more saying that you appear to be assuming that the other variables are independent of Site simply because Site is categorical, and that doesn't seem reasonable. In fact it seems very plausible that one or more of the other variables in your model is strongly influenced by Site, and that needs to be considered in your analysis.
Comment: @RobertdeGraaf are you saying i should be adding interactions between sites and the other variables?
Answer: My recommendation, if you want to test for collinearity and have categorical variables as well as continuous ones and are using R is to use the perturb package. The idea here is to add small amounts of random noise to the variables - by adding uniform or normal noise to the continuous variables and by shifting some categorical ones - and seeing what happens to the coefficients.
Answer: From the code I have seen statisticians don't usually include the categorical covariates. However, I generally run a covif with and without the categorical covariates, just to see whats going on. I additionally check for collinearity with boxplots of categorical covariate vs categorical covariate and cat cov vs continuous cov.
Zurr et al. 2010 do not include site in their covif function. Check out the supplementary data. I'm sure you can find some nice info there on collinearity as well.
http://onlinelibrary.wiley.com/doi/10.1111/j.2041-210X.2009.00001.x/abstract


Local mail exchange with DNS servers

Question: I have a problem with correctly setting up a working infrastructure for testing mail spoof preventing mechanisms.
As stated in a graph below, I have 2 mail servers (centos1 & 2) and 2 DNS servers. It is obligatory to have one DNS per host to test SPF records.
The problem is, that two DNS cannot communicate with each other. I mean, they can ping but I do not really know how to set up them to provide A or MX records for other domain.
In real networks those local DNS servers have to communicate to root DNS that provides domain names to the local ones. Should I set up additional root DNS server? If so, how to do it? I have looked almost everywhere on the internet and found nothing...
For example, I want to send an email from firstname.lastname@example.com to email@example.com, but when I do so, mail exchange demon shows up a following message:
<firstname.lastname@example.com>: Host or domain name not found. Name service error for
    name=another.local type=A: Host not found

My present configuration for one DNS is (the second one is just like that with only difference in domain name):
Forward zone:
$TTL 1D
@       IN SOA  dns1.example.local. root.example.local. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
@       IN      NS      dns1.example.local.
@       IN      A       192.168.21.131
dns1    IN      A       192.168.21.131
host    IN      A       192.168.21.131
centos1 IN      A       192.168.21.128
centos2 IN      A       192.168.21.129
another.local   IN      A       192.168.21.130
example.local   IN      MX 5    centos1.example.local.

Reverse zone:
$TTL 1D
@       IN SOA  dns1.example.local. root.example.local. (
                                        0       ; serial
                                        1D      ; refresh
                                        1H      ; retry
                                        1W      ; expire
                                        3H )    ; minimum
@       IN      NS      dns1.example.local.
@       IN      PTR     example.local.
dns1    IN      A       192.168.21.131
host    IN      A       192.168.21.131
centos1 IN      A       192.168.21.128
centos2 IN      A       192.168.21.129
131     IN      PTR     dns1.example.local.
128     IN      PTR     centos1.example.local.
129     IN      PTR     centos2.another.local.

And named.conf
options {
        listen-on port 53 { 127.0.0.1;192.168.21.131; };
        listen-on-v6 port 53 { ::1; };
        directory       "/var/named";
        dump-file       "/var/named/data/cache_dump.db";
        statistics-file "/var/named/data/named_stats.txt";
        memstatistics-file "/var/named/data/named_mem_stats.txt";
        recursing-file  "/var/named/data/named.recursing";
        secroots-file   "/var/named/data/named.secroots";
        allow-query     { localhost; any; };

        /*
         - If you are building an AUTHORITATIVE DNS server, do NOT enable recursion.
         - If you are building a RECURSIVE (caching) DNS server, you need to enable
           recursion.
         - If your recursive DNS server has a public IP address, you MUST enable access
           control to limit queries to your legitimate users. Failing to do so will
           cause your server to become part of large scale DNS amplification
           attacks. Implementing BCP38 within your network would greatly
           reduce such attack surface
        */
        recursion yes;

        dnssec-enable yes;
        dnssec-validation yes;

        /* Path to ISC DLV key */
        bindkeys-file "/etc/named.root.key";

        managed-keys-directory "/var/named/dynamic";

        pid-file "/run/named/named.pid";
        session-keyfile "/run/named/session.key";
};

logging {
        channel default_debug {
                file "data/named.run";
                severity dynamic;
        };
};

zone "." IN {
        type hint;
        file "named.ca";
};

zone "example.local" IN {
        type master;
        file "forward.example.local";
        allow-update {none; };
};

zone "21.168.192.in-addr.arpa" IN {
        type master;
        file "reverse.example.local";
        allow-update {none; };
};

include "/etc/named.rfc1912.zones";
include "/etc/named.root.key";

To sum up, how to make my mail servers able to exchange mails with one DNS for every one of them?
Please be sure to check the graph below, I think it can explain a lot.
network graph
Looking forward to hearing from you! :D
Comment: It is a project which you run on VMware Workstation thus I vote to close as it does not belong here on ServerFault. That being said, it seems like you are in way over your head. First learn how DNS works, then how to set up and configure name servers. Then learn about mail servers and how they interact and use the DNS. I believe your understanding of DNS is a major issue here.
Comment: Did you really use `.local` TLD or is this just bad obfuscation. `.local` is reserved for multicast DNS, you shouldn't use it for "real" zones.
Comment: It is changed now, but as long as I understand, it has no impact on my project since it is all done in my local network without connecting to external networks. I just want to configure 2 mail servers, each with its own domain to later implement spf, dkim and dmarc mail security. If I am wrong I am sorry but this is my first adventure with dns servers.
Comment: Are you asking where to add the glue records? (I do not see why you would be running *two* name servers at all for your test. Either simulate a typical setup - different nameservers for the tld and each domain, or just exclude DNS from your test and point them to a single instance that has all the records.)
Answer: I think you have incorect record here :
another.local   IN      A       192.168.21.130

Your zone is for domain/hostname : example.local
If you want to add new domain with : another.local
Create new zone for it.

Local mail exchange with DNS servers


Positioning two blocks on the same line

Question: I have this HTML code:

    Lorem ipsum dolor sit amet, nunc euismod nisl nam euismod, quis maecenas blandit ac, neque sed ut pulvinar, lectus sagittis sapien mauris per risus vel. Ligula sapien sed morbi cras tellus commodo. Rutrum mattis accumsan, hac sed praesent, neque tortor neque, commodo mauris sagittis turpis, faucibus sed ultrices tempor interdum. Lobortis assumenda nisl, posuere cras sit risus egestas bibendum nec, magna in, sed mattis pharetra felis nulla vitae aptent, in semper et...

I would that the two blocks are positioned on the same line. I use this CSS:
.right {
width: 250px;
background-color: orange;
float: left;
}

.left {
width: 100px;
background-color: orange;
float: left;
}

It's good, but I want that the right side (the text) is not large 250px, but 100%. If I put width:100%, the block is not on the same line.
How can I do this?
Comment: 100% of what? what is the size for their parent's?
Comment: 100% of the page, I want to use all the width that is on the right
Answer: Here is my solution to your problem - you set the width on the left item, and the margin on the right item. The left item is floated, the right item isn't. I have also made the display of the right item "block".
.right {
    display: block;
    margin-left: 100px;
    width: auto;
    background-color: orange;
}

.left {
    width: 100px;
    background-color: orange;
    float: left;
}

Answer: For floated elements, if you want to use percentage widths, you should calculate the width of each:
.right {
width: 50%; /*or 45%*/
background-color: orange;
float: left;
}

.left {
width: 50%; /*or 55%*/
background-color: orange;
float: left;
}

Then they will display on the same line.
Also, if there are margins or paddings, you should take this into consideration when calculating the widths as if you set both to 50% but there is a margin of 10px, it will still force the next element onto a new line.
To make the .right element calculate the width, you need to set its width to width: auto; and counter-margin the .left element: margin-left; 100px; (where 100px is equal to the .left elemtents width).
Example for you here.
Answer: delete the width for the right class and the float. This will make the right class to get the remaining width of the parent element.
.right {
    background-color: orange;
}
.left {
    width:250px;
    background-color: orange;
    float:left;
}

example http://jsbin.com/ayaha3

Positioning two blocks on the same line


Testing the linearity assumptions for categorical predictors

Question: Me and my friend are currently writing our final essay but we are having some problems with our analysis…
We are doing an hierarchical multiple regression, and we has some categorical predictors (like two-levels variables as biological and non-biological, and some with more levels like grade). Before doing this we controlled for several assumptions, the linearity assumption included. We have some issues with our linearity plots that we do not understand.
Judging from our plots, there is no linear relationship between some of our predictor variables and the dependent variable, although, in our performed regression analysis the variable have a significant association.
How can we understand this? Should we take these predictors out of the regression, or can we still include them? And if we can include them, what is the reasoning for this?
We would be so greatful if someone could help us with this! :)
Here are two picture of two of the scatterplots, as examples:
Comment: Welcome to Cross Validated! How would you expect a linear relationship to look in plots like you gave?
Comment: More linear, like a diagonal stretch i assume. Just so the linearity-assumption that the regression requires is met
Comment: Consider providing more information about the data you are analyzing and the questions you are trying to answer, incl. what's PSE, creIR and Power? Also, the first scatterplot suggests the relationship between Power and PSE may be non-linear (this could be addressed by transforming Power). In the second scatterplot there is a lot of overplotting; it may be more instructive to look at the average PSE for the two levels of creIR.
Answer: The "linearity" assumption (more properly, "correct functional specification" assumption) states that the means of the conditional distributions of Y|X all fall on the function you specify.
A flat line is still a line, so lack of relationship does not imply violation of linearity.
Also, linearity is automatically satisfied for a two-level (binary) X, since the linear model imposes no restrictions on the mean function (a line always passes perfectly through two points having x separation).
Similarly, full dummy variable representations of categorical predictors also imply no restrictions, so linearity is automatically true there as well, as long as there is no other X in the model.
However, with multiple categorical predictors, all modeled with full dummy sets, there will be restrictions unless a saturated model having all possible interactions is modeled. Thus, violation of linearity refers to presence of interaction in this case.
Comment: Okay, Thank you for your answer! So if we have horizontal lines when plotting IV and DV, we can still put the IV in the regression analysis? :)
Comment: First, you need a partial regression plot to detect effects visually. Second, there is no violation of assumption by including a weak predictor, but you might want to exclude them for reasons of parsimony and accuracy of the estimated model. Including weak predictors adds noise to the predictions that is caused by variability in the estimated parameters.


Overthrow and throw-by

Question: The two terms are very popular in my locality. According to my teacher,

overthrow: is when fielder near the pitch misses throw from fielder at far
   off in field.

He defined "throw-by" as the event when "batsman has not touched the ball with his bat or gloves or any part of his body, he attempts run, fielder throws ball but misses run out"
Surprisingly, I found no mention of "throw-by" on the internet or in the laws as my teacher said.
Did he confuse "throw-by" with another popular terminology? Or is there really some "throw-by" phenomenon, conspicuously absent from the internet?
Answer: This term is not known to a group of cricket enthusiasts and fans, and a Google search using various parameters relating to cricket wicketkeepers and overthrows did not find any results with the phrase.
I conclude that this term specifically for an overthrow by the wicketkeeper is not common in the world and probably limited to a small region or regions.
Answer: As much I understand the context, your teacher probably wants the differentiate a bye run and a normal run in the context of overthrow. These two can also be looked into as two entirely different context. Whatever comes off the bat is normal run and whatever does not come off the bat are extra run - in our context a bye run. On the other hand overthrow is any run conceded by the fielding team after the event of throw by the fielders, as you described correctly above. The term, according to my knowledge, is not any official term, but it is widely used to convey the sense of Bye + Overthrow in different parts of India.
Cheers.

Overthrow and throw-by


How use global parameters in Forman?

Question: I'm new in Foreman, and I want to use a parameter for all my hosts managed by puppet and I think to use the global parameters it's a good way. But I can't understand how use it.
For exmple if I take the ntp module and if I want to have the same ntp server on all the host how I have to declare the global parameter and the documentation are very poor...
I tired :
ntp_servers = time.nrc.ca
$::ntp::servers = time.nrc.ca
::ntp::servers = time.nrc.ca
ntp::servers = time.nrc.ca
No ones match.
Answer: I assume you use the foreman WebGui:
If you are in the Smart Class Parameter tab of the ntp class, select servers, check the Override Box an then select array for Parameter type. Then input the list of your desired timeserver in the following form:
["timehost1.domain.tld","timehost2", ...]

It took me a while myself to figure that out.
In general, you need to know or find out which type is expected from the puppet module. I find myself looking into the code of the modules if it is not clear in the first place. Also, if you want to make a parameter over writable somewhere down the road of host groups or whatever you use for node of different types, I found that you have to set the default yourself. The builtin default only works while Override is unchecked. At least for modules like ntp which have a params subclass. Otherwise you end up with errors stating the parameter was not found/could not be set or similar.
I'm fairly new to puppet myself, so if anyone has a better explanation I'd be glad.
Cheers, Christoph
Screenshot
Comment: "ntp_servers" is a global parameter that you can set under Configure > Global parameters, but the other examples you gave are class parameters and Christoph's answer is right.  Most modules will use class parameters, you'd have to explicitly change them to use $::ntp_servers then inside the manifest if you wanted to use globals for some reason.
Comment: Thanks for your answer. Yes I used the webui. I undertand the smart Class but it's global parameter who I want to understand (and smart Variables).
Comment: @Darkjeff Yeah, I saw that on reread of the question. Sorry for the quick shooting. I dimmly remember playing around with that an then ending up with using the class parameters, which then are global for the installation (or at least the environment in which you set the parameter). I'm not really sure the Foreman global parameter are intended the way you try to use them, since foreman can do way more than be a puppet enc.
Comment: Ok that answers to my question. So I have to use class parameter. What do you use for big value like 30 user creation ? It's a big hash not really easy to maintain.
Comment: So, after a look in the foreman manual and the comment from m0dlx: I could for example use ´my_ntpservers´ as a global parameter if I intend to write my own wrapper class, which then uses this parameter?
Comment: Darkjeff: not much you can do about a large hash in a value really.  If a text editor's easier then Hiera may be better, or the next version of Hammer CLI should add an interface to manage values.  Christoph: yep.

How use global parameters in Forman?


Falha ao fazer um alteração no banco de dados

Question: Quando vou fazer um Update na tabela Impressora meu programa está se fechando sozinho, ao depurar o programa o seguinte erro foi acusado:

Meu Update está dessa forma:
begin
    if cdsImpressora.state in[dsedit] then
    begin
      dmDatabase.SQLConnection.Execute('UPDATE Impressoras SET '+
         ' PATRIMONIO ='''+ cdsImpressoraPATRIMONIO.AsString+''','+
         ' PATRIMONIOBANDEJA = '''+ cdsImpressoraPATRIMONIO.AsString+''','+
         ' PATRIMONIODUPLEX = '''+ cdsImpressoraPATRIMONIODUPLEX.AsString +''','+
         ' PATRIMONIOMAILBOX = '''+ cdsImpressoraPATRIMONIOMAILBOX.AsString +''','+
         ' NUMEROIP = '''+ cdsImpressoraNUMEROIP.AsString + ''','+
         ' ENDERECOEXTERNO = '''+ cdsImpressoraENDERECOEXTERNO.AsString +''','+
         ' NUMERONF = '''+ cdsImpressoraNUMERONF.AsString +''','+
         ' NUMEROPORTA = '''+ cdsImpressoraNUMEROPORTA.AsString+''','+
         ' NUMEROSERIE ='''+ cdsImpressoraNUMEROSERIE.AsString+''','+
         ' SENHA = ''' + cdsImpressoraSENHA.AsString+''','+
         ' USUARIO = ''' + cdsImpressoraUSUARIO.AsString+''','+
         ' CAMINHO = ''' + cdsImpressoraCAMINHO.AsString+''','+
         ' SETORINSTALACAO ='''+ cdsImpressoraSETORINSTALACAO.AsString+ ''',' +
         ' CODIGOMODELO = ' + cdsImpressoraCODIGOMODELO.AsString+ ',' +
         ' FRANQUIA = ' +iif(cdsImpressoraFRANQUIA.AsString='','0',cdsImpressoraFRANQUIA.AsString)+','+
         ' VALORIMPRESSAO = ' +iif(cdsImpressoraVALORIMPRESSAO.AsString='','0',TrocaVirgPPto(cdsImpressoraVALORIMPRESSAO.AsString))+','+
         ' TIPOPATRIMONIO = '''+cdsImpressoraTIPOPATRIMONIO.AsString + ''','+
         ' PATRIMONIOOUTRO = '''+cdsImpressoraPATRIMONIOOUTRO.AsString + ''','+
         ' VALORIMPRESSAOCOLOR = '+iif(cdsImpressoraVALORIMPRESSAOCOLOR.AsString='','0',TrocaVirgPPto(cdsImpressoraVALORIMPRESSAOCOLOR.AsString))+','+
         ' FRANQUIACOLOR = '+ iif(cdsImpressoraFRANQUIACOLOR.AsString='','0',cdsImpressoraFRANQUIACOLOR.AsString)+','+
         ' CORTESIAIMPRESSAO = '+iif(cdsImpressoraCORTESIAIMPRESSAO.AsString='','0',cdsImpressoraCORTESIAIMPRESSAO.AsString)+','+
         ' VALOREXCEDENTEIMPRESSAOCOLOR =' +iif(cdsImpressoraVALOREXCEDENTEIMPRESSAOCOLOR.AsString='','0',TrocaVirgPPto(cdsImpressoraVALOREXCEDENTEIMPRESSAOCOLOR.AsString))+','+
         ' VALORFIXOMENSAL = ' +iif(cdsImpressoraVALORFIXOMENSAL.AsString='','0',TrocaVirgPPto(cdsImpressoraVALORFIXOMENSAL.AsString))+','+
         ' VALOREXCEDENTEDIGITALIZACAO = '+iif(cdsImpressoraVALOREXCEDENTEDIGITALIZACAO.AsString='','0',TrocaVirgPPto(cdsImpressoraVALOREXCEDENTEDIGITALIZACAO.AsString))+','+
         ' VALORDIGITALIZACAO = '+iif(cdsImpressoraVALORDIGITALIZACAO.AsString='','0',TrocaVirgPPto(cdsImpressoraVALORDIGITALIZACAO.AsString))+ ','+
         ' STATUS = '+QuotedStr(cdsImpressorastatus.AsString)+','+
         ' FRANQUIADIGITALIZACAO = '+iif(cdsImpressoraFRANQUIADIGITALIZACAO.AsString='','0',TrocaVirgPPto(cdsImpressoraFRANQUIADIGITALIZACAO.AsString))+
         ' where CODIGO = '+cdsImpressoraCODIGO.AsString, nil);
    end;
  end;
  cdsImpressora.Close;
  sdsImpressora.CommandText := 'select * from Impressoras where codigo = 0' ;
  cdsImpressora.Open;
  MostraFila(0);

E minha tabela impressora está configurada da seguinte forma:

Se tiverem alguma ideia de o que possa estar ocorrendo. Pois para inserir no banco o erro não ocorre.
Comment: Muito provavelmente um de seus campos inteiros está vazio.
E vejo que você ainda não aprendeu a usar o QuotedStr.
Answer: O seu CODIGOMODELO é um integer no banco e no seu update você não está fazendo o IIF
' CODIGOMODELO = ' +iif(cdsImpressoraCODIGOMODELO.AsString='','0',cdsImpressoraCODIGOMODELO.AsString)+','+

Uma coisa que você pode fazer para lhe ajudar a identificar os problemas. É separar a sua instrução sql em uma variável, e usando o modo debug do delphi, avaliar o valor da variável para identificar possíveis problemas de concatenação.
Uma das formas de inspecionar é no modo debug você apertar a sequência Ctrl+F7 e usar o Evaluate/Modify para ver o valor da variável.
Na imagem estou inspecionando a minha variável update, podendo copiar o texto que está no result e analisar melhor usando alguma ferramente de banco de dados.
Comment: Eu devo usar `iff` se for `Integer` no banco? Desculpe a pergunta é que sou iniciante em Delphi e esse código não fui eu quem desenvolveu
Comment: Digamos que sim, sempre que o campo for integer, tem que montar a instrução passando um integer e como você está usando um AsString, se o valor do campo for `nil` o delphi deixa em branco a tua concatenação. Mas o seu estilo de programação está muito fora de padrões de desenvolvimento que o Delphi proporciona, lhe aconselharia a usar os componentes da paleta `Data Controls` junto com os da `Data Access` e seus `DataSets`. Unindo esses componentes, você não precisa digira uma linha de código se quer para fazer um simples CRUD.
Comment: Outra coisa, se você está iniciando com Delphi, pq Delphi? Eu particularmente já não inicio mais nenhum projeto em Delphi, meus novos projetos são todos em C#.
Comment: Sim, na verdade eu sugeri que fosse atualizado para Java que é uma linguagem que tenho mais domínio porém fui instruído a apenas fazer as alterações necessárias em delphi mesmo
Comment: Fiz essa alteração que tu sugeriu na tua resposta, porém o mesmo erro continuou ocorrendo
Comment: Fiz uma edição na resposta
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/51707/discussion-between-pablo-vargas-and-r-santos).
Answer: Faz um theparam entre banco e seu update para que você consiga identificar qual é o campo que esta causando o erro de conversão.
Uma técnica que utilizo nesse caso é tirar um pedaço do update e deixar poucos campos e ir adicionando os outros gradativamente , dessa forma você verá qual campo esta dando o problema.


How to read JSON from external URL and display in a block?

Question: I want to load some JSON data from an external URL and display it in a block.
How do I go about that?
Answer: For the most basic solution, you would need to:

Create a custom module;
Implement hook_block_info and hook_block_view to define your block (see block_example.module for examples);
When generating the block content, use drupal_http_request to retrieve the json data from your URL and process the return value as needed.

A more complex version of your custom module could for instance involve implementing hook_block_configure to make the URL configurable from the UI, using theme functions to generate the HTML output, and caching/storage of the return value.
A completely different approach, which may or may not be appropiate in your case, would be to use the Feeds module to retrieve the JSON and store the data as nodes, and use the Views module to generate a block listing those nodes.
Answer: Maybe too simple of an approach, but if all you truly want to do is display JSON data (no need to store it), then I'd add a new block as "Full HTML" and then add some JQuery.
To embed an HTML snippet it would be:

The method would be similar for JSON, only you'd have to do some formatting of the return that would be custom to your application.
Here's a working example pulled from JQuery.getJSON documentation customized ever so slightly to work inside a Drupal Block:

Comment: Not necessarily. Depends on whose server is faster: your server or the JSON resource? True, there will always be a delay when for JQuery to load after the document renders. If you decide to cache the result, a lightweight approach drupal way would be to use drupal_http_request as @marcvangend advised and store the result in a revisioned node for history.
Comment: pretty cool, thanks. The json doesn't change often so I might be better off storing or caching it, that should improve the load time


Task: Give an example for a group $(B, \circ) $ and a subgroup $U \subsetneq B$

Question:
Task (no homework): Give an example for a group $(B, \circ) $ and a
  subgroup $U \subsetneq B$.

Can you please check if my solution is fine?
Let the set be $B= \left\{-1,1\right\}$, let's take multiplication, so we have the group $(B, \cdot)$.
All axioms of a group are satisfied, so it's indeed a group.
Let the set U be $U= \left\{1\right\}$, so we already have that $U$ is a subset of $B$, and it's a group too, thus it's a subgroup $(U, \cdot)$

Is it correct like that?
Comment: looks fineto me
Answer: I'm not sure how formal you want to be. Your example is correct, but you may be asked to prove it.
Here's a more slightly formal approach: Let $B=\{-1,1\}$. Let $\cdot$ stand for the multiplication operator. Then $(B, \cdot)$ is a group as $\cdot$ is associative (by definition of multiplication), the elements in $B$ are closed under multiplication ($1\cdot1 = 1, 1\cdot -1 = -1, -1\cdot 1 = -1, 1 \cdot 1 = 1$), we have an identity element, namely $1$, and we have an inverse for each element: $1\cdot 1 = 1$, $-1 \cdot -1  = 1$.
Suppose we take $H = \{1\}$. We will show $H$ is a subgroup of $B$.
To do so we'll apply a subgroup test. In particular, I'll apply the one step subgroup test which states "Let $G$ be a group and let $H$ be a non-empty subset of $G$. If for all $a,b \in H$, $a \cdot b^{-1} \in H$ then $H$ is a subgroup of $G$."
Well in our case we have a pretty simple subset $H$. Still we need to check what the test states: Do we have a group? Yes, $B$. Do we have a non-empty subset of $B$? Yes, $H$. For all $a,b \in H$ is $a \cdot b^{-1} \in H$? Well, we only have element, namely $1$ and $1$ has it's own inverse (e.g., $1 \cdot 1 = 1$) so let $a = 1$ and $b = 1$, then $b^{-1} = 1$ and $a\cdot b^{-1} = 1 \cdot 1 = 1$ and $1 \in H$. So $H$ is a subgroup of $B$ by the one step subgroup test.
Clearly $H \subset B$ and $H \not = B$. Thus $H$ satisfies $H \subsetneq B$ and $H$ is a subgroup of $B$ by the one step subgroup test.


How does the LASSO regularization parameter affect the number of features retained?

Question: I am working on a project where I am implementing Lasso regression in R for feature selection and my scenario is as follows.
For the minimum value of $\lambda$ most of the corresponding coefficients are zero (40 out 45 coefficients are zero). It is said that the coefficients will become zero when $\lambda$ is too high. On the contrary for me, the $\lambda$  value is very small (actually to the power of -5) i.e. I have a very small $\lambda$ value and most of the coefficients are zero.
So, I have a few questions listed below:

Is this scenario common? Can I take any measures to prevent it?
Is selecting by Lasso not suitable for feature selection in my scenario? If so, what are the other methods I can use?

Edit
Added R code below:
    coef(cv.glmmod, s = "lambda.min")[which(coef(cv.glmmod, s = "lambda.min") != 0)]
    > 6.456279e-05 3.838600e-07 1.356334e-05
    colnames(Final_raw)[which(coef(cv.glmmod, s = "lambda.min") != 0)]
    > "smart_1_raw"   "smart_189_raw" "smart_198_raw"
    plot(cv.glmmod)
    best_lambda <- cv.glmmod$lambda.min
    best_lambda
    > 9.175735e-05
    (plot(cv.glmmod$glmnet.fit))

P. S. : I have also tried Ridge and Elastic net and the results were similar as the above.
After Up sampling:

Output of plot(cv.glmmod)

Output of plot(cv.glmmod$glmnet.fit)
Comment: Can you upload a plot of the coefficients versus lambda? `plot(model)` (`plot(model$glmnet.fit)` for CV'd models) gets you this in R, not sure about Python implementations.
Comment: @Dex Groves. I have Uploaded the graphs and code.
Comment: These look very suspect. Your MAE seems low (though I don't know your target variable, so maybe it's reasonable). SE in error across folds is huge. Is your response highly skewed so that it is almost entirely one class? Is it possible that your covariates include something that is leaking, like a copy of the response variable?
Comment: Apologies for late reply. As you said the response (Binary variable)  in the data set is highly skewed. So I did up sampling to even  the 0's and 1's in the data. I have uploaded the "plot(model)" , "(plot(model$glmnet.fit)"  in the "edit 2" section above. Do you find these graphs better?
Comment: Those are much better, now you have 12 nonzero coefficients! If your response is binary, you should be setting `family="binomial"` for the glmnet call. Right now you're optimizing for squared error. I'm curious how changing the family would affect those graphs.
Answer: The penalty parameter $\lambda$ must be chosen after your design matrix is scaled. From section 2.5 of the glmnet paper:
$$N\alpha\lambda_\max = \max_{l \in \{1, \ldots, p\}} \left\vert \sum_{i=1}^n X_{il} y_i \right\vert$$
Note $\alpha = 1$ for lasso regression. $\lambda_\max$ is the value of $\lambda$ for which all coefficients are 0. This function will find $\lambda_\max$ from your input design matrix $X$ and response vector $y$:
find_max_lambda <- function(X, y) {
   mysd <- function(x) sqrt(sum((x-mean(x))^2)/length(x))
   sX <- scale(X, scale = apply(X,2,mysd))
   max(abs(colSums(sX*y/length(y) ) ) )
}

Comment: suppose `lambda_max = 1.54e-4` then you can try a regularization path of say 20 points using `seq(exp(log(lambda_max), log(lambda_max * 1e-4), length.out = 20)`. By the time you reach the smallest value in this sequence, almost all your coefficients will be non-zero.
Comment: The maximum lambda value i got is 0.0001541192 after implementing the above function.


Google Play Billing Library

Question: Na library Google Play Billing, alguém poderia me informar para que serve a parte handlePurchase(purchase)? O que ela faz exatamente?
@Override void onPurchasesUpdated(@BillingResponse int responseCode,
    List<Purchase> purchases) {
if (responseCode == BillingResponse.OK
        && purchases != null) {
    for (Purchase purchase : purchases) {
        handlePurchase(purchase);
    }
} else if (responseCode == BillingResponse.USER_CANCELED) {
    // Handle an error caused by a user canceling the purchase flow.
} else {
    // Handle any other error codes.
} }

É uma função obrigatória para o processo de compra ou, na verdade, a compra já ocorreu e eu poderia fazer qualquer coisa (notificar, abrir uma janela de aviso, consultar compra e etc.)?
O que significa essa parte?
Answer: Uma vez que o método onPurchasesUpdated chegou na chamada do método handlePurchase() significa que a compra já foi efetuada e processada com sucesso na Play Store (daí o responseCode == BillingResponse.OK && purchases != null).
Sendo assim, como você mesmo imaginava, o método handlePurchase() é apenas um método para fazer pós processamento da compra, daí você pode exibir um alerta, salvar os dados num BD local, enviar os dados da compra pra um backend etc.

Google Play Billing Library