Tips for learning and memorizing passages consisting of groups of only slightly different notes?

Question: Not sure how to word it better. I give two examples below. On the right hand (treble clef), the small groups of notes have similar patterns but vary slightly, sometimes just an accidental's difference. When first learning the Clementi Sonatina No. 4, this part was confusing to me and took me a while to get it right and memorize it.
Any tips on learning this type of passages? How would I know or remember it's a certain note with or without sharp, double sharp, or flat? I suppose it can be helped by learning music theory, and understanding why the composer wrote so?
Comment: Learning and memorization are related but quite different aspects, not always related to performance. For instance, some won't actually think whether a note is sharp or not, but how they'd eventually "move" fingers based on physical concepts (touch sensitivity, body awareness). Many use a "compound" approach, decided depending on the context (eg. "what has changed"). Some may consider the harmonic context of those notes. Others may be so well ear-trained to not think about it at all. Experienced musicians often use flexible methods, intuitively deciding the better way to learn each passage.
Answer: General approach
It is generally easier to memorize groups of notes, or patterns of notes, as opposed to memorizing each note individually.
In passages like the ones shown, it can be helpful to "simplify" or "strip down" the passage to essential elements. This sometimes makes clear the composer's intention, which may otherwise be obscured by the "extra" notes. It also can facilitate memorization by simplifying the structure of the passage.
Applied to Clementi
In the case of the Clementi, notice that each beat of sixteenths comprises two different pitches. So one way to practice is to turn the pitch pairs into chords, and hold the chord for the expected duration.

What now becomes more clear is that there are three voices: two in the right hand, one in the left. In this case, another practice technique is to play each voice single, then in pairs, and finally all together. Below is a "hyper-simplified" version. The practice technique goes like this:

Right hand plays top-most voice, left hand plays middle voice.
Right hand plays middle voice, left hand plays bass voice.
Right hand plays top-most voice, left hand plays bass voice.

Applied to Bach
With the Bach, the key observation is that the 32nd notes are "decorative". Although not technically ornaments, they serve a similar purpose. The main note occurs on the beat.

Just looking at the reduced version suggests that each hand is, in effect, playing a three-beat chord in each measure. These could certainly be practiced hands separately, and might work hands together as well. That is, both hands together might form a single chord. (Hint: They do, except the second measure, but the whole passage can still be practiced that way.)

Music theory can help with the "ornamental" notes. Each of them is a half or whole step below the main note, and the determination is according to the key of that particular measure. The first and third measures, for example, are G# minor chords, and the ornaments are diatonic to the G# (harmonic) minor scale. (In fact, the first three measures are in G# minor, and the final measure in G# major so knowing that scale well is helpful.)
But even without this, one could use the Clement "pairs" approach.
Comment: Thank you so much Aaron. This is very helpful! Thanks for taking the time to answer in such detail!


How to Programmatically place order in opencart

