How to display a loop inside the form?

Question: I want to display a query result into value=""
 for($record_count=0;$record_count<$record;$record_count++)
            { //loop for record count
                    ?>

       Invoice number or description <?php /*echo $id;*/echo $record_count;  ?>

                                       <INPUT TYPE="text" NAME="eg_description_<?php echo $record_count; ?>" Value="<?php
                                       foreach ($invoice_no as  $node_inv_no)
                                            {

                                               echo $node_inv_no->nodeValue;
                                            }
                                       ?>" size="10">

but the result in textbox :
CI_INV000243005CI_INV000239562

How can I make it the first textbox = CI_INV000243005
and the second one = CI_INV000239562
?
Thanks a lot
**<?php
       for($record_count=0;$record_count<$record;$record_count++)
            { //loop for record count
                    ?>

       Invoice number or description <?php /*echo $id;*/echo $record_count;  ?>

                       <?php
                       foreach ($invoice_no as  $node_inv_no)
                            {
                               $val = $node_inv_no->nodeValue;
                               echo '<INPUT TYPE="text" NAME="eg_description_' . $record_count. '" Value="' . $val . '" size="10">';
                            }
                        ?>

                       	**

How can I make them display one by one not in double and top to bottom not left into right ?
I want :
Invoice number or description 0 = CI_INV000243005
Invoice number or description 1 = CI_INV000239562
Currently it's displaying :
Invoice number or description 0 = CI_INV000243005 CI_INV000239562
Invoice number or description 1 = CI_INV000243005 CI_INV000239562
Thanks
<?php
$id=($_GET["clientID"]);
$max=($_GET["maxrecords"]);

echo "ID : ".$id."
";
echo "Max Records : ".$max."
";

$request_url = "http://10.21.13.12/solapp/documents/CINV/jadehttp.dll?SolApp&ClientID=$id&maxrecords=$max";
//$request_url = "http://10.21.13.12/solapp/documents/CINV/jadehttp.dll?SolApp&ClientID=42570935&maxrecords=100";
echo "Request URL : ".$request_url."
";

// Find only Posted status
$doc = new DOMDocument;                                        // Create a new dom document
$doc->preserveWhiteSpace = false;                              // Set features
$doc->formatOutput = true;                                     // Create indents on xml

$doc->Load($request_url);

$xpath = new DOMXPath($doc);
$query = '//Document/Status[. = "Posted"]/../DocumentID';
$amount_due = $xpath->query($query2);                                 // A list of matched elements

//$query = '//Document/Status[. = "Posted"]';
$invoice_no = $xpath->query($query);
$amount_due = $xpath->query($query2);                                 // A list of matched elements
$record =$invoice_no->length;                                // A list of matched elements

$invoiceArr = array();
foreach($invoice_no as  $node_inv_no) {
  $invoiceArr[] = $node_inv_no->nodeValue;
}

$amount_dueArr = array();
foreach ($amount_due as  $node_amount_due)
    {
        $amount_dueArr[] = $node_amount_due->nodeValue;
    }

?>

<?php for($record_count=0;$record_count<$record;$record_count++) { ?>

Invoice number or description <?php /*echo $id;*/echo $record_count;  ?>

<?php echo '<INPUT TYPE="text" NAME="eg_description_' . $record_count. '" Value="' . $invoiceArr[$record_count] . '" size="10">
'; ?>

 <?php echo '<INPUT TYPE="text" NAME="eg_payamt_' . $record_count. ' Value="' . $amount_dueArr[$record_count] . '" size="10">
'; ?>

<?php } ?>

I want to view pay ammount due too....but it's empty string on it,
May be I put a wrong loop ?
Any helps ?
thanks a lot
I can print out $amount_dueArr[$record_count] with : print_r($amount_dueArr[$record_count]);
but :
 <?php echo '<INPUT TYPE="text" NAME="eg_payamt_' . $record_count. '
 Value="' . print_r($amount_dueArr[$record_count]) . '"
 size="10">
';

showing empty box, anyone can help ?
should be like this, I forgot one " sign
 <?php echo '<INPUT TYPE="text" NAME="eg_payamt_' . $record_count. '
 "Value="' . print_r($amount_dueArr[$record_count]) . '"
 size="10">
';

Answer: Try something like this. Use following nested loop.
<?php

foreach ($invoice_no as  $node_inv_no) {
   $val = $node_inv_no->nodeValue;
   echo '<INPUT TYPE="text" NAME="eg_description_' . $record_count. '" Value="' . $val . '" size="10">';

}

?>

EDIT:
<?php
$invoiceArr = array();
foreach($invoice_no as  $node_inv_no) {
  $invoiceArr[] = $node_inv_no->nodeValue;
}
?>

<?php for($record_count=0;$record_count<$record;$record_count++) { ?>

Invoice number or description <?php echo $record_count;  ?>

<?php echo '<INPUT TYPE="text" NAME="eg_description_' . $record_count. '" Value="' . $invoiceArr[$record_count] . '" size="10">'; ?>

<?php } ?>

Comment: it's displaying ok but 4 times / double,  but how can I make it top and under,not left and right and display 2 times only ??
Comment: it seems because of two loops ?
Comment: OK. I thought you are executing complete inner loop for each outer loop entry.
Comment: $invoice_no = $xpath->query($query);                                 // A list of matched elements
Comment: i can't do print_r($invoice_no)
Comment: print_r($invoice_no); ==> DOMNodeList Object ( )
Comment: @NAVEED - In your code, the **name** field for each text field, for one value of outer for loop, will be **eg_description_0**  so it will be difficult to handle. I suggest, as in my answer above, to do **eg_description_0[]**. Then the posted values can be handled properly.
Comment: I can do the same with this :
Comment: ';
     ?>
Comment: empty string for $ammount_due ??
Answer: You can do the following but it is not recommended.
<?php foreach ($invoice_no as  $node_inv_no) { ?>
    <INPUT TYPE="text" NAME="eg_description_<?php echo $record_count; ?>" Value="<?php $node_inv_no->nodeValue;?>" size="10">
<?php } ?>

This post will be a good reference for further improvement to your code and logic handling posted data.
You can change your code to :
<?php foreach ($invoice_no as  $node_inv_no) { ?>
    <INPUT TYPE="text" NAME="eg_description_<?php echo $record_count; ?>[]" Value="<?php $node_inv_no->nodeValue;?>" size="10">
<?php } ?>

At the server side you will get an array of values submitted.
NOTICE:The ending [] at the name field of the input tag.
Comment: for($record_count=0;$record_count<$record;$record_count++)
      { //loop for record count

    foreach ($invoice_no as  $node_inv_no) { ?>

How to display a loop inside the form?


union of $[-r,r] ,r\in \mathbb{R}$

Question: I have some basis questions:
I know if  $r \in \mathbb{R}$,We cay say $\cup_{r \in \mathbb{R}}(-r,r)=(-\infty,\infty)$.
Even if $r \in \mathbb{Q}$, $\cup_{r \in \mathbb{Q}}(-r,r)=(-\infty,\infty)$ because $\mathbb{Q}$ is dense in $\mathbb{R}$.
But What is $\cup_{r \in \mathbb{R}}[-r,r]$?
I know $(-r,r) \subsetneq [-r,r] \implies\cup_{r \in \mathbb{R}}(-r,r) \subsetneq \cup_{r \in \mathbb{R}}[-r,r]\implies (-\infty,\infty)\subsetneq \cup_{r \in \mathbb{R}}[-r,r]$ where I am wrong?
Thanks in advance!
Answer: You can have $A_n$ and $B_n$ are subets of $X$ and $A_n$ is strictly included in $B_n$ and $\cup_n A_n=\cup_nB_n$. You just point a particular example of that situation.

union of $[-r,r] ,r\in \mathbb{R}$


Criar um BufferedImage a partir de um Array de int

Question: tenho um array unidimensional que contém as cores de uma imagem, onde a cada intervalo de 3 posições é representado a cor de um pixel (R,G,B):
int[] cores = {255, 0, 0, 0, 255, 0, 0, 0, 255};

Neste array eu teria 3 pixels, onde o primeiro seria [255, 0, 0] (Vermelho), o segundo [0, 255, 0] (Verde) e por fim [0, 0, 255] (Azul). A partir deste array, estou criando uma BufferedImage, tentando passar este array como parâmetro, porém não entendi a utilidade dos parâmetros offset e scansize (os dois últimos parâmetros passados ao setRGB).
BufferedImage rendered = new BufferedImage(getWidth(), getHeight(), this.imageType);

rendered.setRGB(0, 0, this.getWidth(), this.getHeight(), this.getData(), 0, this.getWidth());

A imagem criada gera apenas pixels com a cor azul, gostaria de saber se é possível passar este array como parâmetro ou se vou ter que setar pixel por pixel a nova imagem.
Answer: Não use o setRGB, pois embora funcione, será menos eficiente (pois estará setando um pixel por vez). Use o getRaster().getDataBuffer() da imagem para ter um acesso ao array de pixels diretamente.
O problema de ser apenas azul deve ter algo a ver com o canal Alpha. As cores são codificados em um int único (e não em três ou quatro, considerando o Alpha/transparência), então tem que fazer uma conversão. Fiz um ajuste no código para ficar eficiente e dar o resultado correto:
    int[] cores = { 255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255,
                    255, 0, 0, 0, 255, 0, 0, 0, 255
                                                    };

    // Converte array de origem em um array RGB
    int argb[] = new int[cores.length/3];
    for(int i=0; i<cores.length; i+=3) {
       argb[i/3] = -16777216; // 255 alpha
       argb[i/3] += (((int) cores[i] & 0xff) << 16); // vermelho
       argb[i/3] += (((int) cores[i+1] & 0xff) << 8); // verde
       argb[i/3] += ((int) cores[i+2] & 0xff); // azul
    }

    int larguraImagem = 3;
    int alturaImagem = 5;

    BufferedImage bi = new BufferedImage(larguraImagem, alturaImagem, BufferedImage.TYPE_INT_ARGB );
    final int[] a = ( (DataBufferInt) bi.getRaster().getDataBuffer() ).getData();
    System.arraycopy(argb, 0, a, 0, argb.length);

A saída será uma imagem de 3x5 com uma linha de cada cor (amplificada abaixo em 50 vezes):


Como usar o "echo" em uma view do Laravel?

Question: Estou querendo que no meu layout blade echo somente se a variável $errors estiver definida:
@section('mensagens')

        {{ isset($errors) ?
            '
'
              $errors->first('prontuario')
              $errors->first('senha')
            '
'
            :
            ''
        }}

    @show

Como eu faço para ele só mostrar essa div da classe alert-danger se a variável $errors do meu formulário estiver definida?
Answer: Você também pode fazer assim:
@section('mensagens')

        @if (count($errors))

                @foreach ($errors->all() as $error)
                    {{ $error }}
                @endforeach

        @endif

@show

Em vez de você setar cada erro individual, você percorre todos os erros e exibe cada um.
Comment: Deu certo!!! Ficou exatamente do jeito que eu queria, só aparecendo a div quando tiver o erro. Obrigado!
Comment: Por nada!
Estamos aqui para ajudar uns aos outros! ;)
Answer: Use @if e @endif
@section('mensagens')

      @if($errors)

                  {{ $errors->first('prontuario') }}
                  {{ $errors->first('senha') }}

      @endif

@show

Comment: Obrigado pela resposta. Mas mesmo não estando definida a variável $errors, ainda aparece o pequeno retângulo da div :/
Comment: Vai subindo o IF...
Comment: Não está indo. Ainda aparece a DIV alert mesmo subindo. Estou pensando em fazer essa parte em PHP...
Comment: Posta seu Controller onde está essa variável.
Comment: if ($validator->fails()) {
            return Redirect::to('/')
                ->withErrors($validator) // envia de volta todos os erros para o form
                ->withInput(Input::except('senha'));
        }


Show facet filter even if there is no result

Question: Is there a way to show the facet filter, even if the Search API module returns no result?
Comment: I know there a way to display a 'facet block' that will display facets ... I thought every facets would be displayed within this block, but It only lists 10 facets among the 14 it should have list (in my case)
Answer: Not really, the facets (both search api and solr) are made up from the results of the search, therefore if there are no results then it doesn't know what to populate the facets with.
Depending on your expected output you may be best creating a custom/views block to display some relevant content then re-write the urls to conform with the search query, acting like a search facet.
Answer: If you're using search_api_db, then you could use this patch :
https://www.drupal.org/node/2219897
It will add an option in your search server settings tyo allow a facet block to display facets even if there's no results !


In unsupervised learning, is a result of 2 clusters meaningful?

Question:
I used both agglomerative clustering and k-means on a dataset and see the results below. Result from agglomerative clustering was demonstrated with silhouette score while kmeans with inertia score. The inertia score was pretty smooth overall, while the highest silhouette score was at 2 clusters. I wonder people think would be optimal number of clusters and why? I know for silhouette scores usually the one with the highest value would be the optimal number of clusters but I rarely see results of two clusters so is two clusters even meaningful?
Comment: Two clusters can be meaningful, however, in your case, I would say your model did not find particularly good partitions, hence the slow and steady decline. You may want to try other models/distances/metrics.
Answer: My somewhat heterodox opinion is that a cluster analysis is meaningful if it has meaning and that this is a substantive question rather than a statistical one.
Sure, you can use the various statistical criteria for number of clusters as a sort of guideline, but these criteria often disagree with each other.
So ... look at the various cluster solutions.  Which one tells you something interesting, something surprising, something useful?  That's the one to go with.


Stripe Payment Using VSCode and XCode issue

Question: Hi every one I am trying to build E-Commerce IOS app ,  and I am using Stripe payment gateway with VSCode
but when I run this line of code : paymentContext.requestPayment()
it gives me this error : Error: Must provide source or customer
here is my Checkout view controller
class CheckoutViewController: UIViewController, CartItemDelegate {

@IBOutlet weak var tableView: UITableView!

@IBOutlet weak var selectPaymentMethodBtn: UIButton!
@IBOutlet weak var selectShippingMethod: UIButton!

@IBOutlet weak var serviceFeeLabel: UILabel!
@IBOutlet weak var delivaryFeeLabel: UILabel!
@IBOutlet weak var subtotalLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!

@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

var paymentContext : STPPaymentContext!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    setupTableView()
    setupPaymentInfo()
    setupStripeConfig()

}

func setupTableView(){

    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UINib(nibName: K.cellIdentifiers.CartItemCell, bundle: nil), forCellReuseIdentifier: K.cellIdentifiers.CartItemCell)

}

func setupPaymentInfo(){
    serviceFeeLabel.text = StripeCart.proccessingFees.penniesToFormattedCurrency()
    delivaryFeeLabel.text = StripeCart.shippingFees.penniesToFormattedCurrency()
    subtotalLabel.text = StripeCart.subtotal.penniesToFormattedCurrency()
    totalLabel.text = StripeCart.total.penniesToFormattedCurrency()
}

func setupStripeConfig(){

    let config = STPPaymentConfiguration.shared
    config.requiredBillingAddressFields = .full
    //config.requiredShippingAddressFields = [.name ,.phoneNumber]

    let customerContext = STPCustomerContext(keyProvider: StripeApi)
    paymentContext = STPPaymentContext(customerContext: customerContext, configuration: config, theme: .defaultTheme)

    paymentContext.paymentAmount = StripeCart.total

    paymentContext.delegate = self
    paymentContext.hostViewController = self

}

@IBAction func selectPaymentMethodClicked(_ sender: UIButton) {
    paymentContext.pushPaymentOptionsViewController()
}

@IBAction func selectShippingMethodClicked(_ sender: UIButton) {
    paymentContext.pushShippingViewController()
}

func removeItem(product: Product) {
    StripeCart.removeItemFromCart(item: product)
    tableView.reloadData()
    setupPaymentInfo()
    paymentContext.paymentAmount = StripeCart.total
}

@IBAction func placeOrderClicked(_ sender: RoundedButton) {

    paymentContext.requestPayment()
    activityIndicator.startAnimating()

}

}
and here is my STPPaymentContextDelegate code
extension CheckoutViewController : STPPaymentContextDelegate {
func paymentContextDidChange(_ paymentContext: STPPaymentContext) {

    if let paymentMethod = paymentContext.selectedPaymentOption {
        selectPaymentMethodBtn.setTitle(paymentMethod.label, for: .normal)
    } else {
        selectPaymentMethodBtn.setTitle("Select Method", for: .normal)
    }

}

func paymentContext(_ paymentContext: STPPaymentContext, didFailToLoadWithError error: Error) {

    let alertController = UIAlertController(title: "ERROR", message: error.localizedDescription, preferredStyle: .alert)
    let cancel = UIAlertAction(title: "Cancel", style: .cancel) { action in
        self.navigationController?.popViewController(animated: true)
    }
    let retry = UIAlertAction(title: "Retry", style: .default) { action in
        self.paymentContext.retryLoading()
    }

}

func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPPaymentStatusBlock) {

    let idempotency = UUID().uuidString.replacingOccurrences(of: "-", with: "")
    let data : [String : Any] = [

        "total" : StripeCart.total ,
        "customerID" : UserService.user.stripID ,
        "idempotency" : idempotency

    ]
    Functions.functions().httpsCallable("makeCharge").call(data) { result, error in

        if let error = error {
            print(error.localizedDescription)
            completion(STPPaymentStatus.error , error)
            return
        }
        StripeCart.clearCart()
        self.tableView.reloadData()
        self.setupPaymentInfo()
        completion(STPPaymentStatus.success, nil)
    }

}

func paymentContext(_ paymentContext: STPPaymentContext, didFinishWith status: STPPaymentStatus, error: Error?) {

    let title : String
    let msg : String
    switch status {
    case .success:
        activityIndicator.stopAnimating()
        title = "SUCCESS"
        msg = "THX FOR YOUR SHOPPING"
    case .error:
        activityIndicator.stopAnimating()
        title = "ERROR"
        msg = error?.localizedDescription ?? ""
    case .userCancellation:
        return
    }

    let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
    let action = UIAlertAction(title: "OK", style: .default) { action in
        self.navigationController?.popViewController(animated: true)
    }
    alert.addAction(action)
    self.present(alert, animated: true , completion: nil)

}

}
and here is my index.js code
const functions = require("firebase-functions");