Question: I am new to opencart. And now i am working on the order module.The concept is i have to place order externally. So as in the controller/checkout/confirm.php order placement i have placed the order. The order also successfully stored at the order table. But the problem is, the order is not shown at the admin page. I have searched lot for this issue, finally i found that the order is not placed properly.
My code is,
<code>public function index() {
        $redirect = '';
        $this->load->model('account/address');
        $address = $this->model_account_address->getAddress($this->customer->getAddressId());
       if ((!$this->cart->hasProducts() && empty($this->session->data['vouchers'])) || (!$this->cart->hasStock() && !$this->config->get('config_stock_checkout'))) {
            $redirect = $this->url->link('checkout/cart');
        }

        // Validate minimum quantity requirements.
        $products = $this->cart->getProducts();

        foreach ($products as $product) {
            $product_total = 0;

            foreach ($products as $product_2) {
                if ($product_2['product_id'] == $product['product_id']) {
                    $product_total += $product_2['quantity'];
                }
            }

            if ($product['minimum'] > $product_total) {
                $redirect = $this->url->link('checkout/cart');

                break;
            }
        }

        if (!$redirect) {
            $order_data = array();

            $order_data['totals'] = array();
            $total = 0;
            $taxes = $this->cart->getTaxes();

            $this->load->model('extension/extension');

            $sort_order = array();

            $results = $this->model_extension_extension->getExtensions('total');

            foreach ($results as $key => $value) {
                $sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
            }

            array_multisort($sort_order, SORT_ASC, $results);

            foreach ($results as $result) {
                if ($this->config->get($result['code'] . '_status')) {
                    $this->load->model('total/' . $result['code']);

                    $this->{'model_total_' . $result['code']}->getTotal($order_data['totals'], $total, $taxes);
                }
            }

            $sort_order = array();

            foreach ($order_data['totals'] as $key => $value) {
                $sort_order[$key] = $value['sort_order'];
            }

            array_multisort($sort_order, SORT_ASC, $order_data['totals']);

            $this->load->language('checkout/checkout');

            $order_data['invoice_prefix'] = $this->config->get('config_invoice_prefix');
            $order_data['store_id'] = $this->config->get('config_store_id');
            $order_data['store_name'] = $this->config->get('config_name');

            if ($order_data['store_id']) {
                $order_data['store_url'] = $this->config->get('config_url');
            } else {
                $order_data['store_url'] = HTTP_SERVER;
            }

            if ($this->customer->isLogged()) {
                $this->load->model('account/customer');

                $customer_info = $this->model_account_customer->getCustomer($this->customer->getId());

                $order_data['customer_id'] = $this->customer->getId();
                $order_data['customer_group_id'] = $customer_info['customer_group_id'];
                $order_data['firstname'] = $customer_info['firstname'];
                $order_data['lastname'] = $customer_info['lastname'];
                $order_data['email'] = $customer_info['email'];
                $order_data['telephone'] = $customer_info['telephone'];
                $order_data['fax'] = $customer_info['fax'];
                $order_data['custom_field'] = unserialize($customer_info['custom_field']);
            } elseif (isset($this->session->data['guest'])) {
                $order_data['customer_id'] = 0;
                $order_data['customer_group_id'] = $this->session->data['guest']['customer_group_id'];
                $order_data['firstname'] = $this->session->data['guest']['firstname'];
                $order_data['lastname'] = $this->session->data['guest']['lastname'];
                $order_data['email'] = $this->session->data['guest']['email'];
                $order_data['telephone'] = $this->session->data['guest']['telephone'];
                $order_data['fax'] = $this->session->data['guest']['fax'];
                $order_data['custom_field'] = $this->session->data['guest']['custom_field'];
            }

            $order_data['payment_firstname'] = $address['firstname'];
            $order_data['payment_lastname'] = $address['lastname'];
            $order_data['payment_company'] = $address['company'];
            $order_data['payment_address_1'] = $address['address_1'];
            $order_data['payment_address_2'] = $address['address_2'];
            $order_data['payment_city'] = $address['city'];
            $order_data['payment_postcode'] = $address['postcode'];
            $order_data['payment_zone'] = $address['zone'];
            $order_data['payment_zone_id'] = $address['zone_id'];
            $order_data['payment_country'] = $address['country'];
            $order_data['payment_country_id'] = $address['country_id'];
            $order_data['payment_address_format'] = $address['address_format'];
            $order_data['payment_custom_field'] = $address['custom_field'];

            if (isset($this->session->data['payment_method']['title'])) {
                $order_data['payment_method'] = $this->session->data['payment_method']['title'];
            } else {
                $order_data['payment_method'] = '';
            }

            if (isset($this->session->data['payment_method']['code'])) {
                $order_data['payment_code'] = $this->session->data['payment_method']['code'];
            } else {
                $order_data['payment_code'] = '';
            }

            if ($this->cart->hasShipping()) {
                $order_data['shipping_firstname'] = $address['firstname'];
                $order_data['shipping_lastname'] = $address['lastname'];
                $order_data['shipping_company'] = $address['company'];
                $order_data['shipping_address_1'] = $address['address_1'];
                $order_data['shipping_address_2'] = $address['address_2'];
                $order_data['shipping_city'] = $address['city'];
                $order_data['shipping_postcode'] = $address['postcode'];
                $order_data['shipping_zone'] = $address['zone'];
                $order_data['shipping_zone_id'] = $address['zone_id'];
                $order_data['shipping_country'] = $address['country'];
                $order_data['shipping_country_id'] = $address['country_id'];
                $order_data['shipping_address_format'] = $address['address_format'];
                $order_data['shipping_custom_field'] = $address['custom_field'];

                if (isset($this->session->data['shipping_method']['title'])) {
                    $order_data['shipping_method'] = $this->session->data['shipping_method']['title'];
                } else {
                    $order_data['shipping_method'] = '';
                }

                if (isset($this->session->data['shipping_method']['code'])) {
                    $order_data['shipping_code'] = $this->session->data['shipping_method']['code'];
                } else {
                    $order_data['shipping_code'] = '';
                }
            } else {
                $order_data['shipping_firstname'] = '';
                $order_data['shipping_lastname'] = '';
                $order_data['shipping_company'] = '';
                $order_data['shipping_address_1'] = '';
                $order_data['shipping_address_2'] = '';
                $order_data['shipping_city'] = '';
                $order_data['shipping_postcode'] = '';
                $order_data['shipping_zone'] = '';
                $order_data['shipping_zone_id'] = '';
                $order_data['shipping_country'] = '';
                $order_data['shipping_country_id'] = '';
                $order_data['shipping_address_format'] = '';
                $order_data['shipping_custom_field'] = array();
                $order_data['shipping_method'] = '';
                $order_data['shipping_code'] = '';
            }

            $order_data['products'] = array();

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    $option_data[] = array(
                        'product_option_id'       => $option['product_option_id'],
                        'product_option_value_id' => $option['product_option_value_id'],
                        'option_id'               => $option['option_id'],
                        'option_value_id'         => $option['option_value_id'],
                        'name'                    => $option['name'],
                        'value'                   => $option['value'],
                        'type'                    => $option['type']
                    );
                }

                $order_data['products'][] = array(
                    'product_id' => $product['product_id'],
                    'name'       => $product['name'],
                    'model'      => $product['model'],
                    'option'     => $option_data,
                    'download'   => $product['download'],
                    'quantity'   => $product['quantity'],
                    'subtract'   => $product['subtract'],
                    'price'      => $product['price'],
                    'total'      => $product['total'],
                    'tax'        => $this->tax->getTax($product['price'], $product['tax_class_id']),
                    'reward'     => $product['reward']
                );
            }

            // Gift Voucher
            $order_data['vouchers'] = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $voucher) {
                    $order_data['vouchers'][] = array(
                        'description'      => $voucher['description'],
                        'code'             => substr(md5(mt_rand()), 0, 10),
                        'to_name'          => $voucher['to_name'],
                        'to_email'         => $voucher['to_email'],
                        'from_name'        => $voucher['from_name'],
                        'from_email'       => $voucher['from_email'],
                        'voucher_theme_id' => $voucher['voucher_theme_id'],
                        'message'          => $voucher['message'],
                        'amount'           => $voucher['amount']
                    );
                }
            }

            $order_data['comment'] = "";
            $order_data['total'] = $total;

            if (isset($this->request->cookie['tracking'])) {
                $order_data['tracking'] = $this->request->cookie['tracking'];

                $subtotal = $this->cart->getSubTotal();

                // Affiliate
                $this->load->model('affiliate/affiliate');

                $affiliate_info = $this->model_affiliate_affiliate->getAffiliateByCode($this->request->cookie['tracking']);

                if ($affiliate_info) {
                    $order_data['affiliate_id'] = $affiliate_info['affiliate_id'];
                    $order_data['commission'] = ($subtotal / 100) * $affiliate_info['commission'];
                } else {
                    $order_data['affiliate_id'] = 0;
                    $order_data['commission'] = 0;
                }

                // Marketing
                $this->load->model('checkout/marketing');

                $marketing_info = $this->model_checkout_marketing->getMarketingByCode($this->request->cookie['tracking']);

                if ($marketing_info) {
                    $order_data['marketing_id'] = $marketing_info['marketing_id'];
                } else {
                    $order_data['marketing_id'] = 0;
                }
            } else {
                $order_data['affiliate_id'] = 0;
                $order_data['commission'] = 0;
                $order_data['marketing_id'] = 0;
                $order_data['tracking'] = '';
            }

            $order_data['language_id'] = $this->config->get('config_language_id');
            $order_data['currency_id'] = $this->currency->getId();
            $order_data['currency_code'] = $this->currency->getCode();
            $order_data['currency_value'] = $this->currency->getValue($this->currency->getCode());
            $order_data['ip'] = $this->request->server['REMOTE_ADDR'];

            if (!empty($this->request->server['HTTP_X_FORWARDED_FOR'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_X_FORWARDED_FOR'];
            } elseif (!empty($this->request->server['HTTP_CLIENT_IP'])) {
                $order_data['forwarded_ip'] = $this->request->server['HTTP_CLIENT_IP'];
            } else {
                $order_data['forwarded_ip'] = '';
            }

            if (isset($this->request->server['HTTP_USER_AGENT'])) {
                $order_data['user_agent'] = $this->request->server['HTTP_USER_AGENT'];
            } else {
                $order_data['user_agent'] = '';
            }

            if (isset($this->request->server['HTTP_ACCEPT_LANGUAGE'])) {
                $order_data['accept_language'] = $this->request->server['HTTP_ACCEPT_LANGUAGE'];
            } else {
                $order_data['accept_language'] = '';
            }

            $this->load->model('checkout/order');
            $this->session->data['order_id'] = $this->model_checkout_order->addOrder($order_data);

            $data['text_recurring_item'] = $this->language->get('text_recurring_item');
            $data['text_payment_recurring'] = $this->language->get('text_payment_recurring');

            $data['column_name'] = $this->language->get('column_name');
            $data['column_model'] = $this->language->get('column_model');
            $data['column_quantity'] = $this->language->get('column_quantity');
            $data['column_price'] = $this->language->get('column_price');
            $data['column_total'] = $this->language->get('column_total');

            $this->load->model('tool/upload');

            $data['products'] = array();

            foreach ($this->cart->getProducts() as $product) {
                $option_data = array();

                foreach ($product['option'] as $option) {
                    if ($option['type'] != 'file') {
                        $value = $option['value'];
                    } else {
                        $upload_info = $this->model_tool_upload->getUploadByCode($option['value']);

                        if ($upload_info) {
                            $value = $upload_info['name'];
                        } else {
                            $value = '';
                        }
                    }

                    $option_data[] = array(
                        'name'  => $option['name'],
                        'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value)
                    );
                }

                $recurring = '';

                if ($product['recurring']) {
                    $frequencies = array(
                        'day'        => $this->language->get('text_day'),
                        'week'       => $this->language->get('text_week'),
                        'semi_month' => $this->language->get('text_semi_month'),
                        'month'      => $this->language->get('text_month'),
                        'year'       => $this->language->get('text_year'),
                    );

                    if ($product['recurring']['trial']) {
                        $recurring = sprintf($this->language->get('text_trial_description'), $this->currency->format($this->tax->calculate($product['recurring']['trial_price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['trial_cycle'], $frequencies[$product['recurring']['trial_frequency']], $product['recurring']['trial_duration']) . ' ';
                    }

                    if ($product['recurring']['duration']) {
                        $recurring .= sprintf($this->language->get('text_payment_description'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
                    } else {
                        $recurring .= sprintf($this->language->get('text_payment_cancel'), $this->currency->format($this->tax->calculate($product['recurring']['price'] * $product['quantity'], $product['tax_class_id'], $this->config->get('config_tax'))), $product['recurring']['cycle'], $frequencies[$product['recurring']['frequency']], $product['recurring']['duration']);
                    }
                }

                $data['products'][] = array(
                    'key'        => $product['key'],
                    'product_id' => $product['product_id'],
                    'name'       => $product['name'],
                    'model'      => $product['model'],
                    'option'     => $option_data,
                    'recurring'  => $recurring,
                    'quantity'   => $product['quantity'],
                    'subtract'   => $product['subtract'],
                    'price'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax'))),
                    'total'      => $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity']),
                    'href'       => $this->url->link('product/product', 'product_id=' . $product['product_id']),
                );
            }

            // Gift Voucher
            $data['vouchers'] = array();

            if (!empty($this->session->data['vouchers'])) {
                foreach ($this->session->data['vouchers'] as $voucher) {
                    $data['vouchers'][] = array(
                        'description' => $voucher['description'],
                        'amount'      => $this->currency->format($voucher['amount'])
                    );
                }
            }

            $data['totals'] = array();

            foreach ($order_data['totals'] as $total) {
                $data['totals'][] = array(
                    'title' => $total['title'],
                    'text'  => $this->currency->format($total['value']),
                );
            }

            //$data['payment'] = $this->load->controller('payment/' . $this->session->data['payment_method']['code']);
        } else {
            $data['redirect'] = $redirect;
        }

        echo json_encode("success");

    }
</code>
Is this correct format or still any process to do like updating order table or etc...
I really don't know what to do next.. Please someone guide me to get rid of this issue..
Thanks
Answer: Opencart admin display order which orders have order status is > 0. Did you check your order_status_id in database it will be 0.
That's the issue. How Opencart works, when you are at checkout - confirm page but you haven't confirm your order, Opencart already entered one entry for that order with order status id - 0.
After that when you confirm your order than your selected payment method - callback function (in mostly payment method(s)) update your order status using model > checkout > order function addOrderHistory().
So problem is that you added your order to Opencart but not updated it's order_status_id so after adding order add a function to your module with will update order status of last (or your added) order. For that you can check default payment methods.
Comment: I am using instamojo payment gateway but I have checked its callback function but it is giving error of invalid auth token
Comment: @RohitashvSinghal i think that's payment method error, you can ask payment company for support or can google error so that u will know reason.


Checking the solution of a first order pde

Question: I need some help with this exercise.
Given the following pde:
 $  \begin{cases}
     u_t + b(u)\cdot u_x=0\\[6pt]
      u(x, 0) = u_0(x)
  \end{cases}
 $
I have to check that its solution is $u(x, t)=u_0(\psi(x,t))$ where $x=b(u_0(\psi(x,t)))\cdot t +\psi(x,t)$.
It should not be difficult, but i'm making a mess with implicit derivation, and getting nowhere. Thanks a lot for any indication.
Comment: Is $\psi$ constant?
Comment: I think so, yes.
Comment: and hence u is constant itself!!
Comment: Ups, sorry. I should have written $\psi(x,t)$. In other way it makes no sense,
Comment: i am running in a circle trying to do it
Comment: Maybe $\psi$ is constant. That would only imply $u$ is constant over each straight line $x=b(u_0(\psi))\cdot t +\psi$
Comment: Finally i did it wow
Answer: Differentiating with repect to $x$ and $t$ we get $$1=b'(u_0(\psi(x,t)))\cdot u'_0(\psi(x,t)\cdot \psi_x(x,t)\cdot t +\psi_x(x,t)
\\ 0=b'(u_0(\psi(x,t)))\cdot u'_0(\psi(x,t)\cdot \psi_t(x,t)\cdot t+b(u_0(\psi(x,t))) +\psi_t(x,t)$$ so we have $\psi_t(x,t)=-b\psi_x(x,t)$ equation 1
Moreover,
$$u_x(x, t)=u'_0(\psi(x,t))\cdot \psi_x(x,t)
\\ u_t(x, t)=u'_0(\psi(x,t))\cdot \psi_t(x,t)$$
Then
$$RHS=u'_0(\psi(x,t))\cdot \psi_t(x,t)+b\cdot u'_0(\psi(x,t))\cdot \psi_x(x,t)
\\=0$$
using equation 1
Comment: i have revised the equations and think it is now true
Comment: I don't see how you get equation 1. Also, in the second equation you wrote, I think a $t$ is missing, multiplying next to $\psi_t$
Comment: Ok, I just saw it! Thanks a lot, Semsem :)
Comment: I cancel $b' \cdot u'$ from the first two equations


How can I Limit or forbid download from my Storage?

Question: Every month we have huge number of data download from our Google storage, when we have only about 4Gb pics and docs.
How to understand who use our storage, who and what download and upload in our storage.
How to fix it?
Here it is the examples of
<code>July 2015
Cloud Storage Download US EMEA: 61.511 Gibibytes (Project:API Project) - 7.38
June 2015
Cloud Storage Download US EMEA: 449.487 Gibibytes (Project:API Project) - 53.94
May 2015
Cloud Storage Download US EMEA: 39.645 Gibibytes (Project:API Project) - 4.76
</code>
Answer: You can turn on Access Logging which will provide you a log with every access to your data. This will allow you to see who is downloading your data, when.
You can limit who has access by setting up appropriate Access Control.


Evaluating $\int_0^\infty x^{2\alpha-1}(e^{-x^\alpha}-e^{-r^\alpha x^\alpha})^{n-2}e^{-x^\alpha(1+r^\alpha)}\,dx$

Question: I am looking for a tractable closed form of the following integral where $\alpha>0,r>1$:
$$I=\int_0^\infty x^{2\alpha-1}(e^{-x^\alpha}-e^{-r^\alpha x^\alpha})^{n-2}e^{-x^\alpha(1+r^\alpha)}\,dx\tag{1}$$
It can be assumed that $n\ge2$ is an integer.
Plugging $I$ directly into Mathematica, I get a sort of ugly answer involving non-elementary functions. Not to mention there is some confusion over the convergence of the integral.
Is there a way to tackle the integral by hand and arrive at a form involving elementary functions?
The context is in finding the density of $(\max_{1\le i\le n}X_i/\min_{1\le i\le n} X_i)$ where $X_1,X_2,\cdots,X_n$ are independent random variables having the common Weibull density
$$f(x)=\alpha x^{\alpha-1}e^{-x^{\alpha}}\mathbf1_{x>0}\,,\quad\alpha>0$$
I had used a change of variables $(\max X_i,\min X_i)\to\left(\frac{\max X_i}{\min X_i},\min X_i\right)$ to be faced with $(1)$ trying to find the marginal density $\frac{\max X_i}{\min X_i}$ from the joint density of $\left(\frac{\max X_i}{\min X_i},\min X_i\right)$.
Answer: You can start with the substitution $x^\alpha = y$ . If we let $R = r^\alpha$ , it leads to
$$ I = \frac{1}{\alpha} \int \limits_0^\infty y \left(\mathrm{e}^{-y} - \mathrm{e}^{-R y}\right)^{n-2} \mathrm{e}^{-(1+R) y} \,  \mathrm{d} y \, .$$
In this form it is even more evident that there are no convergence issues for the given ranges of the parameters.
If you want to avoid special functions, you should probably expand the integrand using the binomial theorem:
\begin{align}
I &= \frac{1}{\alpha} \sum \limits_{k=0}^{n-2} {n-2\choose k} (-1)^k \int \limits_0^\infty y \mathrm{e}^{-[R(k+1) + n-2-k+1] y} \,  \mathrm{d} y \\
&= \frac{1}{\alpha} \sum \limits_{k=0}^{n-2} {n-2\choose k} \frac{(-1)^k}{[n + (r^\alpha-1)(k+1)]^2} \, .
\end{align}
I do not see further simplifications for general values of the parameters, but it is a finite sum of nice functions.
In order to get a solution in terms of special functions, the substitution $\mathrm{e}^{-(R-1) y} = t$ can be used to find
\begin{align}
I &= - \frac{1}{\alpha(R-1)^2} \int \limits_0^1 \ln(t) t^\frac{n}{R-1} (1-t)^{n-2} \, \mathrm{d} t \\
&= - \frac{1}{\alpha (r^\alpha -1)^2} \operatorname{\partial_1} \operatorname{B} \left(\frac{n}{r^\alpha - 1} + 1 , n-1\right)
\end{align}
with the beta function $\operatorname{B}$, which eventually reduces to the result given by Mathematica.
Comment: Thanks, the expression with the binomial coefficient was all I was looking for.


Xamarin save photo with latitude and longitude

Question: I am new to Xamarin. I want to take a photo and write to console the latitude and longitude, where the photo was taken. I'm trying to get it with the following code:
var exif = new ExifInterface(picUri.Path);
var latLong = new float[2];
float? lat = null, lng = null;
if (exif.GetLatLong(latLong))
{
    lat = latLong[0];
    lng = latLong[1];
}

if(lat != null && lng != null)
{
    Console.WriteLine("Latitue {0}, Longitude {1} ", lat, lng);
}
else
{
    Console.WriteLine("Some value is equals to null");
}

And I've got Some value is equals to null in the console. What am i missing?
Comment: You can search the Xamarin.Forms.Maps plugin. I use my last application. When the device open GPS, about 2 secound after, find the device location.

https://i.hizliresim.com/YOrdkl.jpg
Answer: You need to add also
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

in the manifest


Android DownloadManager - Download apk and install it

Question: I have looked everywhere to find out how to download a APK that is not from the market place. The APK is stored in my server.
All the sample did not work.
I want my App to download an APK for my server and promt the user to install it.
So far I managed to download the apk onto the user sd. but I can't get he path where is it saved and get to install it.
private void downloadAPK() {
    String url="https://www.example.com/app.apk";
    downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    request = new Request(Uri.parse(url));
    request.setTitle("My App");
    enqueue = downloadManager.enqueue(request);

      new Thread(new Runnable() {

        @Override
        public void run() {

            boolean downloading = true;

            while (downloading) {

                try {
                    Thread.sleep(10000);
                     DownloadManager.Query q = new DownloadManager.Query();
                        q.setFilterById(enqueue);

                        Cursor cursor = downloadManager.query(q);
                        cursor.moveToFirst();
                        int bytes_downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                        int bytes_total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));

                        if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {
                            downloading = false;
                        }

                        final int dl_progress = (int) ((double)bytes_downloaded / (double)bytes_total * 100f);

                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {

                                Log.d("Prog", Integer.toString(dl_progress));
                            }
                        });

                        cursor.close();
                } catch (InterruptedException e) {

                }

            }

        }
    }).start();
}}

BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
             Log.w("", "Downloaded")

        }
        else {
            //do something here
       }

    }
};

onCreate ...
registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

Answer: According to the documentation you can specify the location where you want the file to be saved. All you have to do is adding this line before setting the request to de DownloadManager :
request.setDestinationInExternalFilesDir (context, dirType, subPath);

Answer: You can Query about your download local file using the code below :
Note that :
will return null if the download failed.
String path = Uri.parse(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))).getPath()


Recurrence relation with Z-Transform

Question: I'm revising the Z-Transform. I am looking at the book which gives an example of how to solve the recurrence relation
$$x_{k+2} - 3x_{k+1} +2x_k = 1$$
where $x_0 = 0$ and $x_1 = 1$. The book uses the left-shift theorem which states that if $Z[x_k] = F(z)$ then $Z[x_{k+m}] = z^m F(z) - (z^m x_0 + z^{m-1} x_1 + z^{m-2} x_2 + \dots + z x_{m-1})$. Using this, we can find the solution.
However, I remember 10 years ago when I did a lot of signal processing, I used to invert the recurrence relation so that I can use the right-shift theorem which is simpler. So I would convert the above recurrence relation to
$$x_k - 3 x_{k-1} + 2 x_{k-2} = 1$$
and then use the right-shift theorem which states: if $Z[x_k] = F(z)$ then $Z[x_{k-m}] = z^{-m}F(z)$. Using this technique, I get a different result to the book. I must have made a mistake because I also don't get the opportunity to input the initial conditions using the right shift theorem. What have I done wrong? I don't need the recurrence relationship solved - the book solves it. I just don't know if what I remember is true or if I'm mistaken.
Answer: In this case the result of the question in using the right-shift form is correct in concept. In this case the initial terms are not required.
The process becomes more clear when solving this recurrence relation:
$$ x_{k} - 3 \, x_{k-1} + 2 \, x_{k-2} = 1 $$
by the following method.
\begin{align}
x_{k} - 3 \, x_{k-1} + 2 \, x_{k-2} &= 1 \\
F - \frac{3}{t} \, F + \frac{2}{t^2} \, F &= \frac{t}{t-1} \\
(2 - 3 t + t^2) \, F &= \frac{t^3}{t-1} \\
F &= \frac{t^3}{(t-1)^2 \, (t-2)} \\
&= \frac{1}{\left(1 = \frac{1}{t}\right)^2 \, \left(1 - \frac{2}{t}\right)} \\
&= - \frac{1}{(\left(1 - \frac{1}{t}\right)^2} - \frac{2}{1- \frac{1}{t}} + \frac{4}{1- \frac{2}{t}} \\
&= \sum_{n=0}^{\infty} ( 2^{n+2} - n - 3 ) \, t^{-n},
\end{align}
where
$$ F(t) = \sum_{n=0}^{\infty} x_{n} \, t^{-n}. $$
The solution of the difference equation is then
$$ x_{k} = 2^{k+2} - k - 3. $$
This result may be a shifted form of result.
When considering the original form
$$ y_{n+2} - 3 \, y_{n+1} + 2 \, y_{n} = 1$$
the general solution is
$$ y_{n} = c_{0} \, 2^n - n - 1 + c_{1} $$
which maintains the same form as the result found for $x_{k}$.

Recurrence relation with Z-Transform


loop em matriz de correlação em R

Question: Tenho tentado aprender sobre loops e funções em R. Assim me dispus à seguinte situação:
Tenho uma matriz de correlação par a par:
dados<-matrix(rnorm(100),5,5)
colnames(dados)<-c('A','B','C','D','E')
rownames(dados)<-c('A','B','C','D','E')
dados
cor<-cor(dados)

Quero usar condições de loop e if para obter apenas as combinações das variáveis com valores > 0.5 do objeto cor. Entretando, não consigo encontrar uma modo para percorrer par a par as linhas e colunas da minha matrix.
Tenho tentado o seguinte código:
for (i in 1:nrow(cor)){
  for (j in 1:ncol(cor)){
    # comando para comparar par a par
    if (cor[i,j]>0.5){
      #retornar um nova matrix com variável e valor > 0.5
    }
  }
}

Alguém pode me ajudar a solucionar esses comandos?
Answer: Pressupondo que você queira que usar loops (para treinar ou por outra razão, porque neste caso não é preciso usar loops), você pode aramazenar os resultados em uma lista.
Recriando seus dados (com set.seed() para reproducibilidade):
set.seed(10)
dados <- matrix(rnorm(100),5,5)
colnames(dados) <- c('A','B','C','D','E')
rownames(dados) <- c('A','B','C','D','E')
cor <- cor(dados)

Percorrendo o loop e salvando resultados em uma lista:
# lista para armazenar resultado
resultados <- list()

for (i in 1:nrow(cor)){
  for (j in 1:ncol(cor)){
    if (cor[i,j]>0.5){
      # armazena no primeiro nível a linha e no segundo nível a coluna
      resultados[[rownames(cor)[i]]][[colnames(cor)[j]]] <- cor[i,j]
    }
  }
}

resultados
$A
        A         C
1.0000000 0.7764006

$B
       B        E
1.000000 0.912793

$C
        A         C
0.7764006 1.0000000

$D
D
1

$E
       B        E
0.912793 1.000000

Com a lista em mãos você pode arrumar os dados da forma como quiser. Por exemplo, a forma mais simples de transformar em um vetor é com unlist().
unlist(resultados)

     A.A       A.C       B.B       B.E       C.A       C.C       D.D       E.B       E.E
1.0000000 0.7764006 1.0000000 0.9127930 0.7764006 1.0000000 1.0000000 0.9127930 1.0000000

Mas vale lembrar que você não precisa usar loops neste caso. Por exemplo, uma forma de obter o mesmo resultado acima seria:
indices <- which(cor > 0.5, arr.ind = TRUE)
res <- setNames(cor[indices], paste(colnames(cor)[indices[,2]], rownames(cor)[indices[,1]], sep = "."))
res
     A.A       A.C       B.B       B.E       C.A       C.C       D.D       E.B       E.E
1.0000000 0.7764006 1.0000000 0.9127930 0.7764006 1.0000000 1.0000000 0.9127930 1.0000000

Answer: Um jeito fácil é utilizar a função melt do pacote reshape2, como foi explicado nessa pergunta (em inglês).
código:
install.packages("reshape2")             # Caso você não tenha instalado o pacote ainda
library(reshape2)

set.seed(0101)
dados <- matrix(rnorm(100),5,5)
colnames(dados) <- c('A','B','C','D','E')
rownames(dados) <- c('A','B','C','D','E')
CorMatrix <- cor(dados)                    # Tente usar nomes de variáveis que não sejam
                                           # também nome de função

CM <- corMatrix                            # Copiando sua matriz
CM[lower.tri(CM, diag = TRUE)] <- NA       # Removendo as correlações repetidas e a diagonal
rownames(resultados) <- NULL               # (não necessário) limpando os nomes das linhas
resultado <- subset(                      # Filtra as linhas que possuem o valor de correlação
    melt(CM, na.rm=T),                     # maior do que você queira (0.5 no caso)
    value > 0.5)

resultado:
>resultado
   Var1  Var2   value
1   C     D    0.5215197

Uma dica referente ao seu código, não utilize o nome de uma função como nome de variável, como foi o caso da matrix cor.

loop em matriz de correlação em R


How to show that $\sum\frac{c_nt^ne^{-t}}{n!}$ converges absolutely?

Question: We know that $\sum_n c_n$ converges absolutely where $c_n$ is complex.
How to show that $$\sum_n\frac{c_nt^ne^{-t}}{n!}$$ converges absolutely on $\mathbb{R}$.
I tried the ratio test of the term $\left|\dfrac{c_n t^ne^{-t}}{n!}\right|$
I get $$\left|\dfrac{t}{n+1}\dfrac{c_{n+1}}{c_n}\right|$$
Comment: Hint: it's enough to show $|\frac{c_nt^ne^{-t}}{n!}|\leq|c_n|$ for large $n$.
Comment: So I have to show that $\lim\limits_{n\to\infty}\dfrac{t^n}{n!}=0$?
Comment: Yes, that will be enough.
Answer: Noting that $$(n!)^{1/n} > \log n - 1,$$ we have, by the root test, that $$\left|\frac{c_nt^ne^{-t}}{n!}\right|^{1/n} < \frac {|c_n e^{-t}|^{1/n} t} {\log n - 1} \to_{n \to \infty} 0,$$ where $t$ is a real constant and $|c_n|$ is obviously bounded. This means that the series converges absolutely.


Recommended Way to Control Making HTTP requests?

Question: Hypothetically, if the user clicks "save,save,save,save" a bunch of times on a text file, making single character changes at a time and managing to resave 5 times before the first save is processed, what is best practice in that situation?  Assuming we don't have a "batch process" option...  Or maybe they push save,save,save,save on 4 files one after the next before they've all been processed.
Should you queue up the requests and process them one at a time?  Or should you just let it happen and it will work itself out somehow?
Thanks!
Answer: We usually send down a GUID in the page when a form is initialized, and send it along on the save request. The server checks a shared short-term memory cache- if it's a miss, we store the GUID and process the save, if it's a hit, we fail as a dupe request. This allows one save per page load (unless you do something to reinit the GUID on a successful save).
Comment: i'm just wondering if it's a problem for the server, or does it have everything built in to handle this? I'm thinking Rails here :)
Comment: Just depends on the editing semantics. If "last writer wins" is OK and you don't have any app-level transaction or locking issues, I wouldn't worry about it. If you're talking about credit card transactions or something else with major side effects (save-to-disk, file creation, etc), then yeah, you need to lock it down somehow.
Answer: If you make your save operation light enough, it shouldn't matter how many times the user hits save.  The amount of traffic a single user can generate is usually quite light compared to the load of thousands of users.
I'd suggest watching the HTTP traffic when you compose a Gmail message or work in Google docs.  Both are very chatty, and frequently send updates back to the server.


How do I minimize my installer in Inno Setup?

Question: I created my own custom minimize button in Inno Setup.
I would like to know how to minimize my installer when I click on it.
The minimize should be just like the default minimize button on the border of the installer.
Answer: To simulate a click on the minimize button in a window title, send WM_SYSCOMMAND message to the installer wizard form using the PostMessage support function:
const
  WM_SYSCOMMAND = 274;
  SC_MINIMIZE = $F020;

procedure MinimizeButtonClick(Sender: TObject);
begin
  PostMessage(WizardForm.Handle, WM_SYSCOMMAND, SC_MINIMIZE, 0);
end;

Answer: You can use this code.
procedure MinimizeBtnClick(Sender: Tobject);
begin
 SendMessage(WizardForm.Handle,$112,61472,0);
end;

Comment: That's exactly the same code as my answer shows. You have just used hexadecimal notation, where I've used decimal notation, and vice versa.
Comment: Im sorry mr. According to me, in programming we can use many different codes but all it same means. So, please appreciate people to answer a question. Thanks sorry if i distrub you


Roman numeral slash notation meaning and function? (V/iii)

Question: When trying to find the function of the B major chord in C major I found that it was listed as a "V/iii" chord in this online calculator. I have never seen this before and don't know what this means and what it suggests about the function. To be clear, not referring to inversion slash chords (C/G, Am/C etc.)

I am quite new to RN analysis and any help would be greatly appreciated as I am unsure where to find such information online.
Comment: Careful. I respectfully believe Aaron is confusing two concepts. I think the above linked question is a different thing to what is being asked in the OP. There are two different kinds of "slashy" chord notations. Aaron's link is talking about "chord over bass" (Gmaj _over_ E bass) but the OP (and the answers below) are about "secondary tonality"  (the five of five, the five of four, etc).
Comment: @gingerbreadboy - generally there is the slash chord in letters, like C/E, which signify a C chord with E in the bass (1st inversion), and the one OP is asking about, - R.N. Two very usual. Can't think of the other ten...
Comment: @Aaron - not the slash chord question at all similar to the one quoted. OP is using RN.
Comment: Does this answer your question? [What does the chord notation X/Y ("slash chord") mean?](https://music.stackexchange.com/questions/104163/what-does-the-chord-notation-x-y-slash-chord-mean)
Comment: `two different kinds` who am I kidding there are probably a dozen different uses for `slash` in chords and notation :)
Comment: @Tim This usage is covered in the answer and includes a link to another post with additional information. "In Functional Analysis (Roman Numeral Analysis), slashes are used to indicate a secondary dominant relationship. Secondary dominants are explained in [What is a secondary dominant chord?](https://music.stackexchange.com/q/22057/70803)."
Answer: iii in key C major is E minor. The V of that chord is B (or B7). B is non-diatonic, and is called the secondary dominant in that key. It can lead to Em, and often does, although, despite the allusion that it's going to, it often doesn't.
So, V/iii is the dominant of a diatonic chord from a particular key. Another example would be V/V,, where the 1st V represents D (or D7), which does often feature moving to the dominant of that key. The 'dominant of the dominant'.
Comment: Is this applicable to all scale degrees? For example could I analyse Bm as iii/V ("secondary mediant to the dominant")?
Comment: I can only recall seeing dominants used in this way, V or vii
Comment: @LeaG only if it is a useful description. A chord with dominant function usually leads very strongly to its resolution and therefore it makes sense to describe it as relative to that chord (e.g. V/iii). Your example, iii of V, is a chord that for starters would be exceedingly rare (if you want to use this label you probably missed one or more modulations) but also, the iii of V usually does not have a very clear relationship to V itself, so even if you encounter those notes it most probably functions differently and should then also be described differently.
Comment: @nuggethead - secondary dominants are seen V/ii, V/iii, V/V and V/vii. There's a possibility of V7/IV, as V7 there contains a non-diatonic b7. Need to verify that one!
Comment: @LeaG - the point of secondary dominants id that they are dominants of of diatonic chords. iii/V would not constitute such.
Comment: @LeaG: If you really think that Bm is useful to describe as iii/V, maybe it would be better to think of V as tonic—maybe the song has temporarily modulated into a different key.
Answer: This notation is used to code secondary tonalities. V/iii then would be read as "the secondary dominant to the root iii (which in this case is B major to E minor)".
Generally the notation is function/key. Note though that B major does not necessarily have that function in the context of C major.
Comment: It's certainly true that V/iii _means_ "the secondary dominant of the mediant," it's more commonly _read_ as "five of three."
Comment: @phoog: Indeed.  Further, since the V of III and the V of the iii would both be the same chord (a VII with raised sharp accidentals on the third and fifth), there's no need to say "V of minor iii" to distinguish it from "V of III".
Answer: V of iii.  The dominant of iii, which in this case is Em.  Quire a common progression.
Starting off in C major, you'll also often come across D leading to G, V of V.  Or E leading to Am, V of vi.
If B - Em results in a lengthy visit to Em, you'll probably find it useful to re-designate Em as i.  If the chord progression is 'just passing through' leave it as iii.   A chromatic chord does not necessarily imply a new key centre.
B can also function as a dominant to C major - all three notes are 'leading notes' to those of the C triad!


regular expression is not producing the expected result in hive

Question: I want to replace non-ASCII characters with empty space in hive query. I tried below query. But it is not working..
<code>select regexp_replace(col_name, '[^\u0000-\u007F]+', '')
</code>
What am I doing wrong here? any clues will be appreciated. Thanks in advance.
Comment: Joe, if possible, can you please give example of non-ASCII characters that you are trying to replace in your question, I am trying select regexp_replace("Big¿¿©Data", '[^\u0000-\u007F]+', ''); and its giving me output by replacing ¿¿© char with space.
Comment: @praxnet  When I execute the query select regexp_replace("Big¿¿©Data", '[^\u0000-\u007F]+', '')  in hive, I am getting  BD as result , everything else is replaced .. is that expected.
Comment: @praxnet ,, I am not able to paste the character in the comment box  that I am trying to replace.
Comment: What I meant was, select regexp_replace("Big¿¿©Data", '[^\u0000-\u007F]+', '')  -->  Output = BigData, non-ASCII characters replaced with space are  ¿¿©
Comment: Can you share a link of your non-ascii characters by putting it in some site like https://unicodelookup.com/#%C6%92/1
Answer: remove the ^ as that is 'beginning of a string' marker


divs floated to left and right + another div therebetween

Question: This is my mockup:

I want to set divs as in the picture. DIV 1 and DIV 2 contain dynamically generated content and the width is different every time.
Div 1 is floated to the left side and Div 2 is floated to the right side.
My question is: how to position Div 3 to fit it between div 1 and 3?
My code is:
HTML

sassssss

dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd

asdasdfgdsgdf

CSS
.dia {
background: #282828;
padding: 10px;
height: 106px;
border-radius: 5px;
}

.dia .center {
 margin-left: 20px;
}

.dia .left, .dia .right {
 overflow: hidden;
}

.dia .left {
 float: left;
 margin-right: 10px;
}

.dia .right {
 float: right;
 margin-left: 10px;
 background: rgb(214,214,214);
}

and I want to fit center div which now is too wide and moves right div lower than I want.

SOLUTION:
HTML

sassssss

ddddddddddddddddddddd dddddddddddddddddddddddddd ddddddddddddddddddddddddddddddddd dddddddddddd

asdasdfgdsgdf

CSS
.dia {
 background: #282828;
 padding: 10px;
 height: 106px;
 border-radius: 5px;
 width: inherit;
}

.dia .left, .dia .right {
 overflow: hidden;
 height: 106px;
}

.dia .left {
 float: left;
 margin-right: 10px;
}

.dia .right {
 float: right;
 margin-left: 10px;
}

.dia .center {
 height: inherit;
 float: left;
}

JQuery
$('.dia .left a:not(:first-child)').css('width',$('.dia a').outerWidth(true)+'px');
$('.dia .center').css('width',$('.dia').width()-$('.dia .left').outerWidth(true)-$('.dia .right').outerWidth(true)+'px');

And Fiddle
Comment: Please add your code to the question as well, that way if the [link rots](http://en.wikipedia.org/wiki/Link_rot) this question will remain useful to future visitors.
Comment: Do you know how wide div 1 and 2 are as you generate the page?
Comment: Setting a fixed width to your `.dia` / parent class can resolve your issue.
Comment: Jeroen: I add it in few minutes.
Laurence: No. I don't know.
Shahar: I'll try it tomorrow. ;)
Comment: Shahar: I setted fixed width but it didn't work for me.
Answer: Simply float the central div.
For your purpose you case use:
.dia{
float:left//Float container in order to contain nested elements.
}

.dia div{
float:left;
}

Here's a fiddle you can fiddle with
Comment: but maybe i can calculate secure width for side divs.. Thanks ;)
so.. JavaScript can help me. Right. I want to mark your answer as useful but i haven't reputation enough. How can i get some?
Comment: but when parent div will be not enough wide three divs will be one below another. Try resize Result area to smaller width one and you'll see. I want something like on my mockup.
Comment: You can add a min-width property to avoid that. It all depends in the content. like this http://jsfiddle.net/raam86/YvnnW/28/
Comment: but i don't know the min width required for content in div 1 and 2. It'll have dynamic size content.
Comment: So use javascript. You can't have it all
Comment: You can click the the tick under the vote count. This will choose the answer. You can also give useful answers for more rep ;)
Comment: I need 15 rep points to mark as useful but i have only 11 :( :P
Comment: You need 15 rep to vpvote and no minimum rep to choose best answer/
Comment: But nobody published 100% correct answer. Everyone help me in which direction I have to go but in every answer requires something more than it's written. So I want to mark answer as useful not as a correct.
Answer: Well I did manage to do this in this fiddle, but it feels a little like a workaround, since you have to be careful with center content. Then again, it works, so you can use it as a placeholder or something until you or someone else comes up with better solution.
CSS:
.dia {
background: #282828;
padding: 10px;
height: 106px;
border-radius: 5px;
}

.dia .center {
overflow:auto;
height: 100px;
background-color: #aaa;
margin-left: 20px;
}

.dia .left {
float: left;
height: 100px;
background-color: #ddd;
}

.dia .right {
position:absolute;
/*.dia padding + border*/
right: 15px;
/*.dia padding + border + (.dia height - this height)/2*/
top: 18px;
height: 100px;
background: rgb(214,214,214);
}

Comment: so. to this fiddle i have to add only line breaking ;)
Comment: It depends on what you are using your side divs for. If they don't have much content, this shouldn't be a problem. But I think the answer and comments by raam86 sound better.
Comment: I get it to work tomorrow. ;) It's probably the best solution for my idea :)
Comment: In yours solution center div was to wide and text isn't displayed completely but setting static height is a good idea ;) Thanks for help (I can't set your post as useful because 15 rep is required)
Comment: @Maciej Czekaj wait, you mean you can't select an answer? You should see a black&white "check" symbol under the votes number... Click it to accept an answer.
Comment: But nobody published 100% correct answer. Everyone help me in which direction I have to go but in every answer requires something more than it's written. So I want to mark answer as useful not as a correct.
Answer: try this.
<!DOCTYPE html>