const admin = require('firebase-admin');
admin.initializeApp()
const stripe = require("stripe")(functions.config().stripe.secret_test_key)
exports.createStripeCustomer = functions.firestore.document('users/{id}').onCreate(async (snap, context) => {
const data = snap.data();
const email = data.email;

const customer = await stripe.customers.create({ email: email })

return admin.firestore().collection('users').doc(data.id).update({ stripID: customer.id })

});
exports.makeCharge = functions.https.onCall(async (data , context) => {
const customerID = data.customer_id;
const total = data.total;
const idempotency = data.idempotency;
const uid = context.auth.uid;

if (uid === null) {
    console.log('Illegal Access')
    throw new functions.https.HttpsError('permission-denied' , 'Illegal access attempt')
}

return stripe.charges.create({
    amount: total,
    currency: 'JOD',
    customer: customerID
}, {
    idempotency_key: idempotency
}).then( _ => {
    return
}).catch(err => {
    console.log(err);
    throw new functions.https.HttpsError('internal' , err + 'Ln tutemm alsheraa')
});

})
exports.createEphemeralKey = functions.https.onCall(async (data, context) => {
const customerID = data.customer_id;
const stripeVersion = data.stripe_version;
const uid = context.auth.uid;

if (uid === null) {
    console.log('Illegal Access')
    throw new functions.https.HttpsError('permission-denied' , 'Illegal access attempt')
}

return stripe.ephemeralKeys.create(
    {customer: customerID} ,
    {stripe_version: stripeVersion}
    ).then((key) => {
        return key
    }).catch((err) => {
        console.log(err)
        throw new functions.https.HttpsError('internal' , 'unable to create ephemeral key')
    })

})
so how could I solve this problem
Note : I am Living in Jordan , I don't know why I told you that but I think it makes different
I found that the problem is inside stripe.charges.create({ ... }) code , thats why when I printed the customerID with error it gives me (.undefined) , and thats why when I check my stripe Logs for charge event I found this
My Charge Logs
but where is the problem exactly  ???
I tried to add my real visa but it showed me error says : Your card was declined
I tried to add the customerID manually hardcoded into my index.js but it shows me this error : "Cannot charge a customer that has no active card"
Answer: The error message Must provide source or customer means that you're trying to create a charge but either the source(card) is missing from the request or a customer ID that has a saved payment method in order for the charge to work.
The client-side code you've provided looks fine but would recommend checking your Stripe logs (https://dashboard.stripe.com/test/logs) to validate that if you're adding in a new source then the request to attach the source to customer object isn't failing.
I'm pretty certain that the error is coming from stripe.charges.create({ ... }). You'd want to check if the customerID is indeed present and if it is, does that customer have a source attached.


Distance based Spatial sampling

Question: I am struggling with spatial sampling of data which has Latitude & Longitude for data points. I need to do sampling such that no adjacent or nearby point should get  selected ( Need to give some radius criteria)in a sampled dataset. Kindly help.
Basically my problem statement is my sampled data set should have points which are 200 meters (or x meters) far away from each other.
Comment: Instead of throwing away data, consider adopting statistical procedures that are appropriate for your data, your model, and your problem.  Could you tell us more about those things?
Answer: You can build up your sample iteratively:
Start with a copy of your full dataset $S$.

Pick a single observation $i$ at random from $S$.
Compute the distances of all points in $i$ to $S$.
Remove all observations from $S$ that are too close to $i$ (as well as $i$ itself).
Repeat until you have a large enough sample or $S$ is empty.

A few things to note:

Not every observation has the same probability of being selected. Intuitively, observations in clusters are less likely to be selected as they compete with each other. Observations at the centre of a cluster are particularly unlikely to be selected.
It is not guaranteed that you will be able to get a sample of your desired size using this method. In case you run out of observations before reaching your desired sample size, you would need to repeat the whole procedure until you get lucky.
Comment: Unfortunately, even repeating the procedure does not fix the problem of unequal selection probabilities.  It's even worse than that, because the selection of one point can be strongly correlated with the selection of other points, even those far away.  The question as asked doesn't offer enough information to enable one to offer a reasonable solution.
Answer: @mrischard.
I solved this problem by multiplying LAT with LONG and sorted the data in ascending order (Similar LAT & LONG produces almost similar product when geographical area is of city size). After sorting , I will apply batching i.e. 1,2,3,4,5,6,.... , 10 And this will give me 10 samples in which points are 10 nearest point distant.

Distance based Spatial sampling


What is the x-axis on this plot of loss functions?

Question:
(source https://en.wikipedia.org/wiki/Loss_functions_for_classification)
A bit confused on how to interpret this graph. I understand that the y-axis here refers to loss, which is a function of the product of the predicted label and the actual label.
I also understand that the x-axis represented by $y_i f(x_i)$. $y = \{-1, 1\}$ represents the possible values of the binary output.
So then, why would $y_i f(x_i)$ ever exceed 1? If $f(x)$ represents the probabilities of $y$ = 1, then it shouldn't leave the bounds {-1,1}.
An example would be great appreciated.
Comment: I edited your question. We want out site to be self-contained, so there is no need to check external sources to understand the questions and answers. It is always better to paste image into your question rather then providing a ling (links became unaccessible, or web pages change over time).
Answer: Quoted from the Wiki article:

For computational ease, it is standard practice to write loss functions as functions of only one variable. Within classification, loss functions are generally written solely in terms of the product of the true classifier $y$ and the predicted value $f(\vec{x})$

In other words, you're plotting the loss against the univariate quantity $y f(\vec{x})$. The article is assuming that $y$ can take on the values 1 or -1 so that quantity allows you to have one plot for the loss regardless of what $y$ is.
Remember that $f(\vec{x})$ is the output of your classifier, which doesn't have to be -1 or 1, or even a probability. It's just a function. To see how you get the curves, plug in a few values of $f$ for each value of $y$ and see what it looks like.
Edit:
Hopefully this better explains the range. The loss is not restricted to be in the same range as the data itself. It is something that we define and varies depending on how we compute it. For example, if we use 0-1 loss, the loss is 0 if we match the label and 1 otherwise, there is no measure of distance.
Now, suppose that $f(\vec{x})$, returns an estimate $\hat{P}\left(y = 1 ~ | ~ \vec{x}\right)$ of the conditional probability $y=1$ as a function of our covariates. We could call it 1 if this is $> 0.5$ and -1 otherwise, but that's very coarse. Maybe we want to penalize the classifier less for being a "little bit" wrong than if it's confidently wrong - for instance saying the probability of 1 is 0.01 when in fact it was a 1.
The other loss functions allow us to take this into account. Also, notice that in the example you provided it is assuming that $f$ isn't a probability, but rather scaled to be between -1 and 1.
for square loss we use $(1 - y f(\vec{x}))^2$. If $f$ has the same sign as $y$ and magnitude 1, it is 0. If it has magnitude 1 and the opposite sign we get 4 (because inside we have $1 - -1$).
In general, you can have more or many different loss functions and output functions from your classifier. Usually, though, we'll deal with $f$ where it is estimating conditional class probabilities and lies in $[0, 1]$ or is scaled to $[-1, 1]$ which is the same thing. Which loss function we use depends on the problem we are trying to solve as well as our tastes. Some work better in certain situations than others and as far as I know it's tough to directly compare the output of different loss functions meaningfully.
Comment: Thanks -- see edits to the question, still a bit confused about the range of $yf(x)$.


Dynamically Adding BalancerMembers to Proxy

Question: Running Apache 2.4 I would like to be able to dynamically add  BalanaceMembers via API to a balancer group in the proxy_balancer module.
There are hints that this is possible. The documentation for mod_proxy_express says mod_proxy_balancer "provides dynamic growth."
I see that there is a BalancerGrowth directive, which I have tried adding but see no more slots in the balancer-manager page.
How do I provide for dynamic growth of proxy balancer members? How do I add and remove them? Where is the documentation for the API for adding, removing, and managing members?
Answer: this does not yet work for me because i do not see something in the user-interface how i would add it but maybe this helps you. i will give you an update if i find out something new
i used the configuration option mentioned in this thread
<code><Proxy balancer://myset growth=5>
    BalancerMember http://localhost:8080 route=8080
    BalancerMember http://localhost:8081 route=8081
    ProxySet lbmethod=bybusyness
    ProxySet stickysession=JSESSIONID
</Proxy>
</code>

EDIT
if you click on the lb-link there is a new input field and a checkbox. here you can add new workers. i don't know if one can remove them though. maybe just disabling hosts is possible


Sanity check: Will this SQL query join how I want?

Question: My deepest apologies for the query, that's legacy code for you. I basically want to check my code makes logical sense.
Essentially I want to return all rows of the "signatures" table where the "claim_id" = the "claim_id" on the "claims" table.
From that, I intend to check if the "signature_id" = null for each claim. If it does, that claim has no related signature, correct?
$SQL="
SELECT
    `claims`.`claim_id`,
    CONCAT(`insurers`.`insurer_name`,IF((`insurers`.`insurer_branch`<>''),CONCAT(' - ',`insurers`.`insurer_branch`),'')) as 'insurer',
    `claims`.`claim_number` as 'claim_number',
    UNIX_TIMESTAMP(claims.overflow_date) as 'overflow_date',
    UNIX_TIMESTAMP(claims.reassigned_date) as 'reassigned_date',
    UNIX_TIMESTAMP(claims.reassigned_from_fr_date) as 'reassigned_from_fr_date',
    UNIX_TIMESTAMP(claims.date_of_first_contact) as 'date_of_first_contact',
    UNIX_TIMESTAMP(`claims`.`date_surveyor_made_contact`) as 'date_surveyor_made_contact',
    UNIX_TIMESTAMP(`claims`.`date_of_inspection`) as 'date_of_inspection',
    UNIX_TIMESTAMP(`claims`.`surveyor_completed`) as 'surveyor_completed',
    UNIX_TIMESTAMP( CASE 1 WHEN (claims.overflow_date>0) THEN claims.overflow_date WHEN (claims.reassigned_date>0) THEN claims.reassigned_date WHEN (claims.reassigned_from_fr_date>0) THEN claims.reassigned_from_fr_date ELSE claims.date_of_first_contact END ) as 'date_of_first_contact_debug',
    `claims`.`date_surveyor_made_contact` as 'date_surveyor_made_contact_debug',
    `claims`.`date_of_inspection` as 'date_of_inspection_debug',
    `claims`.`surveyor_completed` as 'surveyor_completed_debug',
    `claims`.`letter_of_findings`,
    `claims`.`int_settlement_reason`,
    `claims`.`ext_settlement_reason`,
    `claims`.`original_surveyor_id`,
    `claims`.`surveyor_id`,
    `claims`.`broker_name`,
    `insurers`.`insurer_type`,
    `insurers`.`insurer_id`,
    `signatures`.`signature_id`,
    `signatures`.`claim_id`
FROM
    (((`claims` claims INNER JOIN `insurers` insurers ON claims.`insurer_id` = insurers.`insurer_id`)
    INNER JOIN `users` users ON claims.surveyor_id = users.user_id)
    LEFT JOIN `signatures` signatures on claims.claim_id = signatures.claim_id)
WHERE
    (`claims`.`claim_type` <> ".$conn->qstr(TYPE_DESKTOP).") AND
    (`claims`.`claim_type` <> ".$conn->qstr(TYPE_AUDIT).") AND
    (`claims`.`insurer_id` NOT IN ('".implode("','",$arrSURGE)."')) AND
    (`users`.`status` = ".$conn->qstr(STATUS_LIVE).") AND
    (`claims`.`claim_cancelled_id` = 0) AND
    $where
";

The code I've added is both the signatures. selectors, and the LEFT JOIN 'signatures' signatures on claims.claim_id = signatures.claim_id) line.
claim_id is PK on the claims table, and signature_id is PK on signatures table.
Thanks!
Comment: This question appears to be off-topic because it is about a [code review](http://codereview.stackexchange.com/).
Comment: is there a reason you cant test this yourself to check if the result is according to what you want?
Comment: It could be seen that way. I was more looking for help about how LEFT JOIN functions, and whether it will return the desired result, not to improve code that I know works.
Answer: The null check will only shows items with signatures. If you leave the null check out of the picture, you will get nulls for items where signature is not present.
check this
Comment: THAT's the kind of thing I was looking for. Extremely helpful, thank you.
Comment: Nice image. Where did this come from? Cite your source please. :-)


Project's running fine on iPhone 4s simulator and throws some core data errors while running on 5/5s simulator

Question: Do you guys think is the Xcode 6 beta 3 thats acting weird ?
anybody having similar issues ?
Answer: If you have changed something in the data model.you need to remove the app first from device or simulator and recompile.It has nothing to do with simulator or device.It is true that xcode 6 is not stable but this is not the cause.
Comment: tried doing that, still the same result.
To be precise, i am getting this error when running on 5/5s simulator.
"The model used to open the store is incompatible with the one used to create the store"
but runs fine on 4s simulator


Lavavel migrate not work in a LAMP AWS instance with MySQL RDS DB --> SQLSTATE[HY000] [2002] Connection timed out

Question: I have setup an EC2 aws instance with Apache, PHP 7.2, Git, Composer and a RDS MySQL 5.7 database.
I followed the AWS official tutorials and others like Deploying and Scaling a Laravel Web App on AWS — Part 1 but I can't finish the laravel project installation. Using ssh terminal connection, in time to migrate (sudo php artisan migrate), I get the response:

Illuminate\Database\QueryException  : SQLSTATE[HY000] [2002] Connection timed out (SQL: select * from information_schema.tables where table_schema = database_name and table_name = migrations)

When I try this same connection using MySQL WorkBench, I can connect, create or drop a table for example.
I think the .env file or config/database.php are properly set, but I can't explain why I get this error. Any help please? Thanks
Answer: Seeing as this is a connection issue:

Between your EC2 instance and the RDS MySQL database: you may have to add a rule to your security group allowing the standard MySQL port. If you've made changes to the Network Access Control List attached to the subnet that your EC2 instance is in, you'll also want to modify the NACL to allow inbound AND outbound traffic from the instance to the RDS database.
Between your RDS instance and Workbench: Check the security group on the Database (not the EC2 instance's security group)


Cannot share docker container data via -v

Question: Trying to play with postgres and docker:
 docker run --name pg -v /Users/xxx/docker/data:/var/lib/postgresql/data -d postgres

stops immediately. Run the image without -v the container keeps running on. If I login via /bin/sh I can see the mountpoint with the postgres default databases:
root@f9e0e92dae26:/# df -k
Filesystem     1K-blocks     Used Available Use% Mounted on
none            19049892   737424  17321744   5% /
tmpfs            1025332        0   1025332   0% /dev
shm                65536        8     65528   1% /dev/shm
none           116884912 52807056  64077856  46% /var/lib/postgres/data
/dev/sda1       19049892   737424  17321744   5% /var/lib/postgresql/data

But I cannot share them with the host in the manner of -v option says.
What's wrong here?

The log says:
    The files belonging to this database system will be owned by user "postgres".
This user must also own the server process.

The database cluster will be initialized with locale "en_US.utf8".
The default database encoding has accordingly been set to "UTF8".
The default text search configuration will be set to "english".

Data page checksums are disabled.

fixing permissions on existing directory /var/lib/postgresql/data ... ok
initdb: could not create directory "/var/lib/postgresql/data/pg_wal/archive_status": Permission denied
initdb: removing contents of data directory "/var/lib/postgresql/data"

I've tried to pass an additional shared directory to the VM, beside /Users and /, in my case /Users/xxx/docker/data, restarting the VM but that seems not to work.
Within the VM (docker-machine ssh) I can see now /data mounted. Docker machine seems to mount the last part of the full path.
Any explanation?
So with that maybe the offical postgres images could be changed (in the dockerfile?) to change the base path, examples appreciated.
Comment: You should try to debug > `docker logs pg`
Comment: "Permission denied" is pretty straightforward, no? The usual debugging steps apply (checking ownership, permissions, &c).
Comment: It's not simple as it seems. The directory at host side belongs to my own, so wrong permissions is not the real topic. I'm working with docker toolbox for Mac, it seems that's a general problem regarding the underlying VM.
See edited above.
Comment: I'm run into the same problem a few days ago, this and a reedit thread are the only things I found on the whole internet. Any updates on how to fix this?
Answer: After getting the exact same error, what worked for me was pruning the volumes. I never could figure out why there wasn't enough space in the first place.
Before you run the command below for any pruning, be sure to read the details here: https://docs.docker.com/config/pruning/#prune-everything
If you can bear to prune the volumes, this should do the trick to eliminate the OP's error:
docker volume prune

Edit:
It appears some need to prune more than the volumes. An earlier version of this of this answer accounted for that, so I'm now including it again.
To do a system prune, run:
docker system prune --volumes

Or if you really want to get rid of everything, run:
docker system prune --volumes --all

Comment: This worked for me. But I'm a bit confused. It didn't delete any volumes. But now containers are running fine
Answer: I hit the same problem with Vbox VM under Windows. I tried to use shared folders between VM and my Windows Os, which cause the problem with the permissions. I solved the problem with passing directory from /home/{username}/.. for a volume
Answer: I'm still not sure what was the actual issue. But in my case pruning the volumes did not help. I removed all the containers, images, and volumes, also restarted docker. It worked fine. Hope this helps.
Answer: Following up on Nicolas's answer,
In my case, just pruning volumes wasn't sufficient, I pruned everything (images, containers, volumes, and networks) and then it started working. Command: docker system prune --volumes
Note Make sure the deletion doesn't affect any of the other setup.


Output elements between specific element

Question: Suppose I have a table with a column which looks like:
SELECT Col1
FROM table;

Col1
A
A
B
B
C
C
D
B
E
B
F

I would like to output elements that are between "B"s, which are C, D, E
How can I do that with a query?
Comment: Short answer, you can't. If you have nothing to order by, there _is_ no "between two rows", since the order you're getting is pseudo random. If you add an ORDER BY to your query, it's doable.
Answer: declare @t table (ID INT IDENTITY(1,1),col1 VARCHAR(10))
insert into @t (col1) values ('A')
insert into @t (col1) values ('A')
insert into @t (col1) values ('B')
insert into @t (col1) values ('B')
insert into @t (col1) values ('C')
insert into @t (col1) values ('C')
insert into @t (col1) values ('B')
insert into @t (col1) values ('E')
insert into @t (col1) values ('B')
insert into @t (col1) values ('F')

select ID,col1 from @t
where ID between (select MIN(id) from @t WHERE col1 = 'B') and
(select MAX(id) from @t WHERE col1 = 'B')
and col1<>'B'


O que o computador faz com 2 valores distintos que precisam ser retornados e estão no mesmo escopo de memória?

Question: Possuo esse código com essa única função, ela realiza o produto entre 'a' e 'b' que recebe da função "main". Gostaria de saber como a função contida nesse código lida com o retorno de 2 valores para o "escopo de cima", se fizerem um teste de mesa do que ela está fazendo, vão perceber que dentro de um mesmo escopo ela tem que retornar dois valores distintos, o que ela faz com esses valores então? Soma? Pois se a resposta for soma mesmo, cheguei no resultado certo.
#include <stdio.h>

int funcao (int a, int b)
{
    if (b==0)
        return 0;

    if (b%2==0)
        return funcao(a+a, b/2);

    return funcao(a+a, b/2)+a;
}

int main ()
{
    int a, b;

    printf("Entre com 'a' e 'b' respectivamente: ");
    scanf("%d %d", &a, &b);

    printf("Resultado: %d", funcao(a,b));

    return 0;
}

Comment: *...executa os dois returns...* Não! Ao encontrar a primeira instrução `return` a execução da função é interrompida e fluxo de processamento é devolvido ao ponto onde a função foi chamada retornando o valor da expressão passado ao `return` ou `void` se não nada for passado.
Comment: Certo, então está dizendo que quando ela retorna de um escopo, ela ignora o return em que está e passa para o segundo return, que é o responsável por retornar algum valor ao escopo de cima, é isso?
Comment: Eu estou dizendo que ao encontrar exatamente o primeiro `return` a função para  e é retorna com um valor exatamente no ponto onde a função foi anteriormente chamada. Tudo o que estiver após o return é ignorado.
Comment: Entendo o que diz, você está me explicando a natureza do return como desvio de fluxo, e eu havia perguntando sobre sua atuação dentro do meu código, mesmo assim consegui entender, obrigado. Contudo, acho que não me expressei bem, vou reformular, uma função que recebe um valor x do escopo de memória anterior, e dentro de seu escopo atual gera outro valor para retornar, que é o caso da minha, o que ela faz com esses dois valores distintos, soma? Vou até editar a pergunta
Comment: Aonde no seu código estão sendo retornados dois valores? Aqui `return 0;` retorna zero, aqui `funcao(a+a, b/2);` retorna o resultado da função e aqui `return funcao(a+a, b/2)+a;` retorna o resultado da função mais `a`.
Comment: Isso é uma função recursiva, pra entender melhor, sugiro ler [aqui](/q/4282/112052), [aqui](/q/186269/112052) e [aqui](/q/46012/112052). No seu caso, em nenhum lugar a função retorna 2 valores, em todos os `return`'s, sempre é retornado apenas um. Só que em alguns casos, o valor é calculado usando o resultado de uma chamada recursiva (mas ainda é um valor só)
Comment: É mais para o lado do que o hkotsubo disse, fiz essa chamada para entenderem o que eu falo: https://ibb.co/LpTSwSh
Comment: 'F' seria a função, notem que F(16,2) por exemplo, recebe '0' do escopo anterior e gera 16 em seu escopo, F(8,4) recebe 16 do escopo anterior e gera 8 em seu escopo, até voltar ao início
Comment: O que quero saber, é se é um padrão o C somar, por exemplo, recebeu 16 do escopo anterior e gerou 8 no escopo atual, antes de retornar ao escopo de cima então ele tem que somar 8+16, certo?
Comment: Não seria isso o que está tentando fazer https://ideone.com/iTOWKU . Essa frase F(16,2) por exemplo, recebe '0' do escopo anterior não faz sentido. O que é trocado de informações entre contextos de funções são os parâmetro como entrada e valor retornado como saída.
Answer: Primeiramente, segue uma sugestão de leitura que pode ajudar no entendimento de funções de forma geral: O que acontece quando chamamos uma função?.
Dito isso, acho que primeiro podemos ver como seria se a funcao não fosse recursiva, e depois vemos como a versão recursiva não muda tanto assim. Então vamos modificar um pouco a funcao para que ela não seja mais recursiva:
int funcao(int a, int b) {
    if (b == 0)
        return 0;
    if (b % 2 == 0) // em vez de chamar "funcao", estou chamando "outra_funcao"
        return outra_funcao(a + a, b / 2);
    return outra_funcao(a + a, b / 2) + a;
}

int outra_funcao(int a, int b) {
    if (b == 0)
        return 0;
    if (b % 2 == 0)
        return outra_funcao(a + a, b / 2);
    return outra_funcao(a + a, b / 2) + a;
}

outra_funcao é praticamente igual à funcao, com a diferença que a funcao original não é mais recursiva.

O que acontece quando chamamos funcao(3, 1)?
Neste caso, a função receberá os valores 3 e 1, que correspondem aos parâmetros a e b. Ou seja, para funcao(3, 1), temos que a=3 e b=1.
Por isso o código não entra no primeiro if, já que b não é igual a zero. E como b é um número ímpar, então b % 2 é 1, por isso ele também não entra no segundo if.
Então ele cai no último return, que é:
return outra_funcao(a + a, b / 2) + a

Ou seja, a funcao está retornando apenas um valor. Esse valor é o resultado da expressão outra_funcao(a + a, b / 2) + a. E esta expressão está fazendo basicamente duas coisas:

chamando outra_funcao(a + a, b / 2)
pegando o resultado da chamada acima e somando com a

O resultado disso tudo é o valor retornado por funcao. Em nenhum momento tem 2 valores sendo retornados. Temos apenas uma chamada de função (outra_funcao), cujo resultado é somado com outro valor (no caso, a), e o resultado dessas operações vira um único valor, que é retornado pela funcao.
Bom, como chamamos funcao(3, 1), temos que a=3 e b=1, então a expressão acima acaba virando:
return outra_funcao(3 + 3, 1 / 2) + 3

Que por sua vez acaba virando:
return outra_funcao(6, 0) + 3
// como são inteiros, 1 / 2 é "arredondado" para zero

Ou seja, para saber o resultado desta expressão, precisamos saber o valor de outra_funcao(6, 0).
E quando chamamos outra_funcao(6, 0), temos a=6 e b=0 (esses a e b dentro de outra_funcao não são os mesmos a e b da funcao). Neste caso, entrará no primeiro if, e por isso ela retorna zero.
Ou seja, return outra_funcao(6, 0) + 3 é o mesmo que return 0 + 3, que é o mesmo que return 3. Concluindo, funcao(3, 1) retorna 3.

Mas repare que funcao e outra_funcao fazem basicamente a mesma coisa. Então para que ter duas funções redundantes, quando eu posso ter uma só?
int funcao(int a, int b) {
    if (b == 0)
        return 0;
    if (b % 2 == 0)
        return funcao(a + a, b / 2);
    return funcao(a + a, b / 2) + a;
}

Agora funcao é recursiva (ela é chamada dentro dela mesma). Apesar disso, seu funcionamento continua basicamente o mesmo:

chamei funcao(3, 1), ou seja, a=3 e b=1

não entra em nenhum dos if's, ou seja, cai no return funcao(a + a, b / 2) + a
que por sua vez, é o mesmo que return funcao(3 + 3, 1 / 2) + 3, que é o mesmo que return funcao(6, 0) + 3
então agora preciso calcular funcao(6, 0) - é outra chamada de função (só porque chamou a mesma funcao, não muda o fato de ser outra chamada "independente")

em funcao(6, 0), temos que a=6 e b=0 (como é outra chamada de função, esses a e b não são os mesmos da primeira chamada)
como b=0, entra no primeiro if e retorna zero

como funcao(6, 0) retornou zero, a expressão return funcao(6, 0) + 3 é o mesmo que return 0 + 3, que é o mesmo que return 3

ou seja, funcao(3, 1) retorna 3

Em nenhum momento há o "retorno de dois valores". A funcao sempre retorna apenas um valor. O que acontece é que em alguns casos o valor é obtido através de uma expressão que pode envolver outra chamada de função (e não importa se é a mesma função ou outra, a ideia é a mesma: temos que obter o valor retornado pela chamada para poder calcular o resultado final da expressão).
Não existe essa coisa de "escopo de cima", "escopo anterior", nada disso. É apenas uma função que pode chamar outra, que pode chamar outra, que pode chamar outra (sendo que essa "outra" pode ser inclusive a mesma função, com argumentos diferentes). O importante é que todas essas chamadas não fiquem se chamando eternamente, e que em algum momento elas retornem algum valor, que será usado pela chamada anterior, que será usado pela anterior a esta, e assim por diante, até chegar à primeira chamada, que retornará o resultado final.

Outro exemplo: funcao(3, 4). Temos que:

a=3 e b=4, entra no segundo if, então retorna funcao(a + a, b / 2) → funcao(6, 2)

funcao(6, 2) → a=6 e b=2, entra no segundo if, então retorna funcao(a + a, b / 2) → funcao(12, 1)

funcao(12, 1) → a=12 e b=1, não entra em nenhum if, retorna funcao(a + a, b / 2) + a → funcao(24, 0) + 12

funcao(24, 0) → a=24 e b=0, entra no primeiro if, retorna zero

funcao(12, 1) retorna funcao(24, 0) + 12 → 0 + 12 → 12

funcao(6, 12) retorna funcao(12, 1) → 12

funcao(3, 4) retorna funcao(6, 2) → 12

Ou seja, o resultado é 12.
Outra forma de visualizar:

Se a imagem acima não carregar, segue o mesmo diagrama em ASCII:
+- funcao(3, 4) --------------------------------------------+
|  a=3, b=4                                                 |
|  entra no segundo if                                      |
|  retorna funcao(6, 2)                                     |
|              ↓                                            |
|       +- funcao(6, 2) ---------------------------------+  |
|       |  a=6, b=2                                      |  |
|       |  entra no segundo if                           |  |
|       |  retorna funcao(12, 1)                         |  |
|       |              ↓                                 |  |
|       |       +- funcao(12, 1) ---------------------+  |  |
|       |       |  a=12, b=1                          |  |  |
|       |       |  não entra em nenhum if             |  |  |
|       |       |  retorna funcao(24, 0)  + 12 ----+  |  |  |
|       |       |              ↓                   |  |  |  |
|       |       |       +- funcao(24, 0) -------+  |  |  |  |
|       |       |       |  a=24, b=0            |  |  |  |  |
|       |       |       |  entra no primeiro if |  |  |  |  |
|       |       |       |  retorna zero         |  |  |  |  |
|       |       |       +---------- | ----------+  |  |  |  |
|       |       |                   ↓              |  |  |  |
|       |       |  retorna          0  +  12 ←-----+  |  |  |
|       |       |  retorna 12                         |  |  |
|       |       +---------- | ------------------------+  |  |
|       |                   |                            |  |
|       |  retorna 12 ←-----+                            |  |
|       +---------- |------------------------------------+  |
|                   |                                       |
|  retorna 12 ←-----+                                       |
+-----------------------------------------------------------+

Repetindo: não existe essa história de "escopo de cima", de baixo, anterior, etc. O que temos são chamadas de função. Quando você chama uma função, ela é executada, e só depois que ela retorna, o código que chamou a função continua de onde parou. Quando uma função chama outra (ou ela mesma), ela tem que esperar a chamada terminar, para só depois pegar o resultado retornado e poder usá-lo.
Não tem essa história de "o padrão do C é somar" (como perguntado nos comentários). Foi você que disse que deve fazer uma soma:
funcao(a + a, b / 2) + a
                     ↑
         Aqui você disse para somar

Esse código soma o resultado de funcao(a + a, b / 2) com a. Só que para fazer esta soma, ele precisa saber o resultado de funcao(a + a, b / 2) - então ela chama a função novamente para saber qual é esse resultado (só que essa chamada pode acabar fazendo outra chamada, que pode fazer outra, e outra, etc, até que em algum momento elas caem no primeiro if e começam a retornar os resultados para quem as chamou).
Se em vez dessa soma, tivesse qualquer outra operação (subtração, multiplicação, outra chamada de função, ou qualquer outra expressão válida), ela seria feita. O "padrão" não é somar, é chamar as funções, pegar os resultados e usá-los da forma que o código indica - se o código diz para somar, como é o caso, ele soma.
Enfim, é "só" isso.
Comment: Muito obrigado, finalmente tive tempo de fazer a leitura desse seu texto e entendi perfeitamente o comportamento dessa função recursiva através de seu diagrama, executei algumas vezes com valores diferentes e deu certo aqui, fico muito grato.
Answer: Não sei se entendi, mas ela não está retornando dois valores. Está retornando a soma de 'a + (chamada da propria função ( valor a,valor b))'.
Entradas e ciclos da função recursiva:
input a == 2, b == 2
recursividade:
Entra 2,2 -> Respeita o segundo if que gera os inputs -> 4,1 -> Entra no ultimo return que gera os inputs (8,0.5) somado com 4 ( (a+a,b/2) +a) nessa parte o (8,0.5) gera 0 que somados com 4  resulta em 4. Com isso respeita a entrada 2*2 = 4.
Entra 3,3 -> Entra no ultimo return que gera (6,1.5)+3 -> O (6,1.5) entra na ultima condição que gera (12,(1.5)/2)+6   - > o input (12,(1.5/2) entra na primeira condição que retorna 0, logo fica 6+3 = 9.
Não sei pra que essa mirabolância toda, mas funciona. Espero ter ajudado


AkkaHTTP: Getting content out of an HttpEntity

Question: I'm working with AkkaHTTP in Scala, trying to interact with an API, but I'm having some trouble getting data with certain API calls. Basically, I have a curl command which works in my terminal for any valid API call to this certain API, but in my current code I only get the actual data for calls whose responses are small enough.
My first attempt was using sys.process._ and the !! method on a string with "curl (url) -X GET -H \"Authorization: Bearer (auth token)\" (which is the command that works in my terminal), but that failed with an error in scala due to issues parsing the header; so after making no headway on that and realizing I wanted to use AkkaHTTP anyway, I abandoned that approach and came to the code below, whose format I borrowed from another stackoverflow post.
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
implicit val executionContext = system.dispatcher

val responseFuture: Future[HttpResponse] = Http().singleRequest(HttpRequest(
  uri = "(url)").withHeaders(
  RawHeader("Authorization", "Bearer (auth token)")
))

responseFuture
  .onComplete {
    case Success(res) => println(res)
    case Failure(_)   => "failure"
  }

Now, I've tried this on two different API calls; the first, which in my terminal returns a JSON string with 327 characters, returns a blob, where res.entity is HttpEntity.Strict(application/json,(the same JSON blob as in the terminal)). However, while the second call returns in my terminal a JSON blob with 203,413 characters (much bigger than the first one), sending that request in scala returns a blob where res.entity is just HttpEntity.Chunked(application/json). I would presume the payload is split into multiple packets ("Chunked" being a fairly applicable name for that scenario), but I can't seem to figure out how to get the payload information from here, and I'd appreciate some help.
Answer: If it's acceptable to load the entire entity into memory, you can call toStrict on the ResponseEntity:
import scala.concurrent.Future
import scala.concurrent.duration._

val entityFut: Future[String] =
  responseFuture.flatMap(_.entity.toStrict(5 seconds).map(_.data.utf8String))

entityFut.onComplete {
  case Success(body) =>
    println(body)
  case Failure(_) =>
    println("failure")
}

You could also use a built-in unmarshaller:
import akka.http.scaladsl.unmarshalling.Unmarshal

val entityFut: Future[String] =
  responseFuture.flatMap(resp => Unmarshal(resp.entity).to[String])


What do these prior distributions mean?

Question: Suppose we have a prior distribution of $$\pi_1(\theta)=k\theta^{k-1},$$ and we have another of $$\pi_2(\theta)=k(1-\theta)^{k-1}.$$ Intuitively, what do the two different distributions mean / represent?
I understand that the summarise the beliefs of the tester before and after the test, but I don't understand specifically what these ones mean. Are they not both very much the same, since if $\theta\in(0,1)$, then so is $(1-\theta)$, and the only "difference" is that one is analogous to probability of throwing heads, while the other is analogous to throwing tails - by symmetry aren't both these prior distributions "the same"?
I'd like to understand what $k$ and $\theta$ represent, and also what is significant about the power of $k-1$ - what makes this different to, say, an exponential function?

Note: both have $\theta\in(0,1)$, $k>1$ is a constant, and is discrete (an integer).
The likelihood is a binomial - $f(x|\theta)={k\choose x} \theta^x (1-\theta)^{k-x}$ - and is applied to $n$ i.i.d. random variables, so the overall likelihood is $$f(\vec x|\theta)=\left(\prod_{i=1}^n {{k}\choose x_i}\right)\theta^{\sum x_i}(1-\theta)^{nk-\sum x_i}$$
Comment: @Bey What are complementary priors? I haven't heard of these before. What do they mean about the different initial beliefs of the testers? Or are the two beliefs not different?
Comment: I agree with you. They are complementary priors.
Comment: It's not a technical term, they are expressing the same idea different ways.
Comment: Is $k$ continuous or does it take discrete values like - 2, 3, 4, etc? Also could you be more elaborate on what $\pi_1$ and $\pi_2$ represent. Posterior = prior $\times$ likelihood, so you also have to tell what is the likelihood function, you haven't mentioned that here.
Comment: @ShishirPandey I have edited to include this
Comment: @Xi'an I just meant that I understand that about priors and posteriors in general - that they represent beliefs before and after a test.
Answer: The priors are beta distributions:
$$\begin{align} \operatorname{beta}(\theta\mid k,1) &= \theta^{k-1} (1-\theta)^{1-1} / B(k,1) \\ &= \theta^{k-1} / (1/k) \\ &= k \theta^{k-1} \end{align}$$
Typically that's interpreted as having previously observed $k$ successes and $1$ failure. The other prior is just $\operatorname{beta}(\theta\mid 1,k)$.

What do these prior distributions mean?


Connection between covariant and contravariant components o tensor

Question: What is the general proof of the relation between covariant and contravariant components of a tensor using the metric tensor?
$${g^{mr}g_{rn}=\delta^{m}_{n}}$$
Comment: What relation are you referring to exactly?
Comment: I added the expression.
Answer: I guess you are interested in the connection between covariant and covariant tensors on a Riemannian manifold. Let $(M,g)$ be a Riemannian manifold and let $\alpha$ be a $(0,1)$- covariant tensor (a section of $T^*M$). Then there exists a unique $(1,0)$-contravariant tensor $v$  (a section of $TM$) such that $\alpha=g(v,\cdot)$.
Example: $g(grad\, f,\cdot)=df$
So  for any (r,s)- tensore $T$ (a section of $\otimes^rT^M{\otimes^s}T^*M$) you can find a unique (s,r)-tensor $T^*$ associated with $T$ via the metric $g$.


Using DiskLruCache in android 4.0 does not provide for openCache method

Question: Have anyone worked on DiskLruCache?
http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html
provides an example of using this caching method. But i observe the implementation for DiskLruCache in 4.0 source code does not have defined methods. Any idea how to use this?
Comment: Finally did it http://stackoverflow.com/a/32516598/1939564
Answer: You can use Picasso as image loader.
Or
This is what I did:
I created a class named DiskLruImageCache with a DiskLruCache (the one from Jake Wharton) object and the same methods in the simple implementation on the dev guide (displaying bitmaps efficiently):
public class DiskLruImageCache {

    private DiskLruCache mDiskCache;
    private CompressFormat mCompressFormat = CompressFormat.JPEG;
    private int mCompressQuality = 70;
    private static final int APP_VERSION = 1;
    private static final int VALUE_COUNT = 1;
    private static final String TAG = "DiskLruImageCache";

    public DiskLruImageCache( Context context,String uniqueName, int diskCacheSize,
        CompressFormat compressFormat, int quality ) {
        try {
                final File diskCacheDir = getDiskCacheDir(context, uniqueName );
                mDiskCache = DiskLruCache.open( diskCacheDir, APP_VERSION, VALUE_COUNT, diskCacheSize );
                mCompressFormat = compressFormat;
                mCompressQuality = quality;
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    private boolean writeBitmapToFile( Bitmap bitmap, DiskLruCache.Editor editor )
        throws IOException, FileNotFoundException {
        OutputStream out = null;
        try {
            out = new BufferedOutputStream( editor.newOutputStream( 0 ), Utils.IO_BUFFER_SIZE );
            return bitmap.compress( mCompressFormat, mCompressQuality, out );
        } finally {
            if ( out != null ) {
                out.close();
            }
        }
    }

    private File getDiskCacheDir(Context context, String uniqueName) {

    // Check if media is mounted or storage is built-in, if so, try and use external cache dir
    // otherwise use internal cache dir
        final String cachePath =
            Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
                    !Utils.isExternalStorageRemovable() ?
                    Utils.getExternalCacheDir(context).getPath() :
                    context.getCacheDir().getPath();

        return new File(cachePath + File.separator + uniqueName);
    }

    public void put( String key, Bitmap data ) {

        DiskLruCache.Editor editor = null;
        try {
            editor = mDiskCache.edit( key );
            if ( editor == null ) {
                return;
            }

            if( writeBitmapToFile( data, editor ) ) {
                mDiskCache.flush();
                editor.commit();
                if ( BuildConfig.DEBUG ) {
                   Log.d( "cache_test_DISK_", "image put on disk cache " + key );
                }
            } else {
                editor.abort();
                if ( BuildConfig.DEBUG ) {
                    Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + key );
                }
            }
        } catch (IOException e) {
            if ( BuildConfig.DEBUG ) {
                Log.d( "cache_test_DISK_", "ERROR on: image put on disk cache " + key );
            }
            try {
                if ( editor != null ) {
                    editor.abort();
                }
            } catch (IOException ignored) {
            }
        }

    }

    public Bitmap getBitmap( String key ) {

        Bitmap bitmap = null;
        DiskLruCache.Snapshot snapshot = null;
        try {

            snapshot = mDiskCache.get( key );
            if ( snapshot == null ) {
                return null;
            }
            final InputStream in = snapshot.getInputStream( 0 );
            if ( in != null ) {
                final BufferedInputStream buffIn =
                new BufferedInputStream( in, Utils.IO_BUFFER_SIZE );
                bitmap = BitmapFactory.decodeStream( buffIn );
            }
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
            if ( snapshot != null ) {
                snapshot.close();
            }
        }

        if ( BuildConfig.DEBUG ) {
            Log.d( "cache_test_DISK_", bitmap == null ? "" : "image read from disk " + key);
        }

        return bitmap;

    }

    public boolean containsKey( String key ) {

        boolean contained = false;
        DiskLruCache.Snapshot snapshot = null;
        try {
            snapshot = mDiskCache.get( key );
            contained = snapshot != null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if ( snapshot != null ) {
                snapshot.close();
            }
        }

        return contained;

    }

    public void clearCache() {
        if ( BuildConfig.DEBUG ) {
            Log.d( "cache_test_DISK_", "disk cache CLEARED");
        }
        try {
            mDiskCache.delete();
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }

    public File getCacheFolder() {
        return mDiskCache.getDirectory();
    }

}

Utils source code is:
public class Utils {
    public static final int IO_BUFFER_SIZE = 8 * 1024;

    private Utils() {};

    public static boolean isExternalStorageRemovable() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            return Environment.isExternalStorageRemovable();
        }
        return true;
    }

    public static File getExternalCacheDir(Context context) {
        if (hasExternalCacheDir()) {
            return context.getExternalCacheDir();
        }

        // Before Froyo we need to construct the external cache dir ourselves
        final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
        return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
    }

    public static boolean hasExternalCacheDir() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
    }

}

Remember to put
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

on your AndroidManifest.xml
I figured out this way by reading this code and the javadoc from Jake Wharton's DiskLruCache
Comment: Figured it out. I need to call close() on the DiskLruCache when my activity finishes. Works fine now.
Comment: Sorry, I forgot I used my own Utils class. I'll update the answer with the proper source code.
Comment: I am getting a java.lang.IllegalStateException: edit didn't create file 1.
Any idea why?
Comment: @Platonius Thanks. This has been very helpful. In `put()` you have `mDiskCache.flush()` before `editor.commit()` . Shouldn't it be the other way round? Using your code as it is, leaves the last entry as dirty, and if the app restarts, that cache entry is no longer available.
Comment: In your `DiskLruImageCache.getDiskCacheDir()`, would `Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED` be better replaced by `Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())`? This is based on http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html#disk-cache
Comment: Hi, I'm using your class to cache Bitmaps, but for some reason all are deleted when you close the app. When it goes throught onPause works great. It deletes everything when It close. How can I avoid that?
Comment: Hi platonius, Thanks for your time and effort. So i can use this for my grid view implementation for diplaying the images in the sdcard and make it work as efficiently as default gallery. Meanwhile have you tried this above piece of implementation anywhere?
Comment: Awesome, So the scroll will be fast enough as well as the memory usage is also taken care right?
Comment: Yes, you can use this with a grid view. I'm using it for my current project following a similar code  as the one you can find on the [dev guide](http://developer.android.com/training/displaying-bitmaps/index.html) and the sample code for that lesson. It has been working pretty well. Remember to put READ_EXTERNAL_STORAGE and WRITE_EXTERNAL_STORAGE on the Android manifest.
Comment: I think so. I have run some simple tests on it and it works fast enough.
Comment: For some reason, it caches all my images but the last added one. I have went through the code and everything runs correctly, the logger says "image put on disk cache", but as soon as its needed next time, it will not be found. Anybody else faced this problem?
Comment: @RameezHussain It's on the source code for "bitmap fun" on the dev guide: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
Comment: Hi. I don't get where to find the Utils class... can you give more info?
Comment: @sajal I think I misunderstood how a lru cache works. I thought it was normal to always lose the last entry since it is the least-recently used by the time the app restarts. UPDATE: I've done some tests and changing the order of flush and commit doesn't seem to change journal's content. Although, if flush means "write whatever we've done with disk cache to journal" then I'm ok with putting commit first and then flush.
Comment: flush() will write on your disk (external storage). Therefore calling flush() everytime you put somthing into this cache could leed to performance issues. Normally its enough to call close(), which will call flush(), when you are done (example activity gets destroyed) and then all commited changes will be written to the disk. But what I dont understand is, why a snapshot has an array of InputStreams to read from and not exactly one. The demo code above uses only the first one to read ( snapshot.getInputStream(0); ) and write (editor.newOutputStream(0); ). Does anybody know why?
Comment: @Pang I think you're right. Environment.MEDIA_MOUNTED is a String, so it should be compared with     equals. Thanks, I'll change the code.
Comment: I was constantly getting IOException on the mDiskCache.flush(); That call is incorrect since you cannot flush it before commiting the edit.  DiskLruCache was failing with "Failed to delete" error. Removing that line fixed the problem.
Comment: That's weird. I never have that problem. Have you tried putting `flush()` after `commit()`, as @sajal suggest?
Comment: I am trying to implement the above code with Volley. How do I use this class? Can someone help me out?
Comment: Please post sample code how to use DiskLruImageCache class in Adapter. Many thank.
Comment: @Platonius `out = new BufferedOutputStream(editor.newOutputStream(0), Utils.IO_BUFFER_SIZE);` in **writeBitmapToFile** is always null?
Comment: Can you please help @Platonius
Comment: Because I thought about implementing something myself: Picasso is just GREAT! Pretty straight forward with quite much functionality.
Comment: What about synchronization when writing item to cache?
Answer: You can also use the SimpleDiskCache, which wraps the DiskLruCache with more developer friendly interface.
Comment: @Malachiasz if it was true (it's not), SimpleDiskCache would indeed be useless.
Answer: I wrote a library based on this nice piece of code posted by @Platonius. It includes some bug fixes, for example frequent IOExceptions in the put() method with "failed to delete file". It uses both LRU and disk cache: https://github.com/felipecsl/Android-ImageManager


Jacobian and chain rule

Question: I am trying to work out the derivative of a scaler ($J$) with respect to a vector ($x$) via chain rule. Below I laid out the steps in between, I find the matrix shape only checks out when I consider $x$ is a row vector. I labeled the details as below.
Red is the shape of a vector, and blue is the shape of the derivative matrix.

I think I still don't understand Jacobian, or derivative of a vector w.s.t. a vector well enough, please correct me.
Answer: the RHS of the second equation should be transposed since the left hand has been.
Answer: If you compare the RHS of your expressions they are identical, however, the LHS you have affected by transposition. When you transpose a vector
$$
z=Ax
$$
then the transpose is
$$
z^T=(Ax)^T=x^TA^T.
$$
Correspondingly, the RHS must change.
P.S. The first line is better for understanding and more natural, the second line is a burden from the vector analysis to have the gradient to be a vector instead of a row.
Comment: I thought normal people prefer column vectors (influenced by [Gilbert Strang's MIT linear algebra](https://ocw.mit.edu/courses/mathematics/18-06-linear-algebra-spring-2010/) course and my own reading in general, but when it comes to Jacobian, it's actually row vectors are prefered, which is why Jacobian equation on [wiki](https://en.wikipedia.org/wiki/Jacobian_matrix_and_determinant) used row vector, is that correct?
Comment: Linear algebra calculations prefer column vectors, that's why gradients tend to be a column. However, the gradient/Jacobian are [covariant transformations](https://en.wikipedia.org/wiki/Covariance_and_contravariance_of_vectors). It is a conflict that is hard to resolve.
Answer: Just uploaded a version that illustrate the right way to look at the chain rule with proper transpose operations. Convention: $x$ is a column-vector, $x^T$ is its corresponding row vector.

Jacobian and chain rule


Android; define theme for specific View subclass within Activity

Question: is there a way to define a style that affects all Views in an Activity of a given type, without editing all of the xml View tags to define the style.  is there a way to define something like "all TextViews in this Activity have a minHeight of 70sp"?
Comment: Something  like a custom theme(only for that particular activity) for which you set the desired views attributes?
Comment: well, yes, i think.  but i want to style/theme only Views of a specific type.  i'm trying to avoid explicitly defining the style for each TextView instance, as it just seems like there ought to be a way to do this.  and if there isn't, there should be.
Comment: See http://stackoverflow.com/questions/10903647/set-a-consistent-style-to-all-edittext-for-e-g. Worked for me.
Answer: A theme is what you want. Each android widget has a default style that you could override to make it as you want. For example:
<resources xmlns:android="http://schemas.android.com/apk/res/android">

</resources>

a theme that overrides the style for a TextView. SpecialTextView is a style like this:

Then simply set the TextViewSpecial theme in the manifest to the desired activity. You can use this method to ovreride the style of what widget you want.
Answer: Just define a theme for the layout.


Sobrepor duas imagens com :hover

Question: O meu objetivo seria que uma imagem em .png ficasse por cima de uma imagem .jpg ao passar o cursor por cima. Tentei com o seguinte código:
 .image{
 width: 320px;
 height: 180px;
}

.image:hover{
content: url('playplay.png');
}

Mas fica com este aspeto

Ao passar o cursor a imagem jpg desaparece sendo substituida pela png, mas o meu objetivo era que o botão do play ficasse sobre a imagem. As imagens têm exatamente o mesmo tamanho e ficarão nessa disposição (4 alinhadas horizontalmente)
Comment: Adicione o seu html à pergunta.
Answer: Acontece que da forma como está fazendo, no hover, você substitui a imagem ao invés de exibir a outra sobreposta. Vai precisar mudar um pouco a estrutura do seu html e adicionar um tratamento no css.
Exemplo

.thumbnail {
    position: relative;
    float:left;
    width: 50%;
}

.image {
  opacity: 1;
  display: block;
  width: 320px;
  height: 180px;
  height: auto;
  transition: .5s ease;
  backface-visibility: hidden;
}

.overlay {
  width: 100px;
  height: 100px;
  transition: .5s ease;
  opacity: 0;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-image: url('//d30y9cdsu7xlg0.cloudfront.net/png/66410-200.png');
  background-repeat: no-repeat;
  background-size: 100px 100px;

}

.thumbnail:hover .image {
  opacity: .8;
}

.thumbnail:hover .overlay {
  opacity: 1;
}

.text {
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  padding: 16px 32px;
}

Obs.: As firulas de animação já estavam no meu css, se for necessário posso limpar os efeitos se ficou difícil de entender.
Answer: Fiz três opções para você. Com Pseudo Element ::after, com Dois Backgrounds (nessa opção o CSS pode ficar mais extenso, mas vale de referência). E fiz um modelo com Position e alternando o z-index no :hover
Execute o Snippet para ver as opções.

/* com pseudo elemente ::after */
.imgafter {
    float: left;
    width: 200px;
    height: 100px;
    margin: .5rem;
    cursor: pointer;
    position: relative;
}
.imgafter:hover::after {
    content: "\25B6";
    color: limegreen;
    font-size: 5rem;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
.img1 {
    background: url(http://fillmurray.com/200/100) no-repeat center;
    background-size: cover;
}
.img2 {
    background: url(http://fillmurray.com/300/100) no-repeat center;
    background-size: cover;
}
.img3 {
    background: url(http://fillmurray.com/300/200) no-repeat center;
    background-size: cover;
}
.img4 {
    background: url(http://fillmurray.com/200/200) no-repeat center;
    background-size: cover;
}
/* com dois backgrounds */
.imagem {
    float: left;
    width: 200px;
    height: 100px;
    background-image: url(http://placecage.com/200/100);
    margin: .5rem;
}
.imagem:hover {
    float: left;
    width: 200px;
    height: 100px;
    background-image: url(https://cdn3.iconfinder.com/data/icons/developerkit/png/Play.png), url(http://placecage.com/200/100);
    background-repeat: no-repeat;
    background-position: center;
    background-size: 50%, 100%;
    cursor: pointer;
}
/* Com Position */
.base {
    width: 200px;
    height: 100px;
    cursor: pointer;
    margin: .5rem;
    float: left;
    position: relative;
    z-index: 1;
}
.base:hover .play {
    width: 50px;
    height: 50px;
    -webkit-clip-path: polygon(100% 50%, 0 0, 0 100%);
    clip-path: polygon(100% 50%, 0 0, 0 100%);
    background-color: #0f0;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    z-index: 2;
}

Com ::After

Com Duble Background

Com Position

Comment: com dois backgrounds foi o que funcionou melhor para mim, tive só que fazer alguns pequenos ajustes porque causa do tamanho das imagens, mas no final ficou perfeito. muito obrigada!
Comment: @DianaTaveira Se você optou pela resposta do `hugocsl`, deve marcá-la como a resposta, não a minha :)
Comment: @LeandroAngelo não se preocupe, obrigado pela gentileza ;) tmj

Sobrepor duas imagens com :hover


`rbind` dataset by sequence in a directory

Question: I have a data set with identical row and row numbers. I want to rbind those data in a sequence of two.
For example for data 5LSTT-test12_1.avgm and 5LSTT-test12_1_sum.avgm
first I want to merge them by using rbind and save them with the new name let's say test12.avgm. This process should be done for each two file inside the same directory.
I have checked over the net but most of the solutions for merging the data into a single file. I don't know how to merge two data and save them as single data and do this process all the files in the path.
The data set goes like this
5LSTT-test12_1.avgm
5LSTT-test12_1_sum.avgm
5LSTT-test13_1.avgm
5LSTT-test13_1_sum.avgm
.
.
.
.
5LSTT-test30_1.avgm
5LSTT-test30_1_sum.avgm

Answer: Assuming that the vector of object names ('v1') are ordered, we can split it to 2 element each list element using gl.  I am not sure if these objects are already in the global environment.  In that case, we can use mget and replace the do.call(rbind, lapply(x, read.table) with do.call(rbind, mget(x))
lst <- lapply(split(v1,as.numeric(gl(length(v1), 2, length(v1)))),
               function(x) do.call(rbind,lapply(x, read.table)))

Change the names of the 'lst' with 'nm1'
nm1 <- sprintf('test%d.avgm', 12:30)
names(lst) <- nm1

If we need to create new files, we can do:
lapply(seq_along(lst), function(i) write.table(lst[[i]],
                     paste0(nm1[i],'.txt'), quote=FALSE))

data
v1 <- sort(sprintf('5LSTT-test%d_1.%s', 12:30,
               rep(c('avgm', 'sum.avgm'),each=19)))

Comment: works perfect I got the output. Really really appreciate your help. Thanks!
Comment: Dear @akrun only one small thing the program gave an error when try to open open file '5LSTT-test10_1.-sum.avgm': No such file or directory. How can change the 'sum.avgm' because it tries to read .sum.avgm files but in real the file format is
"5LSTT-test13_1-sum.avgm"
Comment: @Thabescity  The `nm1` created was of the format `"test12.avgm"`.  Are you saying the files are not in the format `"5LSTT-test12_1.avgm"`.  I may have missed the point.
Comment: @Thabescity  `sprintf('5LSTT-test%d_1-sum.avgm', 12:30)` gives the file names in the format you specified.  Still I didn't quite understand the problem.
Comment: Dear @akrun sorry for delay. yes that part is ok. But when we you used rep(c('avgm', 'sum.avgm') it reads .sum.avgm files. My files in the directory has the format like this 5LSTT-test12_1-sum.avgm
Comment: I think you need to replace `.` with `-`. i.e.  `sort(sprintf('5LSTT-test%d_1-%s', 12:30,rep(c('avgm', 'sum.avgm'),each=19)))`


Toggle event capturing in jQuery or Javascript?

Question: I have elements on my page (id=itemid) that when hovered over cause another element (id=panel) to become visible (via fadeIn). Basically a hover event on itemid causes panel to fadeIn and mouseOut leads to fadeOut.
I want to make a button so that when clicked the panel element does not fadeIn or out but stays visible. When that button is clicked, the mouseIn and mouseOut events should work again.
Any ideas?
Thank you!
$(document).ready(function(){
    $('.itemid').hover(
        function () {
            $('.panel').fadeIn(300);
        },
        function () {
            $('.panel').fadeOut(200);
        }
    );
});

Comment: Do the fade in/out on hover with a class, then simply add/remove said class on click.
Answer: Set a flag for whether to do the fading or not:
$(document).ready(function(){
var fadeEnabled = true;
$('.itemid').hover(
    function () {
        if (fadeEnabled) {
            $('.panel').fadeIn(300);
        }
    },
    function () {
        if (fadeEnabled) {
            $('.panel').fadeOut(200);
        }
    }
);

$("#myButton").click(function() {
     fadeEnabled = !fadeEnabled;
});

});

Then, just toggle that flag with your button and it will enable or disable the fade behavior.
Answer: On click of the button, use $(selector).unbind('mousein') on your object/item to deregister the events., and the reregister on another click of the button. Keep toggling on each click of the button.


How to call an action inside another action in Yii?

Question: I've a situation where i get some information from database and based on the data , i want to do/forward to some other controller & action.
How can i do this using Yii? Its like an ajax request..
If i can use the CController->forward() , then how can use the post values for actions?
Answer: I shall assume that the reason why redirect() didn't work for you was because you can't sent post variables with it. If that's the case, then let me show you how to overcome the lack of POST support in redirect(). You can use setState(). It creates variables that simulate POST variables. This is the code to store or set a variable:
Yii::app()->user->setState('var', 'value');

And, in order to trace the value you just code as follows:
Yii::app()->user->getState('param1');

It would equally work with forward, but I'm not sure why you want to use it instead of redirect().
Comment: maybe because redirect() changes the url, and forward() doesn't, @Vijay wants an ajax kind of request. user state is a good idea though to pass parameters, +1.


Establish a unique server-client connection with SignalR in asp.net

Question: I use SignalR to print a document from a web site through a printer connected to the network. When I test it on a pc, it works fine. The problem is when there is more than one pc connected, since it prints as many copies as the number of computers connected using SignalR.
This is the html code:
$(document).ready(function () {
var myHub = $.connection.myHub;
        var direccionWeb = $("#direccionWeb").val().toString();
        $.connection.hub.url = direccionWeb + "/signalr";
        $.connection.hub.start().done(function () {
            myHub.server.broadcastMessageToPrinterReportTicket(global_venta, global_mesa, nombregarzon, idgrupo, grupo);

        }).fail(function (error) {
            console.error(error);
        });
 });

This is the HUB file:
public void BroadcastMessageToPrinterReportTicket(String global_venta, String global_mesa, String nombregarzon, String idgrupo, String grupo)
    {
        string nombreImpresora = grupo;
        //resto de código para obtener datos.......

        String nombreRDLC = "report_ticket.rdlc";
        String nombreDataSet = "DataSet_ticket";

        Clients.All.imprimeReport(nombreImpresora, parametros, dt, nombreRDLC, nombreDataSet);

    }

This is the windows form:
public partial class Form1 : Form
{
    HubConnection hubConnection;
    IHubProxy hubProxy;
    //Install-Package HtmlRenderer.PdfSharp -Version 220.127.116.11
    public Form1()
    {
            InitializeComponent();
            IncializaSignalR();
            hubConnection.Closed += IncializaSignalR;
            hubConnection.Start().Wait();
        }

     private void IncializaSignalR()
    {

        String direccionServer = "https://mipaginaweb.cl";

        hubConnection = new HubConnection(direccionServer + "/signalr/hubs");
        hubProxy = hubConnection.CreateHubProxy("MyHub");
        CheckForIllegalCrossThreadCalls = false;

        hubProxy.On<String, ReportParameter[], DataTable, String, String>("imprimeReport", (nombreImpresora, parametros, dt, nombreRDLC, nombreDataSet) =>
        {
            //Instrucción de código para imprimir con reportviewer
          }
        });
   }

When checking the code, I suspect that the cause of the problem could be the "All" statement:
  Clients.All.imprimeReport(.......

Because apparently, it sends the request to all connected users. However, the instruction should go only from the client's PC who made the request to print, as intended.
Comment: Did you try Clients.Caller.imprimeReport ?
Comment: Yes, but it cannot communicate
Answer: When a client connects, they are given a unique "Connection ID" that is stored on the Context object (accessible in the Hub class's method that is handling the call).
You can then use this ID to send them messages, ie:
Clients(Context.ConnectionId).SomeClientMethod();

Sounds like that's what you need to do. Note that because the connection ID is part of a request, if you need it later you will need to store it off in memory somewhere along with a key for the device or generated action so you can fetch it appropriately.
Comment: Do you have an example? I tried this: `Clients.User(Context.ConnectionId).imprimeReport(nombreImpresora, parametros, dt, nombreRDLC, nombreDataSet);` but it doesn't call the print function
Comment: @DavidM Its not Clients.User, just Clients. Based on your comment in the actual question; it sounds like the client may not be maintaining the connection?
Comment: @BradleyDotNET,  Should we change the  hubProxy.On("imprimeReport", (nombreImpresora, parametros, dt, nombreRDLC, nombreDataSet) =>
        {
            //
          }
For another instruction?
Comment: @Danilo That looks right to me. Is that object being disposed somewhere? Obviously it worked at some point because your Clients.All worked
Comment: I found this solution: (https://stackoverflow.com/questions/19522103/signalr-sending-a-message-to-a-specific-user-using-iuseridprovider-new-2-0) but I want to know how to get the user ID and send it to the client
Comment: I see that when using Clients.All.imprimeReport (....) it works fine, but when it changes to another method, on the client side it does not pass the function's breakpoint.imprimeReport (So they tell me)
Comment: @DavidM I haven't done ASP.NET authentication; so I can't help you there. Going direct with Caller (assuming you never left the request of course) or the connection ID never fails for me. The primary issue is if you try to use one of those outside an actual request context (which is quite common) which is why I mention you may need to store it off


android equivalent for setInterval of javascript for class

Question: i want to know what is the android equivalent for setInterval of javascript for class i am trying to http post data to server at a regular intervals for example 10 seconds below is the code.
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    tv=(TextView)findViewById(R.id.textview);
    text    = "";

    try {
        postData(); // display the data

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

   public void postData() throws JSONException{
        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        final Random myRandom = new Random();
        HttpPost httppost = new HttpPost("http://mywebpage.com/index.php?id="+myRandom.nextInt(100000));
        JSONObject json = new JSONObject();

        try {

            JSONArray postjson=new JSONArray();
            postjson.put(json);

            // Post the data:
            StringEntity se = new StringEntity( "JSON: " + json.toString());
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httppost.setEntity(se);

            // Execute HTTP Post Request
            System.out.print(json);
            HttpResponse response = httpclient.execute(httppost);

            // for JSON:
            if(response != null)
            {
                InputStream is = response.getEntity().getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();

                String line = null;
                try {
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                text = sb.toString();
            }

            tv.setText(text);

        }catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
        } catch (IOException e) {
            // TODO Auto-generated catch block
        }

    int initialDelay = 1000;
    int period = 5000;
    Timer timer = new Timer();
    TimerTask task = new TimerTask() {
   public void run() {
    Looper.prepare();
    try {
   postData();
   }
   catch (JSONException e) {
   // TODO Auto-generated catch block
    e.printStackTrace();
   }
   Looper.loop();
   Looper.myLooper().quit();
    }
   };
    timer.scheduleAtFixedRate(task, initialDelay, period);

    }

all replies are welcomed :)
LOG FILE:
01-21 02:07:30.441: W/dalvikvm(575): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
01-21 02:07:30.451: E/AndroidRuntime(575): FATAL EXCEPTION: Timer-0
01-21 02:07:30.451: E/AndroidRuntime(575): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.view.ViewRoot.checkThread(ViewRoot.java:2802)
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.view.ViewRoot.invalidateChild(ViewRoot.java:607)
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.view.ViewRoot.invalidateChildInParent(ViewRoot.java:633)
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.view.ViewGroup.invalidateChild(ViewGroup.java:2505)
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.view.View.invalidate(View.java:5139)
01-21 02:07:30.451: E/AndroidRuntime(575):  at android.widget.TextView.checkForRelayout(TextView.java:5364)

Comment: Read first ... write code later ... i mean read whole dev guide from developer.android.com website .. Then you should knwon that you should not do internet operation on ui thread and how to avoid it asynctask/intentservice
Answer: I think this is what you're looking for: Android scheduleAtFixedRate
Comment: int initialDelay = 1000;
        int period = 5000;
        Timer timer = new Timer();
        TimerTask task = new TimerTask()
        {
            public void run()
            {
                Looper.prepare();
                try {
     postData();
    } catch (JSONException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
                Looper.loop();
                Looper.myLooper().quit();
            }
        };
        timer.scheduleAtFixedRate(task, initialDelay, period);         the app. is crashing ?
Comment: What is the output you get from LogCat when the app crashes?
Comment: i have added the log in the post, pls check.
Comment: 01-21 02:07:30.441: W/dalvikvm(575): threadid=7: thread exiting with uncaught exception (group=0x4001d800)
Comment: Set a break point in postData(). It should throw an exception at tv.setText(text). You can't edit any UI objects while not on the UI thread.
Answer: I think, you could use my Clock class.
It starts/ stops the timing and shows the time and/or date in the registered TextView fields.
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import android.os.Handler;
import android.widget.TextView;
/**
 * The class for creating and refreshing many different fields on different layouts,
 * that can hold actual time and/or date in different formats
 * The formats should be as in http://developer.android.com/reference/java/text/SimpleDateFormat.html.
 * Only present and visible fields are being actualized, so there is no need to clean the clock list after closing an activity
 *
 * Examples of use:
 *
 *      Clock.registerClock((TextView) findViewById(R.id.TimeField), "HH:mm");
 *      Clock.registerClock((TextView) findViewById(R.id.DateField), "d.M.yyyy EEE");
 *      Clock.start(10000L);
 *
 * @author Petr Gangnus
 */
public final class Clock {
    /**
     * the handler that works instead of timer and supports UI
     */
    static private Handler handler = new Handler();
    /**
     * the interval of the time refreshing
     */
    static private long refreshStep;

    /**
     * pairs TextView timer+time/date format
     */
    private TextView clockFace;
    private String format;
    private Clock(TextView clockFace, String format){
        this.clockFace=clockFace;
        this.format=format;
    }
    // here is the list of views containing the visual timers that should be held actual
    static private ArrayList<Clock> clocks=new ArrayList<Clock>();
    /**
     * fills all timer fields by actual time value, according to their formats.
     */
    static private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           for(Clock clock:clocks){
               showActualTimeDate(clock);
           }
           handler.postDelayed(this,refreshStep);
       }
    };

    //============================================ public members ====================================================================
    /**
     * add a clock to the list of updating clocks
     * @param clockFace - the place where the time or date will be shown
     * @param format - the format of the time/date
     * @return
     */
    public static boolean registerClock(TextView clockFace, String format){
        if (clockFace==null) return false;
        if(clocks.contains(clockFace)){
            // old clockFace
            clocks.get(clocks.indexOf(clockFace)).format=format;
        } else {
            // new clockFace
            clocks.add(new Clock(clockFace, format));
        }
        return true;
    }
    /**
     * remove a clock from the updating list
     * @param clockFace
     * @return
     */
    public static boolean unRegisterClock(TextView clockFace){
        if (clockFace==null) return false;
        if(clocks.contains(clockFace)){
            // found clockFace
            clocks.remove(clocks.indexOf(clockFace));
        } else {
            // not found clockFace
            return false;
        }
        return true;
    }
    /**
     * put in the "place" the actual date/time in the appropriate "format"
     * @param place
     * @param format
     */
    public static void showActualTimeDate(Clock clock){
        if (clock.clockFace==null) return;
        if (clock.clockFace.getVisibility()!=TextView.VISIBLE) return;
        Date thisDate=new Date();
        SimpleDateFormat df=new SimpleDateFormat(clock.format);
        clock.clockFace.setText(df.format(thisDate));
    }
    /**
     * start the ticking for all clocks
     * @param step the tick interval
     */
    public static void start(long step) {
        refreshStep=step;
        handler.removeCallbacks(mUpdateTimeTask);
        handler.postDelayed(mUpdateTimeTask, 0);
    }
    /**
     * Stopping ticking all clocks (not removing them)
     * the calling could be put somewhere in onStop
     */
    public static void stop() {
        handler.removeCallbacks(mUpdateTimeTask);
    }
}