RED

BLUE

Green div with more content.

Answer: How about using a table instead?

             sassssss
             dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
             asdasdfgdsgdf

Then the CSS would be:
.dia {
    background: #282828;
    padding: 10px;
    height: 106px;
    border-radius: 5px;
    width: 100%;
    table-layout: fixed;
}

.dia .center {
    margin-left: 20px;
    word-wrap: break-word;
}

.dia .left, .dia .right {
    overflow: hidden;
}

.dia .left {
    float: left;
    margin-right: 10px;
}

.dia .right {
    float: right;
    margin-left: 10px;
    background: rgb(214,214,214);
}

http://jsfiddle.net/YvnnW/13/
Comment: I would agree in most cases. Makes this problem easily fixed though.
Comment: Seeing HTML is semantic and OP doesn't state it is probably better to use divs or sections or anythings which isn't table which bloats the page and is inflexible.
Comment: Tables are used to hold tabular data. Why people decide to keep on using them for layout is beyond me. Every browser renders them differently. So even if it may seem easier to do it with tables, in the end some of your users will pay the price.
Comment: I'm rewriting page from tables so I can't use your solve (but your fiddle shows what i want to do) ;)
Comment: Dunno's idea works. as long as you also add `word-break: break-word;` to your divs so that those super long words will be forced to wrap.


Determine whether the following map is a linear transformation.

Question: So I have to determine if the following is a linear transformation: $$T: F(I) \rightarrow F(I)$$ defined by: $$T(f) = 2f$$
I know that if you let $T: V\rightarrow W$ be a linear transformation. Then:
a. $T(cu) = cT(u)$ for all $v$ in $V$.
b. $T(u-v) = T(u)-T(v)$ for all $u$ and $v$ in $V$.
So I think I am supposed to let $f_1,f_2$ be in $F$ (or maybe $I$??) and let a scalar $c$ be a real number as well and put them into a, b and solve them for the proof but I'm not sure how I would apply this for this question since the definition of the transformation is $T(f) = 2f$.
Any help would be appreciated. Thanks.
Comment: What is $F(I)$?
Comment: Linearity is $T(af + bg) = aT(f) + bT(g)$ where $a,b$ are elements of the underlying field
Answer: Your "vectors" are elements of $F(I)$, which are functions on the interval(?) $I$. Note that the zero "vector" is actually a function that sends everything to zero.
Your scalars are probably real numbers. They need to be in a field (e.g. real numbers, complex numbers) and should not be in $F(I)$.
Finally, I think you should use the definition of linearity that Ilya posted in the comment above; in particular I don't think $T(cv)=c T(v)$ is implied by the three conditions that you wrote.
Comment: Yeah the question is in the interval $I$. And okay I understand about the scalar. And hmm yeah I just noticed I wrote down the wrong condition, I'll edit it.


Probability of choosing red $\geq 11$ times out of $21$ and probability of choosing red $= 3/4$?

Question: As per the title of the question, I'm interested in finding out how exactly to calculate the probability of choosing, let's say, a red ball out of a bag of balls $\geq 11$ times out of $21$ random, independent trials, and the probability of choosing red is $3/4$ for a single trial?
I understand that in "greater than" scenarios, it's equivalent to the probability of choosing a red ball exactly 11 times + 12 times + ... + 21 times, and for that you use the combination formula (or binomial theorem?), but I'm mostly confused on where exactly the $3/4$ factors into the entire calculation?
Comment: In the [binomial distribution](https://en.wikipedia.org/wiki/Binomial_distribution) the $\frac{3}{4}$ will play the role of $p$.  Letting $X$ be the random variable counting the number of successes, the probability that exactly $k$ occurrences out of $n$ will be "successes" where success has probability $p$ will be $Pr(X=k)=\binom{n}{k}p^k(1-p)^{n-k}$
Answer: Here is how you can calculate the probability of choosing exactly 11 red balls out of 21:
First, there are $21 \choose 11$ possible ways of getting 11 red balls out of 21.  For example, you can start with picking 11 red balls, followed by 10 non-red balls, or first pck 10 non-red balls, and then 11 red balls, or start with a red ball, and alternate with non-red balls, or ...  Again, the number of possible ways or sequences here is $21 \choose 11$
Now, if we focus on a specific sequence:
11 times you need to pick a red ball: $\big( \frac{3}{4} \big)^{11}$ (here is where the $\frac{3}{4}$ comes in)
and 10 times you need to pick a non-red ball: $\big( \frac{1}{4} \big)^{10}$ (the $\frac{1}{4}$ is of course the probability of getting a non-red ball on a single draw, which is $1- \frac{3}{4}$, so this is where the $\frac{3}{4}$ comes in again)
So, a specific sequence occurs with a chance of $\big( \frac{3}{4} \big)^{11} \cdot \big( \frac{1}{4} \big)^{10}$
But since you have $21 \choose 11$ of such possible sequences, (all of which are mutually exclusive), we can add up their probabilities, i.e. we get a probability of:
$\big( \frac{3}{4} \big)^{11} \cdot \big( \frac{1}{4} \big)^{10} \cdot {21 \choose 11}$
of getting exactly 11 red balls
OK, so now you add to this the probability of getting exactly 12 red balls, 13, etc.
P.s. It's too bad the probability of getting a red ball on a single draw is not $\frac{1}{2}$, for then the answer would be very easy ... do you see what it would be and why?
Answer: There are at least three methods of computing such binomial probabilities: (1) Using the formula for the PDF of the relevant binomial distribution, (2) using a normal approximation to binomial, (3) computing exact binomial probabilities using mathematical or statistical software.
You have $X \sim \mathsf{Binom}(n = 21, p=3/4)$ and you seek
$$P(X \ge 11) = P(X > 10) = 1 - P(X \le 10).$$
(1) You are correct that you need to find $P(X = 11) + P(X=12) + \cdots + P(X=21).$ @Bram28 has discussed this in some detail (+1).
(2) This binomial distribution has $E(X) = \mu = np = 21(3/4) = 15.75$ and
$SD(X) = \sigma = \sqrt{21(3/4)(1/4)} =  1.9843.$ The normal distribution
$\mathsf{Norm}(\mu = 15.75, \sigma = 1.9843)$ provides a
reasonably good approximation.
$$P(X \ge 10.5) = P\left(\frac{X - \mu}{\sigma} > \frac{10.5-15.75}{1.9843}\right) \approx P(Z > -2.6458),$$
where $Z$ has a standard normal distribution. You can evaluate this
probability using printed normal tables, but you will need to use -2.65
instead of -2.6458. The answer is about  0.9959 or 0.9960, depending on
the table you use and how much rounding you do.
The figure below shows bars for binomial probabilities and the density curve of the 'best fitting' normal. You want the probability to the right of the vertical broken line.

Note: In view of the figure, you might come very close in (1) by using the binomial PDF to find
$P(X = 8) + P(X = 9) + P(X = 10)$ and subtracting the total from $1$, because there seems to be almost no binomial probability less than 8.
(3) You can use a statistical calculator or software to find the exact
probability. For example, using R statistical software (in which pbinom is
the binomial CDF), we have the result 0.9936.
1 - pbinom(10, 21, 3/4)
## 0.9935773


Random number with negative min or max and with 0.5 as possible decimal

Question: So basically I need to generate a number between a min and max (could be negative as well) and there should be a possibility the number could end with a decimal 0.5.
So, for example, the numbers could be 5, 6, -8.5, 3.5.
I have this to generate my number (example):
rand.nextInt(20 + 1 + 10) - 10;

Comment: How about you generate an int with twice the range you want, and then divide it by 2?
Answer: You could generate an integer with twice the range you want, and then halve it.
Something like this:
int min = -5;
int max = 15;
double r = min + 0.5 * rand.nextInt(2 * (max - min));

If you want max included in the random range, then:
double r = min + 0.5 * rand.nextInt(2 * (max + 1 - min));

Answer: Math.round((min + (rand.nextDouble() * Math.abs(max - min))) / 0.5) * 0.5;
should do the trick by creating a correct value in range [min, max] (including both min and max as possible values!)


Como corrigir erro no modelo auto.arima usando Séries Temporais no R?

Question: Meu objetivo é fazer uma previsão usando Séries Temporais e para isso preciso criar um modelo usando o auto.arima, mas depois de diversas tentativas é exibido a seguinte mensagem de erro:
Error in auto.arima(treino, seasonal = F) : No suitable ARIMA model found
In addition: Warning message:
The chosen unit root test encountered an error when testing for the first difference.
From -(): non-numeric argument to binary operator
0 differences will be used. Consider using a different unit root test.

Para ajudar a entender o que está acontecendo vou deixar aqui o deput dos meus dados.
dput(head(dados, 50))
structure(c("2016-01-01", "2016-02-01", "2016-03-01", "2016-04-01",
            "2016-05-01", "2016-06-01", "2016-07-01", "2016-08-01", "2016-09-01",
            "2016-10-01", "2016-11-01", "2016-12-01", "2017-01-01", "2017-02-01",
            "2017-03-01", "2017-04-01", "2017-05-01", "2017-06-01", "2017-07-01",
            "2017-08-01", "2017-09-01", "2017-10-01", "2017-11-01", "2017-12-01",
            "2018-01-01", "2018-02-01", "2018-03-01", "2018-04-01", "2018-05-01",
            "2018-06-01", "2018-07-01", "2018-08-01", "2018-09-01", "2018-10-01",
            "2018-11-01", "2018-12-01", "2019-01-01", "2019-02-01", "2019-03-01",
            "2019-04-01", "2019-05-01", "2019-06-01", "2019-07-01", "2016-01",
            "2016-02", "2016-03", "2016-04", "2016-05", "2016-06", "2016-07",
            "2016-08", "2016-09", "2016-10", "2016-11", "2016-12", "2017-01",
            "2017-02", "2017-03", "2017-04", "2017-05", "2017-06", "2017-07",
            "2017-08", "2017-09", "2017-10", "2017-11", "2017-12", "2018-01",
            "2018-02", "2018-03", "2018-04", "2018-05", "2018-06", "2018-07",
            "2018-08", "2018-09", "2018-10", "2018-11", "2018-12", "2019-01",
            "2019-02", "2019-03", "2019-04", "2019-05", "2019-06", "2019-07",
            "2016", "2016", "2016", "2016", "2016", "2016", "2016", "2016",
            "2016", "2016", "2016", "2016", "2017", "2017", "2017", "2017",
            "2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017",
            "2018", "2018", "2018", "2018", "2018", "2018", "2018", "2018",
            "2018", "2018", "2018", "2018", "2019", "2019", "2019", "2019",
            "2019", "2019", "2019", " 1", " 2", " 3", " 4", " 5", " 6", " 7",
            " 8", " 9", "10", "11", "12", " 1", " 2", " 3", " 4", " 5", " 6",
            " 7", " 8", " 9", "10", "11", "12", " 1", " 2", " 3", " 4", " 5",
            " 6", " 7", " 8", " 9", "10", "11", "12", " 1", " 2", " 3", " 4",
            " 5", " 6", " 7", "65", "63", "60", "59", "59", "58", "56", "56",
            "57", "58", "58", "59", "59", "57", "57", "58", "60", "59", "58",
            "61", "61", "64", "62", "62", "63", "63", "63", "62", "61", "62",
            "62", "60", "61", "62", "62", "62", "67", "65", "66", "69", "69",
            "69", "69", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5",
            "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5",
            "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5", "5",
            "5", "5", "5", "5", "5", "5", "5", "70", "68", "65", "65", "64",
            "63", "61", "61", "63", "63", "63", "64", "64", "61", "62", "64",
            "67", "64", "63", "65", "64", "67", "67", "69", "71", "69", "69",
            "70", "67", "70", "68", "65", "68", "68", "64", "66", "73", "70",
            "71", "75", "75", "74", "73", "8801", "8284", "8663", "8426",
            "8757", "7807", "7909", "8085", "7342", "7766", "6917", "6524",
            "6712", "5494", "6667", "5841", "6800", "5665", "6181", "6003",
            "5448", "6149", "5955", "6100", "6107", "5267", "6024", "5742",
            "5843", "5355", "5528", "5063", "4957", "5101", "4605", "4576",
            "4887", "4496", "5400", "5867", "6147", "5620", "5301", "10162.76",
            "10271.75", "10989.96", "10531.39", "11106.39", " 9847.93", "10067.73",
            "10243.22", " 9073.81", " 9515.86", " 8374.93", " 8038.93", " 7971.49",
            " 6494.01", " 8086.93", " 7011.61", " 8877.80", " 7118.37", " 7919.78",
            " 7596.31", " 6827.23", " 7590.32", " 7301.27", " 7401.93", " 7639.75",
            " 6677.50", " 7947.16", " 7399.59", " 7678.65", " 6989.26", " 7408.08",
            " 6696.87", " 6587.59", " 6674.26", " 5825.55", " 5889.98", " 6497.34",
            " 6080.41", " 7512.29", " 7962.22", " 8413.40", " 7153.09", " 7460.55",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0",
            "0", "0", "0", "0", "2551.90", "2572.25", "2743.67", "2631.71",
            "2778.78", "2457.02", "2519.70", "2556.61", "2259.24", "2377.52",
            "2106.13", "2019.27", "1990.19", "1627.00", "2037.52", "1762.58",
            "2209.05", "1773.60", "1975.03", "2474.83", "2515.84", "2796.33",
            "2683.44", "2729.78", "2815.84", "2461.95", "2927.25", "2720.48",
            "2827.54", "2561.22", "2706.59", "2480.40", "2436.47", "2475.69",
            "2162.47", "2289.03", "2530.65", "2216.30", "2763.20", "2952.07",
            "3078.76", "2656.94", "2770.48", "10162.76", "10271.75", "10989.96",
            "10531.39", "11106.39", " 9847.93", "10067.73", "10243.22", " 9073.81",
            " 9515.86", " 8374.93", " 8038.93", " 7971.49", " 6494.01", " 8086.93",
            " 7011.61", " 8877.80", " 7118.37", " 7919.78", " 7596.31", " 6827.23",
            " 7590.32", " 7301.27", " 7401.93", " 7639.75", " 6677.50", " 7947.16",
            " 7399.59", " 7678.65", " 6989.26", " 7408.08", " 6696.87", " 6587.59",
            " 6674.26", " 5825.55", " 5889.98", " 6497.34", " 6080.41", " 7512.29",
            " 7962.22", " 8413.40", " 7153.09", " 7460.55", "7610.86", "7699.50",
            "8246.29", "7899.68", "8327.61", "7390.91", "7548.03", "7686.61",
            "6814.57", "7138.34", "6268.80", "6019.66", "5981.30", "4867.01",
            "6049.41", "5249.03", "6668.75", "5344.77", "5944.75", "5121.48",
            "4311.39", "4793.99", "4617.83", "4672.15", "4823.91", "4215.55",
            "5019.91", "4679.11", "4851.11", "4428.04", "4701.49", "4216.47",
            "4151.12", "4198.57", "3663.08", "3600.95", "3966.69", "3864.11",
            "4749.09", "5010.15", "5334.64", "4496.15", "4690.07", "144.31",
            "154.95", "158.53", "156.16", "158.48", "157.65", "159.09", "158.34",
            "154.42", "153.09", "151.31", "154.02", "148.43", "147.72", "151.63",
            "150.08", "163.18", "157.03", "160.16", "158.15", "156.58", "154.22",
            "153.19", "151.64", "156.35", "158.48", "164.98", "161.17", "164.40",
            "163.27", "167.59", "165.32", "166.08", "163.55", "158.14", "160.93",
            "166.23", "169.05", "173.95", "169.72", "171.14", "159.12", "175.97",
            "1270083.5", "1283577.5", "1373321.1", "1315784.8", "1387838.9",
            "1230737.3", "1258276.1", "1280181.6", "1133781.8", "1188912.1",
            "1046583.8", "1004802.2", " 996245.0", " 811598.4", "1010886.1",
            " 876616.5", "1109601.4", " 889594.1", " 989943.9", " 949354.6",
            " 853027.0", " 948310.1", " 912227.5", " 925007.2", " 954813.4",
            " 834704.3", " 993865.2", " 925454.2", " 960578.5", " 874308.5",
            " 926427.2", " 837038.2", " 823264.2", " 834267.9", " 728220.8",
            " 736436.8", " 812370.7", " 760062.2", " 939356.5", " 995718.7",
            "1051979.5", " 894250.4", " 932838.4"), .Dim = c(43L, 15L), .Dimnames = list(
              NULL, c("DATA", "DATA2", "ANO", "MES", "QTDE_LOJA", "ID_ESTRELAS",
                      "QTDE_ID_ENDERECO", "QTDE_TRANSACAO", "QTDE_VL_COMISSAO",
                      "QTDE_VL_TAXA", "QTDE_VL_REEMBOLSO", "Receita_RPC", "Receita_Liquida",
                      "Ticket_Medio", "VL_TRANSACIONADO")))

Seguindo passo a passo do que eu fiz, comecei transformando meus dados em uma matriz e depois transformei essa matriz em uma série temporal.
dados = as.matrix(dados)

VL_TR_TS = ts(dados[,c("VL_TRANSACIONADO")], start = c(2016,1), end = c(2019,7), frequency = 12)

Depois criei minha base de treino, teste e o meu modelo usando o auto.arima.
treino = window(VL_TR_TS, start=c(2016,1), end=c(2019,2))

teste = window(VL_TR_TS, start=c(2019,3), end=c(2019,7))

modelo_1 = auto.arima(treino, seasonal = F)

Mas quando eu executo o script do modelo, exibe a mensagem de erro mencionada acima. No campo seasonal deixei como FALSE, por que se tratava de um outro erro que não indica sazonalidade e passei minha base de 2 para 3 anos por que vi em alguns fóruns que para a base amostral funcionar no auto.arima teria que ser maior que 2 anos, mas mesmo assim a mensagem de erro continua.
Que erro eu estou cometendo? O que devo fazer para corrigir esse erro no modelo auto.arima?
Answer: Seus dados estão no formato character e não como numeric. Vou postar solucionando logo pelas informações que você passou.
Você também pode corrigir isso na importação, vendo os parâmetros que você usou. Se fizer isso recomendo não transformar em matriz, é um passo que você não precisa e se houverem formatos diferentes ela vai forçar tudo a ser character porque matriz não pode ter mais de um formato, diferente de um data.frame.
VL_TR_TS <- as.numeric(dados[,c("VL_TRANSACIONADO")])
VL_TR_TS = ts(VL_TR_TS, start = c(2016,1), end = c(2019,7), frequency = 12)

treino = window(VL_TR_TS, start=c(2016,1), end=c(2019,2))

teste = window(VL_TR_TS, start=c(2019,3), end=c(2019,7))

modelo_1 = auto.arima(treino, seasonal = F)

Comment: obrigado pela resposta, vou testar.


PHP - Where do i use a freebase API key?

Question: I am confused by the getting started docs for Freebase, where would I use my API key in this example:
<!DOCTYPE html>

<?php
include('.freebase-api-key');
$service_url = 'https://www.googleapis.com/freebase/v1/topic';
$topic_id = '/en/bob_dylan';
$params = array('key'=>$freebase_api_key);
$url = $service_url . $topic_id . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$topic = json_decode(curl_exec($ch), true);
curl_close($ch);
echo $topic['property']['/type/object/name']['values'][0]['value'];
?>

If I create this PHP file on my server, does the key go in this file? In the url?
Comment: What is it that you want to do or what is it that is not working how you would like it to?
Comment: This is an example from this page: https://developers.google.com/freebase/v1/topic-overview and it is supposed to "retrieve a Freebase topic and display the topic name"
Comment: if my api key was blahblahblah and I put the php page at example.com/freebase.php, I tried creating the url http: http://example.com/freebase.php?key=blahblahblah but I got nothin'
Comment: The API is at `https://www.googleapis.com/freebase/v1/topic` so you would need to use `https://www.googleapis.com/freebase/v1/topic?key=blahblahblah`.
Answer: Seems like your key should be $freebase_api_key. So just assign it the key value you have above the params line:
$freebase_api_key = 'blahblahblah';

The script will make an auto call for you and echo (some) output.


How to temporarily open a port in ufw for a specific IP address?

Question: I use ufw (Uncomplicated Firewall) on my web server.  Right now I have it set up to allow SSH to the world and fail2ban to prevent massive sign in attempts.  The web server has ports 80 and 443 open.
What I would like to do is close SSH access until I need it and then only make it available to my current public IP address that changes periodically.  I am thinking of a PHP script over HTTPS that verifies my access and then puts the request into a database.  Then a cron job runs a script that reads the database and runs ufw to open the SSH port for just my IP address.  After 30 minutes, the rule would be removed and SSH would become inaccessible again.  I also want to allow multiple IPs to have temporary access as well and I eventually want to expand to other ports beyond SSH.
What ufw commands should my aforementioned automated scripts run to temporarily add and remove SSH port access for individual IP addresses?
Comment: Before I write an answer to my own question, I think I can use "sudo ufw allow from IP.AD.DR.ESS to any port 22" to add and then "sudo ufw delete allow from IP.AD.DR.ESS to any port 22" to remove.  And then remove the general 'allow' rules after I get everything connected up and verified.  Does that sound about right?
Answer: In my opinion a better solution would be to use port knocking, basically you would have "knock" a series of random ports that would then trigger an action on the server, the action would be to allow your IP address to SSH in. You can even setup a timeout so after a while the port would be closed.
For port knocking you could use knockd. You need a knock client too on the other side of course. A knockd config would look like this:
<code>[options]
   logfile = /var/log/knockd.log

[SSH]
  sequence    = 7000,8000,9000
  seq_timeout = 5
  start_command = ufw allow from %IP% to any port 22
  tcpflags    = syn
  cmd_timeout   = 10
  stop_command  = ufw delete allow from %IP% to any port 22
</code>


Erro: Cannot find symbol getRootElement

Question: Estou tentando ler um arquivo .xml usando o código abaixo
  public static String lerArquivoXML(String string){
        SAXBuilder builder = new SAXBuilder();
    File xmlFile = new File("c:\\teste.xml");

    try {

            Document document = (Document) builder.build(xmlFile);
            Element rootNode = document.getRootElement();
            List list = rootNode.getChildren("staff");
        for (int i = 0; i < list.size(); i++) {
           Element node = (Element) list.get(i);
           System.out.println("First Name : " + node.getChildText("firstname"));
           System.out.println("Last Name : " + node.getChildText("lastname"));
           System.out.println("Nick Name : " + node.getChildText("nickname"));
           System.out.println("Salary : " + node.getChildText("salary"));
        }
      } catch (IOException io) {
        System.out.println(io.getMessage());
      } catch (JDOMException jdomex) {
        System.out.println(jdomex.getMessage());
      }
        return null;
    }

Porém, tenho um retorno de erro na linha 8(Element rootNode = document.getRootElement();) conforme o título da pergunta. Os imports estão Ok
xml usado
  <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:apis="http://schemas.datacontract.org/2004/07/Integracao.Modelo.Chamada">
           <soapenv:Body>
            <tem:CancelaSP>

               <tem:token>386922849949</tem:token>

               <tem:cancelaSPIntegracao>

                  <apis:AnoSP>2016</apis:AnoSP>

                  <apis:NumeroSP>5656</apis:NumeroSP>
               </tem:cancelaSPIntegracao>
            </tem:CancelaSP>
         </soapenv:Body>
      </soapenv:Envelope>

Comment: Coloque qual é linha 8 na sua pergunta.
Comment: @Taisbevalle editado
Answer: Como você não explicou exatamente o que está acontecendo com o código, eu fiz a mesma abordagem que você, mas utilizei métodos padrões do JDK, não utilizei SAX. E esta abordagem me pareceu mais simples. Sinta-se a vontade para dizer que não é o que você quer, que irei refazer utilizando SAX.

teste.xml

<?xml version="1.0"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:apis="http://schemas.datacontract.org/2004/07/Integracao.Modelo.Chamada">
           <soapenv:Body>
            <tem:CancelaSP>

               <tem:token>386922849949</tem:token>

               <tem:cancelaSPIntegracao>

                  <apis:AnoSP>2016</apis:AnoSP>

                  <apis:NumeroSP>5656</apis:NumeroSP>
               </tem:cancelaSPIntegracao>
            </tem:CancelaSP>
         </soapenv:Body>
</soapenv:Envelope>

Application

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class JavaApplication2 {

    public static void main(String[] args) {
        try {

            File fXmlFile = new File("/res/teste.xml"); // C:/.../teste.xml

            DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dbFactory.newDocumentBuilder();
            Document doc = builder.parse(fXmlFile);

            //doc.getDocumentElement().normalize();

            NodeList nodeList = doc.getElementsByTagName("soapenv:Envelope");
            for (int i = 0; i < nodeList.getLength(); i++) {
                Node mNode = nodeList.item(i);

                if (mNode.getNodeType() == Node.ELEMENT_NODE) {

                    Element mElement = (Element) mNode;

                    System.out.println("AnoSP: " + mElement.getElementsByTagName("apis:AnoSP").item(0).getTextContent());
                    System.out.println("NumeroSP: " + mElement.getElementsByTagName("apis:NumeroSP").item(0).getTextContent());

                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Output

AnoSP: 2016
NumeroSP: 5656
CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

O código acima faz com que você possa pegar o valor de qualquer Tag que está dentro da tag: soapenv:Envelope.
Comment: Resolvido. Fiz um debug e por algum motivo não estava entrando no loop. Recriei o código e funcionou.
Comment: Com seu código, o erro vai para o getElementsByTagName
Comment: Como você está fazendo? Com o código que eu te mandei? Coloca no pastebin.
Comment: Usei exatamente sua função, sem alterar nada. Apenas corrigi as importações
Comment: Estranho. Alterou a tag `modelo` para a tag do seu xml?
Comment: Coloca o xml que tu tá usando na pergunta, tentarei fazer algo baseado nele.
Comment: Vou editar a pergunta com o exemplo do meu xml
Comment: Fiz o código com o exemplo do seu XML.
Comment: O erro permaneceu. Quais os imports a fazer? veja http://imgur.com/a/PLhNK
Comment: Adicionei as importações, não esqueça de criar uma pasta no `C://` como por exemplo `C:/teste` e colocar o arquivo .xml lá, ou então coloque no projeto e muda a string do caminho
Comment: Com as importações o erro foi corrigido, apesar que a função não está retornando nada
Comment: Olha lá embaixo `return null`. Faz uma string pra retornar o resultado, algo como `String str;` ... dentro do loop: `str = mElement.getElementsByTagName("apis:AnoSP").item(0).getTextContent();`
Comment: nao retorna nada pq sua funcao retorna null
Comment: Apenas na imagem. Eu troquei o tipo de retorno, perdão rs
Comment: O systemOutprint n exibe nada, entende?
Comment: Entendo sim. Estranho. Como tu tá chamando o método?

Erro: Cannot find symbol getRootElement


Drupal 8 Page Cache

Question: I am using dynamic tokens in page title, which is always being cached. I want to stop that.
I have try by disabling page cache using
function hook_preprocess_page(&$vars) {
  $vars['#cache']['max-age'] = 0;
  \Drupal::service("page_cache_kill_switch")->trigger();
}

But they didn't help me, Is there a way so i can only disable or refresh page title cache of a specific page.
My title looks like " lorem ipsum [mydynamictoken:subtoken]  "
Answer: This code works, but you need to place it in the title block.
I wouldn't use the page cache kill switch though, uninstall the module Internal Page Cache instead and then the dynamic page cache can still cache pages where  uncacheable blocks are placeholdered.
Answer: Disable cache for a custom page from route declaration.
If you want to disable cache for a custom controller (Custom module), You have no_cache option (YOUR_MODULE.routing.yml).
Example :
File : mymodule.routing.yml
mymodule.myroute:
  path: '/mymodule/mypage'
  defaults:
    _controller: '\Drupal\mymodule\Controller\Pages::mypage'
    _title: 'No cache page'
  requirements:
    _access: 'TRUE'
  options:
    no_cache: 'TRUE'

Drupal 8 Page Cache


Verify that the map $h: \mathbb{Z}_{18} \rightarrow \mathbb{Z}_3$, given by $h(x)=2x$, is a group homomorphism and find its kernel.

Question: Verify that the map $h: \mathbb{Z}_{18} \rightarrow \mathbb{Z}_3$, given by $h(x)=2x$, is a group homomorphism and find its kernel.
In order to verify it is a group homomorphism let $x,y \in \mathbb{Z}_{18}$ then I want to show that $h(xy)=h(x)h(y)$
$h(xy)=2xy$
Yet notice that
$h(x)h(y)=(2x)(2y)=xy$
I'm not sure how to show this group homomorphism is operation preserving.
The kernel would be all $x \in \mathbb{Z}_{18}$ such that $h(x)=e$ so the set $\left\{2,5,8 \right\}$ would be the kernel of this homomorphism.
Comment: This doesn't even make sense: $h$ isn't a function from $\mathbb{Z}_{18}$ to $\mathbb{Z}_3$ as you've written it....
Comment: It might have been a typo I'll just ignore it and ask my supplemental instructor about it
Answer: Here the group operation is addition and not multiplication. $\Bbb{Z}_18$ and $\Bbb{Z}_3$ are additive groups, not multiplicative.
If you want to show that $h:G\rightarrow G'$ is a homomorphism then you need to prove $h(x\circ y)=h(x)\cdot h(y)$ (where $\circ$ is the operation for $G$ and $\cdot$ is the operation of $G'$)
$\Bbb{Z}_{18}$ is a group under the operation of addition mod $18$ and $\Bbb{Z}_3$ is a group under the operation of addition mod 3.


How to calculate conditional variance?

Question: The distribution of values of the retirement package offered by a company to new employees is modeled by the probability density function:
$$
f(x) = \begin{cases}
  \frac 1 5 e^{-\frac 1 5 (x-5)}, &x>5  \\
  0,                              &{\rm otherwise.}
\end{cases}
$$
Calculate the variance of the retirement package value for a new employee, given that the value is at least $10$.
Part of Solution:
$$
f(x) = \frac{0.2e^{-0.2(y-5)}}{\int_{10}^\infty 0.2e^{-0.2(y-5)}dx} = \frac{0.2e^{-0.2(y-5)}}{-e^{-0.2(y-5)}|_{10}^\infty} = \frac{0.2e^{-0.2(y-5)}}{e^{-0.2(5)}} = 0.2e^{-0.2(y-10)},\\ y>10.
$$
Then note that $Y – 10$ has an exponential distraction with mean $5$. Subtracting a constant does not change the variance, so the variance of $Y$ is also $25$.
I don't know what formula they are using to get $f(y)$ in this case. Can someone tell me what formula it is?
Comment: This is a conditional distribution. Actuarial Exams?
Answer: Hint: Suppose $X$, the retirement package payment, has density function $f(x)$ given above.
Then, given that the value is at least 10, the new PDF would be
$$f_{X \mid X > 10}(x)=\dfrac{f(x)}{\mathbb{P}(X > 10)}\text{.}$$
You can think of this as a consequence of the conditional probability formula:
$$\mathbb{P}(A \mid B)=\dfrac{\mathbb{P}(A \cap B)}{\mathbb{P}(B)}\text{.}$$
Answer: This is a conditional density, the density of $X$ conditional on the event that $X>10$: start with
$$\mathbb{P}(X\in B\,,\ X>10)=\int_{B\cap (10,\infty)} 0.2 e^{-0.2(x-5)}\text{d}x$$
and$$\mathbb{P}(X>10)=\int_{10}^\infty 0.2 e^{-0.2(x-5)}\text{d}x$$

How to calculate conditional variance?


SQL LOADER CONTROL FILE

Question: I have this loader control file.
LOAD DATA
REPLACE
INTO TABLE TEST
WHEN TEST_CD != 'A' AND TEST_CD = 'B' AND TEST_TYPE_CD = 15

Currently its loading data when TEST_CD = 'B' AND TEST_TYPE_CD = 15 but now I want to modify it so that when TEST_CD = 'B' as well as test_type_cd = 15 too.. I dont want to load all Test_type_cd when its 15.. i want to load only when it satisfies both condition.. Just keeping the braces around it is going to work.. Plz some one let me know how can I modify this..
I am thinking everyone is confused with what I need.. I want first condition to satisfy as well as 2nd and 3rd condition as 1 condition not to act seperately.. For example if test_cd is not equal A than load the data but 2nd and 3rd condition should act as one piece..when test_cd = B and test_type_cd is 15 than load the data.. i dont want test_type_cd to apply for any other test_cd other than B.. I have 5 of those test_cd A B C D E.. i want only B to apply test_type_cd = 15..
Comment: Your code already makes makes sure both conditions are satisfied.
Comment: You mean you want to load data either TEST_CD = 'B' or TEST_TYPE_CD =5 or both?
Comment: i want to load data when test_cd = 'B' and for that row if test_type_cdis 15 too.. when it satisfy both conditions.. right now it doesnt care when test_cd is b test type cd is 15 or not.. if it satisfies one its loading
Comment: Also, having `TEST_CD != 'A'` is unnecessary because of `TEST_CD = 'B'`.
Comment: Can you double check that something else isn't broken?  Because your syntax is correct.  You're already using an `AND` operator not an `OR` operator so it's impossible for it to behave the way you have described.
Comment: wants to apply test_type_cd = 15 only to test_cd B.. i dont want to apply it to other test_cd C D E that i have
Comment: OR is not an option in SQL loader
Comment: Jack, thanks for the clarification.  +1 for niktrs solution below.
Answer: Try
LOAD DATA
REPLACE
INTO TABLE TEST
WHEN TEST_CD = 'B' AND TEST_TYPE_CD = 15 -- load everything that is b and 15
INTO TABLE TEST
WHEN TEST_CD != 'A' AND TEST_CD != B -- load everything that is not a and not b (because it is loaded above)

Answer: So, you want it to load in when EITHER condition is true, not necessarily BOTH conditions?
WHEN TEST_CD != 'A' AND (TEST_CD = 'B' OR TEST_TYPE_CD = 15)

may satisfy the fractured English of your initial question.

SQL LOADER CONTROL FILE


How to access data returned from props

Question: I new to nextjs and react. I am using the nextjs to fetch data from api and display it in view. this is my code.
const Index = props => (
  <Layout>

Events

      {props.eventList.map(({ venue }) => (

          {venue.name}

      ))}

  </Layout>
);

Index.getInitialProps = async function() {
  const res = await fetch("api link here");
  let data = await res.json();
  console.log(`Show data fetched. Count: ${data.events.length}`);
  return {
    eventList: data.events
  };
};

Now my api return data like this
[
    {
      "id": 4303920,
      "name": "Test Event",
      "venue": {
        "id": 1610,
        "name": "Eiffel Tower Viewing Deck at Paris Las Vegas",
      }
    },
    {
      "id": 4323,
      "name": "Test Event 2",
      "venue": {
        "id": 1610,
        "name": "Eiffel Tower Viewing Deck at Paris Las Vegas",
      }
    }
]

I am able to access the venue details by props.eventList.map function but i am not able to access the id and name.
Comment: What happens when you try your code? Is there an error? In the map if you console log "venue" what is in it?
Comment: i can access the venue fine. but when i am not able to access the name ( Test Event ). it says name is not defined.
Answer: In your map instead of ({venue}) => just do (item) => your issue is you are getting each element and only extracting venue from it instead of the entire element. Once you have item you can say item.id, item.venue etc.
Comment: thanks for your help. it worked. it was so simple and i spend an hour on this.
Comment: If this answer helped you to solve your problem, you should upvote it or mark it as solved in order to really thank the person who helped you.
Answer: You should not put {venue} inside your map function but pass the event like this (event) then you will have even.name and event.is and you will have event.venue.id and event.venue.name

How to access data returned from props


What exactly is the "cross modulation" on Roland Jupiter and JX analog synthesizers?

Question: Roland's later analog synthesizers have a setting for cross-modulation between the two oscillators. I'm trying to find out what the exact technical nature of this effect is. Is it phase modulation, linear frequency modulation, exponential frequency modulation, amplitude/ring modulation, or something else entirely? And does it go one way, or does it affect both oscillators, as is suggested by the term "cross-modulation"?
On the Jupiter-6, there are two faders in the oscillator-1 section to set the cross-modulation level manually and to have it influenced by envelope-1.
On the Jupiter-8, there is one fader in the oscillator-1 section to set the cross-modulation level manually, and it is indicated on the panel as a signal coming from oscillator-2.
On the JX-8P and JX-10, there is a switch in the oscillator-2 section to set the cross-modulation level from 0 to 3.
(On the JX-3P, there is a switch in the oscillator-2 section with settings "off", "sync" and "metal", but nothing to set the cross-modulation level. It looks as if the cross-modulation on the JX-3P is very different from the implementation on other models.)

UPDATE
A few (vague) sources on internet forums suggest that the cross-modulation is exponential frequency modulation of oscillator-1 by oscillator-2.
I'd be interested to have this confirmed by someone who has access to a Jupiter, and ideally I'd like to know by what interval the pitch of oscillator-1 goes up and down when oscillator-2 is set to a square wave and low-fequency mode, and the cross-modulation level is set to maximum.

Further Googling suggests that on the JX-8P and the JX-10, the four settings are 0: off, 1: oscillator sync (oscillator 2 synced to oscillator 1), 2: cross modulation (apparently oscillator 1 modulating the frequency of oscillator 2) and 3: oscillator sync combined with cross modulation.
So the cross modulation on the JX synthesizers seems to go in the same direction as the oscillator sync (oscillator 1 controls oscillator 2), unlike the Jupiter-8. The Jupiter-6 could do oscillator sync in both directions, so there you had the choice of both options.
Comment: Back in the day on Synth Secrets, https://web.archive.org/web/20160404062919/http://www.soundonsound.com/sos/may00/articles/synth.htm, Reid claimed that "cross modulation" always refers to frequency modulation. I don't know the difference between linear and exponential FM, and don't know which osc is modulator and which is carrier however.
Comment: @PatMuchmore Thanks for that link. I have found a few other mentions on forums suggesting it is exponential FM going from oscillator-2 to oscillator-1, and that it changes the pitch of oscillator-1 (which makes sense). Maybe the "cross" simply means from one oscillator to the other, and doesn't imply that the modulation works both ways.
Answer: One would think that the 'metal' choice on the JX3P refers to Ring Modulation (RM). The reason for my thinking so is that the option was often used for bell like sounds, which is also typically associated with RM. I don't know this for a fact, of course, but it seems to reason.
Just the name brings back memories of making some of the coolest bells and S&H sounds, and I am very much partial to metallic timbres. Also, I recall it had Frequency Modulation (FM) which sort of infers a separation between FM and CM (in terms of Roland's use). Sadly I do not have the synthesizer anymore.
This does not answer your question anywhere near 'exactly', but I think you would need someone from Roland in order to find that kind of answer.
Answer: TL;DR:
JP8 and JP6 crossmod is exponential FM of DCO 1 by DCO 2, JX-8P is amplitude modulation (ring modulation) of DCO 2 by DCO 1 (plus sync if wanted).
Details:
All of this should be fairly easy to figure out from the service manuals for the various synths.
Right now I'm looking at the JP8 service manual. Here, the output from VCO 2 - tapped after the waveform selector - is fed back to the exponential (v/oct) input of VCO 1. There is nothing going into the reference current input of VCO 1 (the circuit around op amp 1A on page 12 of the service manual), so the JP 8 has no linear FM.
The signal from VCO 2 goes through IC18A, which is a BA662 OTA, this acts as a voltage controlled amplifier/attenuator, and this is what is controlled by the panel potentiometer.
The same is the case for the JP-6, although here the signal is fed through a CEM3360 VCA. It is still sent back to the exponential input of VCO 2. Nothing is fed into pin 13 of the CEM3340 VCO so the JP-6 has no linear FM either.
The JX-8P is completely different. It doesn't have VCOs, it has DCOs, meaning the frequency is digitally controlled. It does NOT let the output of DCO 2 control the frequency of DCO 1, neither exponentially nor linearly. Instead, when crossmod is enabled (pos 1 or 2 on the PG-800 switch), the output of DCO 1 controls the amplitude (volume) of DCO 2, which I guess means that the output of DCO 2 is now DCO 1 times DCO 2, or exactly what is described as ring modulation in figure 2 here (given that it follows the gain requirements stated): https://www.keyboardmag.com/gear/on-synthesizers-amplitude-and-ring-modulation
PS: This means that, unlike what OP says about crossmod on the JX-8P, DCO 1 does NOT modulate the FREQUENCY of DCO 2, it modulates the AMPLITUDE.
In the circuit diagram the control for this part of the X-mod is labeled 'Metal', so it is very possible that this has the same effect as 'Metal' on the JX-3p, which is also described as a ring modulator type of sound. Interestingly enough, I cannot find any similar circuit on the JX-3p.
The JX-8P (and JX-3P) does also have a sync input on DCO 1 going to Q18, which is the transistor that resets the sawtooth of DCO 1 (i.e. sets the frequency). Sync comes from the same input that resets DCO 2, so whenever DCO 2 resets, so does DCO 1 (which means this is just normal hard sync I guess).
I do have a JP-8 and a JX-8P btw, do you still want something confirmed two years later? :-D
Comment: I'd still be interested to know by how much the pitch of VCO-1 goes up and down if you set VCO-2 to a square wave and the cross modulation to its maximum depth on the Jupiter-8, and whether it's different with VCO-2 in low frequency mode.
Answer: The characteristic feature of cross modulation is that the two signals have similar frequencies, both in the audio range. That creates quite a different effect from amplitude or frequency modulation driven by a low frequency oscillator (i.e. with a frequency between say 5 Hz and maybe as low as 0.01 Hz) where you can hear the effect of each individual cycles of the LFO, or slow changes in the sound of a drone.)
Probably the nearest equivalent to cross modulation would be ring modulation as in early analog synths, or "FM synthesis" as marketed by Yamaha in the 1980s, for example in their DX7 synth.
The frequency and amplitude content of the cross-modulated signal doesn't necessarily have any simple relation to the two inputs, and what you hear doesn't necessarily have a simple relation to what you would measure with a frequency spectrum analyser either, since your ears and brain are a highly nonlinear signal processing system! You could describe it as a "there are no rules - just play with it till you get something you like" type of effect!
Comment: It's a fine answer, but it's not really an answer to the question posed.
Comment: Thank you for answering. I'm creating a Roland-inspired virtual instrument, but unfortunately have only Juno synths to compare with, and therefor I'd like to find out the exact details of the cross-modulation implementation: AM or linFM or expFM or phase modulation, using which waveforms, in which direction, at what level, etc...