Convolution of unit impulse with impulse response

Question: I have a question that's been bothering me. If we can convolve any arbitrary input with a system's impulse response to get the system's total response for that input, then if we convolve the impulse response with a unit impulse, won't we just end up with the very impulse response we just convolved with?
I hope my question is clear. Thanks!
Answer: Yes, if we convolve the impulse response with the unit impulse(i.e $\delta (t)$) we do get the impulse response back. The impulse response is the system's response to an impulse. That's why it is called an impulse response. So if we give $\delta (t)$ as input to a linear time invariant system, the output is the impulse response. Infact, convolution of any function with unit impulse is the function itself.
Linear time invariant(LTI) system is necessary because output is the convolution of input and the impulse response only for LTI systems.
Comment: I had a hunch but wasn't completely sure. Thank you!
Answer: Yes.
$$ y(t) = g(t) \star u(t) := \underbrace{\int\limits_{-\infty}^{\infty} g(t-\tau)u(\tau) d\tau}_{\mathcal{I}} = \int\limits_0^{t} g(\tau)\delta(t-\tau) d\tau = g(t),$$
where $\int\limits_{-\infty}^{\infty}(.)$ changes to $\int\limits_0^{t}(.)$ due to causality (input can only affect future outputs) and the convention that $(\forall \tau > t) \: u(\tau) \equiv 0$.
Note:
The integral $\mathcal{I}$ is well-defined since, by integration by parts,
$$
\begin{align}
\int_\limits{-\infty}^{\infty}g(\tau)\delta(t-\tau) d\tau & = \left.-\int_\limits{-\infty}^{\infty} g'(\tau)(-\sigma(t-\tau)) d\tau + g(\tau)\sigma(t-\tau)\right\rvert_{\infty}^{-\infty} \\
& = \int_\limits{-\infty}^{t} g'(\tau) d\tau + \lim_{\tau \rightarrow -\infty} g(\tau)\sigma(t - \tau) - \lim_{\tau \rightarrow \infty} g(\tau)\sigma(t - \tau) \\
& = (g(t) - g(0)) + g(0) \\
& = g(t),
\end{align}
$$
where $\sigma(x)$ is the Heaviside function:
$$ \sigma(x) =
\begin{cases}
1 & \text{if } x \ge 0 \\
0 & \text{otherwise}.
\end{cases}
$$
More generally, according to Kaplan's Advanced Calculus (5E), p.529 (7.122) we have that

$g(x) \star \delta^{(k)} (x-c) = \delta^{(k)}(x-c) \star g(x) = g^{(k)}(x-c)$
Comment: @Pait: I added a note for clarification.
Comment: Is this formally correct? Is the integral well-defined, despite the multiplication of impulses?
Comment: Thank you for posting the math behind it; it's aids in the conceptualization of the solution.


How to find out master product of simple product?

Question: How can I find out, if a simple product is part of a configurable product and then get the master product? I need this for the product listing.
Just found out:
$_product->loadParentProductIds();
$parentIds = $_product->getParentProductIds();

Answer: Let's say that you have your simple product's Product ID.
To get all the parent configurable product IDs of this simple product, use the following code:-
<?php
$_product = Mage::getModel('catalog/product')->load(YOUR_SIMPLE_PRODUCT_ID);
$parentIdArray = $_product->loadParentProductIds()
                 ->getData('parent_product_ids');
if(!empty($parentIdArray)) {
    // currently in the master configurable product
    print_r($parentIdArray); // this prints all the parent product IDs using your simple product.
}
?>

I suppose this should get you going.
Comment: Yeah, that is they way I've used.
Answer: After version 22.214.171.124 the loadParentProductIds() and getParentProductIds() methods are deprecated. Don't ask me why. Personally I kind of liked those methods. So I've reintroduced them to my local Mage classes. This is how:
Copy
app/code/core/Mage/Catalog/Model/Product.php

to
app/code/local/Mage/Catalog/Model/Product.php

and change the loadParentProductIds() method, found around line 1349 to:
public function loadParentProductIds()
{
        return $this->_getResource()->getParentProductIds($this);
}

This piece of code will query its resource for its parent product ids. For this to work we'll need to rewrite the getParentProductIds() method in the resource class.
So copy:
app/code/core/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php

to
app/code/local/Mage/Catalog/Model/Resource/Eav/Mysql4/Product.php

Find the deprecated getParentProductIds() method. Should be somewhere around line 535. Overwrite it with the pre 188.8.131.52 code:
public function getParentProductIds($object){
    $childId = $object->getId();
    $groupedProductsTable = $this->getTable('catalog/product_link');
    $groupedLinkTypeId = Mage_Catalog_Model_Product_Link::LINK_TYPE_GROUPED;
    $configurableProductsTable = $this->getTable('catalog/product_super_link');

    $groupedSelect = $this->_getReadAdapter()->select()
        ->from(array('g'=>$groupedProductsTable), 'g.product_id')
        ->where("g.linked_product_id = ?", $childId)
        ->where("link_type_id = ?", $groupedLinkTypeId);

    $groupedIds = $this->_getReadAdapter()->fetchCol($groupedSelect);

    $configurableSelect = $this->_getReadAdapter()->select()
        ->from(array('c'=>$configurableProductsTable), 'c.parent_id')
        ->where("c.product_id = ?", $childId);

    $configurableIds = $this->_getReadAdapter()->fetchCol($configurableSelect);
    return array_merge($groupedIds, $configurableIds);
}

Now you once again can do this:
$_product->loadParentProductIds()->getData('parent_product_ids');

Hope this helps you out!
Answer: For Magento 1.4.2 and above use the following method instead:
$configurable_product_model = Mage::getModel('catalog/product_type_configurable');
$parentIdArray = $configurable_product_model->getParentIdsByChild($simple_product_id);


Evaluate the integral using the given data

Question:
Let $f:[0,1]\to [0,1]$ be a continuous function such that $x^2 +(f(x))^2\le 1$ for all $x\in [0,1]$ and $\int_0^1 f(x).dx=\frac{\pi}{4}$, then find $\int_{-1/2}^{1/\sqrt 2} \frac{f(x)}{1-x^2}.dx$

The part that's throwing me off the inequality function. I have no idea how to solve such that problems. Can I get a hint?
Answer: It is a badly written question. It says for all $x \in (0,1)$ and does not define $f(x)$ for $x \lt 0$ and then asks to integrate for negative values of $x$. Anyway I assume the given equation is true for all $x \in (-1, 1)$.
$x^2 + (f(x))^2 \leq 1$ for all $x \ $ and $\displaystyle \int_0^1 f(x) \ dx = \frac{\pi}{4}$.
And we need to find $\displaystyle \int_{-1/2}^{1/ \sqrt2} \frac{f(x)}{1-x^2} \ dx$
We know from the equation that $x^2 + (f(x))^2 \leq 1$ is a circle. The inequality ensures that you cover all the points inside the circle, in addition to covering points on the circle because the question is about area.
The next point which show the integral $I = \frac{\pi}{4} \ $ for $0 \leq x \leq 1$ only reiterates that the function is never negative otherwise the area would be $\frac{\pi}{2}$ for $0 \leq x \leq 1$.
So the integral that we need to find simply translates to $\displaystyle \int_{-1/2}^{1/ \sqrt2} \frac{1}{\sqrt{1-x^2}} \ dx$
Answer: Hint :
$$f(x) \leq \sqrt{1-x^2}$$
It means graph of $f(x)$ always lies on or below the unit circle in the first quadrant.
Now what can you conclude from following? $$\int_{0}^{1} f(x) \, dx = \frac{\pi}{4}$$
Think area!
Comment: @AlbusDumbledore good luck for your exam! By the way I did not understand your comment about integrating both sides of the inequality.
Comment: @MathLover oh that integrating we get $\int_0^1 f(x)\le \pi/4$ which means the equalty must occur
Comment: @AlbusDumbledore Integrating we get $\frac{\pi}{4}$ which is area. There is no inequality here. It is a very standard practice to represent a closed curve with inequality when it is about area otherwise we remain on the curve. Similarly for volume in a closed surface otherwise remain on the surface. If you read $f(x) = y$ in the question, it becomes more clear, may be.
Comment: @MathLover i integrated both sides of inequality $f(x)\le \sqrt{1-x^2}$ which gave $\int_0^1f(x)\le \pi/4$ but as $\int_0^1 f(x)=\pi/4$ this means $f(x)=\sqrt{1-x^2}$ for all $x $ in domain
Comment: That is not true. Take $x = 0.1, f(x) = 0.1$. Is this point in the domain or not? Also not clear what is both sides of inequality.
Comment: @MathLover if a function (differntiable) $f(x)\le g(x)$ for all x doesnt that mean $\int_a^b f(x)\le \int_a^b g(x)$
Comment: That is not at all the point that I am making. I am not sure how you infer that from my previous comment. I am asking how you plan to cover all points inside the circle if $x^2 + y^2 = 1$ instead of $\leq 1$? Anyway we can continue in chat some other time or now whatever you prefer. I don't want to distract you. Again good luck for your exam.
Comment: Are we supposed to find $f(x)$ from the integral?
Comment: @Aditya yes you can deduce from the integral that $f(x) =\sqrt{1-x^2}$ but only over [0, 1]. As MathLover points, the problem then shouldn't be asking for integral over negative bounds as function is not defined there. You'll probably have to assume function is defined the same over negative interval also.
Comment: How is $f(x)=\sqrt{1-x^2}$? My problem is that I don't find the integral useful in finding the function. Can you just decide upon just because the areas match?
Comment: @Aditya, it's not only area, the domain and range are also same. Then the inequality $\int f dx \le \int \sqrt{1-x^2}\,  dx$  states, $f(x)$ can either have smaller or equal area with $\sqrt{1-x^2}$ over $[0,1]$. Equality will occur if and only if at every $x$, the height $f(x)$ of  rectangles matches the height $\sqrt{1-x^2}$ of rectangles of Riemann sum.


Does linking from an https site/page to http site triggers a security warning?

Question: I have a secure page, with it's full security certificate in the SSL protocol or https but when using a relative link to a non secure part of my website it forces the https protocol on it and causes all kinds of problems like the CSS styles not loading and header and footer missing. My idea is to make the link absolute, without the https. Will it trigger a security warning when clicked or will it in any way compromise the security of that page or invalidate the certificate?
Answer: No, there isn't a warning for a link to a non-secure part of your website. However, this isn't a good security practice. Once the user goes to a non-secure part, an attacker could use something like sslstrip to keep HTTPS turned off even when they try to go back to a secure part. Instead, you should make your entire site accessible over HTTPS.
Comment: Thank you for your prompt answer! The plan is to convert the site to a full HTTPS one and this would be a temporary solution. Notwithstanding, another question arises, can that "sslstrip" still be tried/implemented even without the link to a non secure part of my website?
Comment: The way sslstrip works, once a user is on an insecure page, sslstrip can keep them insecure even if links, forms, or other things are supposed to send them to a secure page. If they never end up on an insecure page, though, then sslstrip can't do anything.


possible Eigenvector basis

Question: I am learning to form bases with eigenvalues and want to make sure I understand. I was given the matrix $C= \begin{pmatrix}
  6 & -3 & -1 \\
  11 & -6 &  -3 \\
  -10 & 7 & 5
 \end{pmatrix}$. I found an eigenvector $\begin{pmatrix}
  -1 \\
  -2 \\
  1
 \end{pmatrix}$ for $\lambda =1$. I also found eigenvector $\begin{pmatrix}
  1 \\
  1 \\
  1
 \end{pmatrix}$ for $\lambda=2$. Now knowing $\lambda=1$ and $\lambda=2$ are the only eigenvalues of C, is it possible to get a basis of $\mathbb{R}^3$ consisting of eigenvectors of C?
I don't think it's possible since for both eigenvectors I was given one degree of freedom, thus there was "only one" vector (quotes because I understand there isn't only one). Am I understanding this correctly or is it possible?
Comment: Since the problem seems to be solved, you might want to [mark one of the answers as accepted](https://math.stackexchange.com/help/someone-answers) by clicking the check mark (✓) icon next to the answer on the left. Doing so will mark the question as answered, and will also award both you and the author of the answer a few reputation points.
Answer: No it is not possible to form a basis of $\Bbb R^3$, since you only have $2$ vectors, and $3$ are required to do this, since this is a $3$-dimensional space. So yes you're completely correct.
Answer: You are correct: it is not always possible to find a basis of eigenvectors. As you have discovered, the matrix only has two eigenvectors.
Since $2$ is an eigenvalue of multiplicity $2$, you may well wonder why there is only one eigenvector associated with it. The answer is that there is a vector $v$ so that $(C-2I)v \neq 0$, but $(C-2I)^2v=0$; this is called a generalised eigenvector. If we include generalised eigenvectors, more generally defined as vectors for which $(C-\lambda I)^n v = 0$ for any $n>0$, then we can form a basis; this is the idea behind the Jordan Normal Form.

possible Eigenvector basis


How to build an acquisition models?

Question: I have historical transaction data for a B2B business. I want to prepare acquisition models where the model will predict the potential buyers who haven't purchased from the business yet.
In addition to the transaction data, I have customer data where I have the details about the different businesses in the region (Their Sales, Profitability, Size, Location, and Industry) from an external source.
How do I translate this business problem into a data science problem?
What should be my approach in building these models?
Are there any resources available for similar problems?
I really appreciate any help you can provide.
Answer: You have a binary classification problem. In other words you want a model to decide if a user will be customer or no.
One way is to create two sets of rows. One with users that became customers -1 and a second with users that didn't - 0.
This column with values 0 or 1 is the Y, aka truth label.
You need historical data with the features you think play some role ie how many clicks a user did in a website or his location/age.
These features are what an algorithm will use to adjust its parameters - what we call training. Once you train a model you need to see how good it is.
A simple but effective way for such problem is to use write python program that uses the xgboost or scikit-learn libraries.
There are thousands of tutorials with for similar methods. I hope this gave you some context to search, good luck.

How to build an acquisition models?


Can't convert a code number to a different format in order for it to use within params

Question: When I navigate to this site, input chassis number JTDJC123705048557 right next to Numéro de chassis and hit Consultation button, I get the required result which is displayed at the bottom of that page.
I'm trying to create a script using requests module to mimic the process I've detailed above. The script I've already created can produce the result accordingly only when I hardcode the value of PAGEDATA.
The value of PAGEDATA is the chassis number (decoded or something). The thing is when I use this chassis number JTDJC123705048557 in the inputbox, the value of PAGEDATA within params becomes 5243313432206F6E20436C69636B7E5243313236207E5243313330207E5243313334204A54444A433132333730353034383535377E in dev tools.
This is how I got success (using hardcoded value of pagedata from dev tools):
import re
import requests

link = 'https://www.mobilit.fgov.be/WebdivPub_FR/wmvpstv1_fr.jsp'

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/188.8.131.52 Safari/537.36',
}
params = {
    'SUBSESSIONID': '',
    'DYNAMIC': 'DOREQUEST',
    'NAME': 'CMV_WD_PBL01_CONSULT_STATUS',
    'PSTEPID': '',
    'WINDOWID': '',
    'PAGEDATA': '5243313432206F6E20436C69636B7E5243313236207E5243313330207E5243313334204A54444A433132333730353034383535377E'
}
with requests.Session() as s:
    s.headers.update(headers)
    res = s.get(link)
    session_id = res.url.split("=")[1]
    params['SUBSESSIONID'] = session_id
    params['PSTEPID'] = re.findall(r"pStepId=(.*?);",res.text)[0]
    params['WINDOWID'] = re.findall(r"windowId=(.*?);",res.text)[0]
    resp = s.get(link,params=params)
    print(resp.text)

Question: how can I convert this chassis number JTDJC123705048557 to the value of aforementioned pagedata?
Answer: First to note: the code found on the page is one of the worst I've ever seen before (lot's of global variables, unnecessary calls, generally hand-written spaghetti code).
For the task of computing PAGEDATA I use js2py module with snippet I got from the page Javascript (for pure Python version scroll down):
import js2py

js_hexify = """\
var hexTable= new Array("00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F","10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F","20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F","30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F","40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F","50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F","60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F","70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F","80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F","90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F","A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF","B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF","C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF","D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF","E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF","F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF");
var mB = false;

function hexify(p) {
  var h = new Array(p.length<<1);
  var c = ' ';
  var b = 0;

  for (i = 0; i
 255 ) {
       if ( !mB ) {
          h.push('u');
          mB = true;
       }
       b = c >> 8;
   //    hexStr.push(DecToHex(hiByte));
         h.push(hexTable[b]);
       c = c & 255;
   //    hexStr.push(DecToHex(ch));
         h.push(hexTable[c]);
    } else {
      if ( mB ) {
        h.push('u');
        mB = false;
      }
    //    hexStr.push(DecToHex(ch));
          h.push(hexTable[c]);
    }
  }
  return h.join("")
}"""

context = js2py.EvalJs()
context.execute(js_hexify)

magic_string = "RC142 on Click~RC126 ~RC130 ~RC134 {}~"  # <-- this string is always the same, only the last part changes
id_ = "JTDJC123705048557"

print(context.hexify(magic_string.format(id_)))  # <-- this computes the PAGEDATA parameter

Prints:
5243313432206F6E20436C69636B7E5243313236207E5243313330207E5243313334204A54444A433132333730353034383535377E

Pure Python version:
magic_string = "RC142 on Click~RC126 ~RC130 ~RC134 {}~"
id_ = "JTDJC123705048557"

x = "".join((hex(ord(ch))[2:].upper() for ch in magic_string.format(id_)))

print(x)


Pass string array as parameter in SQL query in C#

Question: In my application written in C# , I am writing a SQL query. Following is the query
SELECT [Resource No_] where [Resource No_] In (@resources)

@resources is user input parameters having one or more that one strings.
My query is failing without showing an error
According to me, query is failing because in @resources parameter following is being passed
"'123,'124','125'"

(there are 2 inverted commas in the beginning and at the end and that is failing my query).
[Resource No_] is of type NVARCHAR in the database.
After Googling, I have found some help on this topic but all are applicable when [Resource No_]  is of type Integer
Comment: Show us how you create this query.
Comment: creating a dynamics string in not possible because I don't know the number of parameters passed by user.
Comment: @Simon Whitehead :: SqlCommand cmd = new SqlCommand (SELECT [Resource No_] where [Resource No_] In (@resources) , conn)
Comment: http://stackoverflow.com/a/337792/2864740
Answer: While I don't agree with the selected answer (or many of the tricky answers) for the "duplicate question", here is an answer to it which shows an approach very similar with my following recommendation.
(I've voted to close this question as a duplicate, because there are such answers, even if buried.)

Only one SQL value can be bound to any given placeholder.
While there ways to send all the data as "one value", I'd recommend creating the placeholders dynamically: it's simple, clean, and will work reliably in most cases.
Consider this:
ICollection<string> resources = GetResources();

if (!resources.Any()) {
    // "[Resource No_] IN ()" doesn't make sense
    throw new Exception("Whoops, have to use different query!");
}

// If there is 1 resource, the result would be "@res0" ..
// If there were 3 resources, the result would be "@res0,@res1,@res2" .. etc
var resourceParams = string.Join(",",
    resources.Select((r, i) => "@res" + i));

// This is NOT vulnerable to classic SQL Injection because resourceParams
// does NOT contain user data; only the parameter names.
// However, a large number of items in resources could result in degenerate
// or "too many parameter" queries so limit guards should be used.
var sql = string.Format("SELECT [Resource No_] where [Resource No_] In ({0})",
    resourceParams);

var cmd = conn.CreateCommand();
cmd.CommandText = sql;

// Assign values to placeholders, using the same naming scheme.
// Parameters prevent SQL Injection (accidental or malicious).
int i = 0;
foreach (var r in resources) {
   cmd.Parameters.AddWithValue("@res" + i, r);
   i++;
}

Comment: This is not the question. Your answer is how to create a new SQL statement; not nice when you have a few thousand entries.
Comment: @fcm I don't think you understand the answer, this is about how you parameterise the query when you have an unknown number of parameters.
Answer: Use a user defined table type to accept your parameter, then a JOIN clause in your select to limit the results set. See http://social.msdn.microsoft.com/Forums/en-US/2f466c93-43cd-436d-8a7c-e458feae71a0/how-to-use-user-defined-table-types
Answer: Do something like
resources.Aggregate(r1, r2 => r1 + "', '" + r2 + "'")

and pass the list in one string.


How to add another field collection instances on Add Form page load programatically

Question: I have one field collection with unlimited values in Commerce Product Add form.
After performing some action, When user redirects to Add Product form, based on some predefined values in session, I want to display User a Field collection items pre-filled.
If I have 5 predefined values then 5 Field-collection items would be displayed to User and by clicking on save that product would be saved with that field collection item values.
By clicking on 'Add another item', User can add more as well. Above field collection items won't be saved until User clicks on Save form button.
I tried below code but it's not adding new items/instances :
<code>function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_product_ui_product_form') {
    if (isset($_SESSION['compatibilityInfo']) && $_SESSION['compatibilityInfo'] != '') {
      $compInfo = $_SESSION['compatibilityInfo'];
      $comp = explode('!c!', $compInfo);
      $cnt = count($comp);

        // Go one level up in the form, to the widgets container.
        $element = drupal_array_get_nested_value($form, array('field_part_details','und'));
        $field_name = $element['#field_name'];
        $langcode = $element['#language'];
        $parents = $element['#field_parents'];
        // Increment the items count.
        $field_state = field_form_get_state($parents, $field_name, $langcode, $form_state);
        $field_state['items_count'] = $cnt;
        field_form_set_state($parents, $field_name, $langcode, $form_state, $field_state);

    }
  }
}
</code>
Answer: I had to do this recently on a product.  What I ended up doing is copying the instance of the field collection and then looping through and creating them.  If your session variable keys are numerical from 0 on then you dont need the $item_count.  In my case it was not so I could not simply use the foreach($value as $key => $val).
<code>$my_loop = array(); // Array of items with your default values
$item_count = 0;
$field_collection_clone = $form['field_my_field_collection']['und'][0]; // Clone the field collection form element

//Loop through and create a new instance of the field collection form
foreach($my_loop as $loop){
 $form['field_my_field_collection']['und'][$item_count] = $field_item_base;
 $form['field_my_field_collection']['und'][$item_count]['field_my_field']['und'][0]['value']['#default_value'] = 'my default value';
$item_count++;
}
</code>
Comment: Your solution is working but by clicking on 'Add another item' button, it removed all other added field collection items except first.
Answer: I resolved it using below code :
<code>$cp = commerce_product_new('product');
foreach($part as $title) {
        $my_collection = entity_create('field_collection_item', array('field_name' => 'field_part_details'));
        $my_collection->setHostEntity('commerce_product', $cp);
        $my_collection->field_year[LANGUAGE_NONE][0]['tid'] = $title->fromYear;
        $my_collection->save();
}
</code>


nodejs Promise.all returns null on some mongoose promises

Question: i am passing array of mongoose promises and for some reason sometimes customerFindPromise return null, and sometimes it return the requested object. am i doing something wrong here
******************** START result0: null result END ********************
 ******************** START result1: { _id: 5a18a637346826574416a588,
doc_fname: 'Bob',
doc_lname: 'Smith',
numOfCases: 1,
__v: 0 } result END ********************
******************** START result2: {"n":1,"ok":1} result END ********************

Code
var customer = {
    doctor_id: 5a18a637346826574416a588,
    cust_fname: 'dfsdf',
    cust_lname: 'sdasd',
    case_type: 'Crowns',
    _id: 5a1cd19438f14164b0087753
}
test(customerCase);
async function test(customerCase) {

    console.log("******************** customerCaseDelete: "+ customerCase._id +" ********************");
    var _id = customerCase._id;
    var doctor_id = customerCase.doctor_id;
    var query = {_id:_id};

    const customerFindPromise = CustomerCases.findById(_id);
    const customerRemovePromise = CustomerCases.remove(query);
    const doctorUpdatePromise = Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true});

    await Promise.all([customerFindPromise,doctorUpdatePromise,customerRemovePromise])
      .then((result) => {
        console.log("******************** START result0: "+ result[0] +" result END ********************");
        console.log("******************** START result1: "+ result[1] +" result END ********************");
        console.log("******************** START result2: "+ result[2] +" result END ********************");
        res.json(result);
      }).catch((err) => {
          console.log("******************** START err: "+ err +" err END ********************");
         throw err;
      });
}

Comment: your code as posted is invalid, specifically the declaration of `var customer`
Comment: Finding and removing an object with the same id at the same time clearly looks like a classic race condition.
Answer: The functions you are running are asynchronous and won't always run in order. Promise.all does not change the execution order of the promises either, it just waits for them all to be resolved.
Sometimes CustomerCases.remove will execute and resolve before CustomerCases.findById so null resolves when the document has been removed first.
Wait for the promises to resolve serially before executing the next query, seeing as you are using async/await it's fairly simple to add:
try{
  let find = await CustomerCases.findById(_id)
  console.log(`find: ${find}`)
  let update = await CustomerCases.remove(query)
  console.log(`update: ${update}`)
  let remove = await Doctors.findOneAndUpdate({_id:doctor_id},{'$inc': {'numOfCases': -1}},{new:true})
  console.log(`remove: ${update}`)
  res.json([find, update, remove])
} catch(err) {
  console.error(err)
  throw err // next(err)?
}

Try bluebirds Promise.each if you need a serial execution helper.
Comment: Promises do not "run", and there is no "execution" in `Promise.all` so there's no order for that either.
Comment: @Bergi better terminology?
Comment: Thank you @Matt, i thought by adding await to promises it won't execute all promises at the same time. is there away to add Promise.all, and is it necessary for this situation.
Comment: @Matt thank you your solution works, what if one of the mongoose function fails, is it possible to revert the functions that got executed
Comment: Mongo doesn't do transactions out of the box. You would need to manually roll back the data you want depending on the error.


multiple output filenames in R

Question: I'm having trouble with the code that I write below. I need to compute the distance matrix for each row of my input matrix (aa) and save the result in a file with the rowname as filename.
The aa matrix is a 100x100, but a test matrix look like this:
ID  A   B   C   D
AA  0.5 0.4 0.9 0.5
BB  0.2 0.1 0.8 0.96
CC  0.3 0.5 0.8 0.4
DD  0.1 0.4 0.5 0.78

Pratically I would like to obtain a single file for each row containing the distance matrix and with "AA.txt" and "BB.txt" and "CC.txt" and "DD.txt" as filenames.
a<- read.table ("test_matrix.txt", header = TRUE)
aa<- structure (a, class = "data.frame")
d_ply(aa, 1, function(row){
cu<- dist(as.numeric(row))
cucu<- as.matrix(cu)
write.table(cucu, quote = TRUE, file = paste(row$ID, "txt", sep = "."), sep = "\t")
}, .progress='text', .print = TRUE)

Using the code above I obtain the correct filenames, but the content is not right because I have a 5x5 matrix instead of a 4x4 one. Can someone tell me which is the problem? I guess something in reading the header...
Thank you!
Comment: @Justin Actually, I think they need to do `as.numeric(row[-1])` to remove the ID column value, before anything will work. (And there's a typo: hader should be header).
Comment: you want `row.names=FALSE` in your write step. The first column in your texts file are the row names of your output matrices.  (personally I think its an odd default!)
Comment: I receive an Error in in read.table I add row.names = FALSE
Comment: @joran I tryed your solution...but don't get a good result (only a single file is written.
Comment: Justin said to add it in `write.table`, not `read.table`. (Although I'm not convinced that's the real issue)
Comment: There are at least two issues, see my answer.
Comment: @Joran I tryed it also in the 'write.table' and I get only one file
Comment: Running your code as presented in the question, with only the two changes mentioned so far, I get four files as expected.
Answer: When I run your code, the output looks like:
"1" "2" "3" "4" "5"
"1" 0   NA  NA  NA  NA
"2" NA  0   0.1 0.4 0
"3" NA  0.1 0   0.5 0.1
"4" NA  0.4 0.5 0   0.4
"5" NA  0   0.1 0.4 0

You'll want to adjust your function to include both my and Joran's advice:
myfun <- function(row) {
  cu<- dist(as.numeric(row[-1]))
  cucu<- as.matrix(cu)
  write.table(cucu, file=paste(row$ID, 'txt', sep='.'), sep='\t', quote=TRUE, row.names=FALSE, col.names=FALSE)
}

Running d_ply(aa, 1, myfun, .print=TRUE) gives files that look like:
0   0.1 0.4 0
0.1 0   0.5 0.1
0.4 0.5 0   0.4
0   0.1 0.4 0

multiple output filenames in R


Inserir registros de uma tabela em outra em MySql?

Question: Estou com dificuldade de inserir dados de uma tabela em outra, por exemplo tenho a tabela orçamento que possui os itens, mas os ítens podem ser de diferentes fornecedores, e quando aprovado este orçamento o mesmo deve gerar as ordens de compras para os respectivos fornecedores, exemplo:

Tabela orçamento

Supondo que SELECT * FROM orcamento WHERE orcamento = 330;, tenho:

Tabela ordem de compra

Gostaria de criar uma ordem de compra para cada fornecedor como na tabela abaixo, sendo desmembrado, da seguinte forma:

Gostaria de criar um ordem de compra com todos os ítens do fornecedor como no exemplo da tabela ordem de compra onde foi criado uma ordem com os ítens de Id 2 e 4 que correspondem ao mesmo fornecedor de código 55, gostaria de usar esta funcionalidade diretamente no banco informando apenas o id do orçamento.
Estou utilizando php com mysql, e não mysqli.
Answer: Você pode usar um INSERT junto com um SELECT.
Por exemplo:
INSERT INTO ordem_compra (id, id_orcamento, fornecedor)
SELECT id, id_orcamento, id_fornecedor FROM orcamento WHERE orcamento = 330;

Comment: então o problema é que dessa forma preciso saber o id do fornecedor, vou informar o id do orçamento que possui diversos ítens e pode havar um ítem para cada fornecedor ou vários do mesmo fornecedor, e o id do fornecedor só saberei após fazer o select do orçamento.
Comment: Não entendi muito bem. Mas você não poderia alterar "fornecedor = 55" pelo id do orçamento e ai você teria todos os dados daquele orçamento no select.
Comment: Editei a pergunta estava confusa mesmo, peço desculpas.
Comment: @WMomesso Editei a resposta. Mas sugiro alterar as nomenclaturas, me parece que o id na tabela ordem_compra é o id do item e o id_oc que é o id da ordem de compra.
Comment: @DiegoSchidt tudo certo, fiz um inner join e funcionou perfeitamente.


Is a bunted foul ball for strike 3 a dead ball?

Question: So figure that a batter has 2 strikes on him and bunts the ball foul for strike 3 is the ball still in play since it is considered a strikeout?
Answer: According to Rule 5.06(c)5:

The ball is dead and runners advance one base, or return to their bases, without liability to be put out, when:

A foul ball is not caught, in which case runners return to their bases.

This is also the reason why pitchers often will not attempt to bunt on two strikes: a foul bunt is a dead ball and strike three.
Answer: Any foul ball is a dead ball if it is not caught. This is covered under Rule 5.06(c)(5) in the 2016 MLB Rule Book.

The ball becomes dead and runners advance one base, or return to
  their bases, without liability to be put out, when:

A foul ball is not caught, in which case runners
  return to their bases.


Computing a marginal posterior of a hierarchical model

Question: This is my first time posting an actual homework question. Usually I have more local resources such as office hours and student peers but this time I am a little short on those. I also need to rest but I can't so I'm spinning my wheels a lot more than I ordinarily would.
I have a hierarchical model of $m$ different binomials with $m$ different sample sizes, whose $m$ different $p$ parameters are governed by a population beta distribution. The beta distribution, of course, also has a prior.
I constructed what I think is the correct joint posterior distribution for this model:
$$P(p_1, p_2,\dots,p_{m}, \alpha,\beta|\mathbf X)\propto \pi(\alpha, \beta)\prod_{i=1}^{m} P(p_i|\alpha, \beta)P(x_i|p_i)$$
$$\propto\pi(\alpha, \beta) \prod_{i=1}^{m}p_i^{x_i+\alpha-1}(1-p_i)^{n_i-x_i+\beta-1} $$
The problem I am facing is that if I want to compute
$$P(\alpha,\beta|\mathbf X)$$
It seems as though, since I have m parameters to remove I am looking at m integrals (integrals because the beta is continuous).
This can't possibly be what I am expected to do unless one of the following is true:

I got the joint posterior incorrect
I should be doing this by sampling
There is an easier trick to mathematically computing a marginal posterior on this
I have the wrong idea of what marginalizing m parameters from a population distribution
amounts to (eg. we just integrate once since they are all from the same distribution; I can't see what to make of the individual p parameters in that case)
Comment: I don't know what the etiquette is for accepting your own answer but since this is the instructor's solution it seems appropriate.
Answer: I was correct in assuming that there was a trick. Here is the given solution:
The trick is that each $p_i$ is independent so you can rewrite the problem as the joint product of m individual integrals.
More specifically with $c=\frac{1}{B(\alpha, \beta)}$,
$$P(\alpha,\beta|\mathbf X)=\int_{p_1}\dots\int_{p_m}\pi(\alpha, \beta) \hspace{2mm} c^m\hspace{2mm} p_i^{x_i+\alpha-1}(1-p_i)^{n_i-x_i+\beta-1} dp_{1}\dots dp_{m}\\= \pi(\alpha, \beta) \hspace{2mm}c^{m} \prod_{i=1}^{m}\int_{p_i}p_i^{x_i+\alpha-1}(1-p_i)^{n_i-x_i+\beta-1}dp_i$$
Because this is the kernel of a $Beta(\alpha + x_i, \beta + n_i-x_i)$  we know each one will integrate to 1 if we add the necessary constant term.
$$\pi(\alpha, \beta) \hspace{2mm}c^{m} \prod_{i=1}^{m}B(\alpha + x_i, \beta + n_i-x_i)* \\ \int_{p_i}B(\alpha + x_i, \beta + n_i-x_i)^{-1} p_i^{x_i+\alpha-1}(1-p_i)^{n_i-x_i+\beta-1}dp_i\\=\pi(\alpha, \beta) \hspace{2mm}c^{m} \prod_{i=1}^{m}B(\alpha + x_i, \beta + n_i-x_i)$$
with $c=\frac{1}{B(\alpha, \beta)}$ the full expression is
$$P(\alpha,\beta|\mathbf X)=\pi(\alpha, \beta) \hspace{2mm}B(\alpha, \beta)^{-m} \prod_{i=1}^{m}B(\alpha + x_i, \beta + n_i-x_i)$$
In the problem I recieved it wasn't stated that the $p_i$ were independent but the original problem was counting bicycles amongst all traffic on different blocks so I suppose it is a logical assumption.


Polymorphism example? (Substitution principle and late dynamic binding)

Question: Below is a snippet of my code and I can't decide whether or not it is an example of Polymorphism.
Class hierarchy 1
Within my Player class (This is a subclass of Character) there is a method called showStats().
public String showStats(){    // Displays all current stats regarding the player.
    String stats = "
Name: "+ getName()+ "
Type: "+ getCharacterType() + "
Health: "+ getHealth() +"
Weapon Equipped: "+ getWeaponEquippedName()+"
Miles Walked: "+getWalked()+"
"+showInventory()+"
Level Completed: "+getLevelCompleted();
    return stats;
}

This method is overridden within the Magician and Warrior classes due to exclusive statistics only Warriors and Magicians would possess if they are of that type (Warriors have a power points attribute and Magicians have a steal points attribute).
Magician Class:
public String showStats(){ // Overridden method that shows all player stats including the number of steal points.
    String stats = super.showStats()+"
Steal Points: "+getMana()+"";
    return stats; }

Warrior Class:
public String showStats(){ // Overridden method that shows all player stats including the number of Power Points if they are a Warrior.
    String stats = super.showStats()+"
Power Points: "+getMana()+"";
    return stats;
}

Within the class Battle I call the showStats() method and the output is not known until the User has selected what character they wish to play as. I just wanted to be certain that this is an example of polymorphism as the character selected is not known until the program has already been compiled and is then selected by the user (i.e. Substitution principle and Late Dynamic Binding).
public static void gameMenu(Player player, int choice, String name)throws FileNotFoundException, IOException, ClassNotFoundException { // Game menu method is for displaying all options (Play game, view game rules, quit) to the user when the game runs.
       //Substitution principle applied to the player object depending upon what character the player wishes to select.
       if (choice == 3) {
           player = new Attack_Warrior();
       }
       else if (choice == 4) {
           player = new Defensive_Warrior();
       }
       else if (choice == 5) {
           player = new Attack_Magician();
       }
       else if (choice == 6) {
           player = new Defensive_Magician();
       }
       else{
           System.out.println("Error. Try again.");
           play(player);                                     // If the user enters an invalid input, the method loops and asks the player to re-enter their input.
       }

Thank you very much for your time and I look forward to hearing your response,
Alex
Comment: If you're overriding `showStats` and somewhere is calling it on an instance without knowing which subtype it is, then you're using polymorphism.
Comment: @khelwood Even if ShowStats() was not created at a superclass level? It was created within the Player class?
Comment: `Player` is a superclass of `Magician` and `Warrior`, right? So `showStats` **is** declared on a superclass (and overridden in subclasses).
Comment: @khelwood If you look at the image I put in you can see that Player is a subclass of Character. Player "extends" Character and Warrior "extends" Player. So is this still an example of polymorphism then? Thank you for your time, Alex
Comment: Yes, as I said, it is polymorphism with `Player` as the superclass and `Magician` and `Warrior` as the subclasses. The fact that `Player` is also a subclass of some other class is not relevant.
Comment: @khelwood I thank you very much for your time. Have a good day!
Answer: It is helpful to annotate the method of your child classes with @Override. If you do not get a compilation error, any code written with the parent type is a proper polymorphic call ;-)


Should I choose strings differently depending of type of guitar?

Question: I own both a dreadnought and a parlor acoustic guitar. On the dreadnought I use extra light elixirs. On the parlor I still have the original phosphor bronze light that came with it.
Is there different aspects to consider when it comes to restringing these guitars due to their neck length and build?
Answer: Essentially, yes.    Most dread-sized instruments will sound better with medium gauge strings.  You have to have enough mechanical energy to "drive" the top.
Many manufacturers of smaller-bodied instruments will specify a string tension.  Some will warn against anything heavier than "lights".   However, my small-bodied GS Mini specifies mediums due to its short scale.
Be aware that switching gauges might require adjustments to truss rod or action.
Comment: Ouch, Medium eh? I find Light to be noticeably heavier to fingerpick than the extra lights ... I think my Dreadnough came with light when I bought it. Both my Guitars are Simon & Patrick. The Dreadnought is a Woodland and the Parlor is a Woodland Pro.
Answer: If you like the reduced volume of the Parlor guitar (so as not to wake the neighbors), You might enjoy Flatwound strings, for purer tones at low volumes. Roundwound strings produce a fair amount of "noisy" overtones which can make notes difficult to identify at lower volumes. Flats don't.
But beware, most flats are "coated". The coating will wear off and the volume and "presence" will drop suddenly and substantially when this happens.
My favs are Thomastiks. I've probably said enough about them in my other answer here.
So if you're bold and curious, try a $10 set of D'Addario Chromes, play it until the coating wears off to get a sense of the spectrum of tones flats can give you.
Comment: I mostly fingerpick and adjust the volume so that my family can enjoy it as background music. I just put on a set of light Ernie Ball on my dreadnought which I have to say feel better than the Elixirs I used to use. I'll take a look at flat wounds when it's time to change on my parlor. Thanks. :-)
Comment: @MdaG Watch out for strings intended "for Archtop Guitars". I tried a set by IIRC Gibson where there was extra wrapping at the ball-end that crept over the bridge (on a Small-body Acoustic). It didn't seem to affect the tone, but it made palm-muting difficult.


Does the logistic function really uniquely satisfy this?

Question: It is said that the logistic function (denoted $y(u)$ below) is derived from the relation:
$$\frac{dy}{du}=y(u)(1-y(u))$$
Does $y(u)=\frac{1}{1+e^{-u}}$ really uniquely satisfy this?  I don't see how.  It seems to me there must be several functions that can satisfy that.  Please help me to see the light.
If I am permitted a follow-up question:
What do I have to do to the first equation so that
$$y(u)=\frac{1}{1+u^{-2}}$$
satsifies it?
Thanks
Comment: You are right, there are infinitely many solutions, though they are all closely related. To determine a unique solution, we need to know an **initial condition**, like the value of $y(0)$.
Comment: I guess you should multiply LHS by $\frac{u}{2}$...
Answer: No, $\frac{1}{1 + e^{-u}}$ is not the only function satisfying the equation.  So would any $y$ of the form $y(u) = \frac{1}{1 + C e^{-u}}$ for any fixed real number $C$, and so would $y$ given by the formula $y(u) = 0$.  (These functions I've listed are it, though, as far as differentiable functions defined on all of $\mathbb{R}$ go; there aren't any others.)  I will give a link on how to arrive at this result in a paragraph or two.
The function $\frac{1}{1 + e^{-u}}$ may be the only function satisfying both the differential equation and some initial condition of interest to the person asserting the uniqueness.  If you are getting the uniqueness assertion from a professor or textbook, they probably have that in mind, even if they forgot to say it.
There is a general method for solving equations like these, but it is best learned from a textbook.  The Wikipedia pages on separable differential equations and separation of variables are a start--- but better would be looking for "separable differential equations" in the index of the nearest calculus or differential equations book.  Wikipedia (and the Internet in general, for basic material like this) is more concerned with methods for writing down formulas that solve a differential equation, than proving that the formulas produced by the method are the only solutions to the differential equation.
I'm not sure what your second question precisely is: there's nothing you can "do" to the original equation to make it have that other solution, beyond just changing the equation entirely.  So really you're asking, what differential equation might have this other function as a solution.
In general, "given a function, find a differential equation satisfied by it" is not that interesting of a problem (unless you are looking for differential equations within some specific restricted class, or have other more specific goals in mind).  Let's see why.  If $y(1 + u^{-2}) = 1$, then differentiating both sides with respect to $u$ and using the product rule you find that $y(-2 u^{-3}) + y'(1 + u^{-2}) = 0$.  This a differential equation and it is satisfied by the original function $y$ (and other functions too).  So that's that.
Maybe this equation is not what you want because it explicitly involves the variable $u$.  But one can prove that there is no differential equation of the form $y'(u) = F(y(u))$ satisfied by the function $y(u) = \frac{1}{1 + u^{-2}}$.
To see this, suppose there were.
Since $y(1) = y(-1) = \frac{1}{2}$ (just compute using the formula for $y(u)$) we would conclude by putting in $u = 1$ and $u = -1$ in the equation $y'(u) = F(y(u))$ that $y'(1) = F(\frac{1}{2})$ and that $y'(-1) = F(\frac{1}{2})$ and hence that $y'(1) = y'(-1)$.  But you can calculate (use the formula for $y(u)$ to find a formula for $y'(u)$, and then put in $1$ and $-1$) that $y'(1)$ and $y'(-1)$ are not equal.  So no such $F$ can exist.


Is it possible to "unbend" a warped bow of a string instrument?

Question: When a bow of a string instrument warps due to misuse, neglect, or some other reason, can one forcefully "unbend" the bow to fix it. If not, what are other ways un-warp the bow other than bringing it to a shop?
Comment: Heat, and a very specific profile jig.
Comment: You could do what a shop does. I'm not sure what that is but I bet it involves a clamp or three and maybe steam or a humidifier or something like that.
Answer: Yes, a bow can be re-cambered, but it requires some skill and I wouldn't recommend trying it yourself (edit: unless it is a cheap bow you want to experiment on and don't care if you wreck it).
When the bow is made, the wood of the bow is bent into shape using heat, often by a careful application of flame.  The wood is unfinished at this point, so a re-profile usually means a refinish job as well.
When the wood gets hot enough the fibers release and the camber can be added to the profile. There is a delicate balance between the shape of the bow and its balance and bow makers can train for many years before mastering the art.
Depending on the age and value of the bow it can be worth it to have it re-worked. If it is an entry level or student bow, then it is usually cheaper to replace the bow.  Prices in the U.S.,from a re-hair to a full rework, range from about $85.00USD to $400.00USD and up.
Comment: The wood bending can also be practiced on with inexpensive hardwood dowels.
Comment: That's a good idea, Alphonso.  In fact, you can make a working bow out of an inexpensive hardwood dowel.
Comment: Yep.  I recamber bows routinely, but it can be tricky.  If you want to try it yourself on a bow you wouldn't mind losing, it's an interesting skill to learn.  It can be done with a flame (best a rather cool one, such as alcohol), an electric heater, or best, a woodstove or other source of radiant heat.  Heat it until you can bend it easily.  Bend into the right curve.  Heat again to make sure the curve holds.  Don't break it.


Erro com biblioteca Picasso

Question: Eu tenho um problema com meu codigo e não consigo encontrar. As imagens não aparecem usando a biblioteca Picasso.
Não posso ver o problema no debug porque durante o processo aparece esta mensagem:
Source not found
The source attachment does not contain the source for the file PathClassLoader.class
Segue a classe que aparece o erro:

public class AdaptadorLista extends BaseAdapter {
    private LayoutInflater mInflater;
    private List<Jogo> itens;
 private View viewSelecionada;
 private int gols=0;
 private TextView txtPlacarSelecionado;
 private boolean btMaisPressionado = false;
 private boolean btMenosPressionado = false;
 private ItemSuporte itemSuporte;
 private LinearLayout linhaLista;
 private Context context;

 public AdaptadorLista(Context context, List<Jogo> itens) {

  this.mInflater = LayoutInflater.from(context);
  this.itens = itens;
  this.context = context;
 }

 @Override
 public int getCount() {
  // TODO Auto-generated method stub
  return itens.size();
 }

 @Override
 public Object getItem(int position) {
  // TODO Auto-generated method stub
  return itens.get(position);
 }

 @Override
 public long getItemId(int position) {
  // TODO Auto-generated method stub
  return position;
 }

 private void importarImagem(ImageView imageView, String url) {

  Picasso.with(context)
    .load(url)
    .resize(70, 70)
    .centerCrop()
    .into(imageView);

 }

 @Override
 public View getView(int position, View view, ViewGroup parent) {

  // TODO Auto-generated method stub

  if(view==null){
   itemSuporte=new ItemSuporte();
   view = mInflater.inflate(R.layout.item_lista, null);
   if(position % 2 == 0){
    view.setBackgroundResource(R.color.listaColor);
   }
   itemSuporte.btMaisGolsMandante=((ImageButton) view.findViewById(R.id.btMaisGolsMandante));
   itemSuporte.btMaisGolsVisitante=((ImageButton) view.findViewById(R.id.btMaisGolsVisitante));
   itemSuporte.btMenosGolsMandante=((ImageButton) view.findViewById(R.id.btMenosGolsMandante));
   itemSuporte.btMenosGolsVisitante=((ImageButton) view.findViewById(R.id.btMenosGolsVisitante));
   itemSuporte.txtPlacarMandante=((TextView) view.findViewById(R.id.txtPlacarMandante));
   itemSuporte.txtPlacarVisitante=((TextView) view.findViewById(R.id.txtPlacarVistante));
   itemSuporte.txtNomeMandante=((TextView) view.findViewById(R.id.txtSimboloMandante));
   itemSuporte.txtNomeVisitante=((TextView) view.findViewById(R.id.txtSimboloVisitante));
   itemSuporte.txtDataJogo=((TextView) view.findViewById(R.id.txtDataJogo));
   //itemSuporte.txtLocalJogo=((TextView) view.findViewById(R.id.txtLocalJogo));
   itemSuporte.simboloMandante=((ImageView) view.findViewById(R.id.imgMandante));
   itemSuporte.simboloVisitante=((ImageView) view.findViewById(R.id.imgVisitante));
   view.setTag(itemSuporte);

  }else{
   itemSuporte= (ItemSuporte) view.getTag();
  }

  Jogo jogo = itens.get(position);
  importarImagem(itemSuporte.simboloMandante, jogo.getTimeMandante().getUrlImagemSimbolo());
  importarImagem(itemSuporte.simboloVisitante, jogo.getTimeVisitante().getUrlImagemSimbolo());
  itemSuporte.txtNomeMandante.setText(jogo.getTimeMandante().getSigla());
  itemSuporte.txtNomeVisitante.setText(jogo.getTimeVisitante().getSigla());
  itemSuporte.txtPlacarMandante.setText(Integer.toString(jogo.getGolsMandante()));
  itemSuporte.txtPlacarVisitante.setText(Integer.toString(jogo.getGolsVisitante()));
  itemSuporte.txtDataJogo.setText(jogo.getData());
Comment: Caezar, esse código não parecer ter problemas. Esta tendo algum erro no Logcat? Como esta seu Manifest? Acessando uma dessas url's pelo browser, ela aparece sem problemas?
Answer: Descobri o problema!
Era coma importação da classe. Estava importando a biblioteca picasso de outro projeto!

Erro com biblioteca Picasso


Error with a specific bash script

Question: I must first of all shamefully admit that I unfortunately know nothing about scripts... I am simply trying to use one that seems to fit my goal.
I am running a VPS node with OpenVZ, and I need a script which will automatically restart the VPS abusing the server load by using the specific command "vzctl restart SERVERID".
However, I'm getting nowhere unfortunately and the script returns errors when launched.
The original script is as follows:
<code>#! /bin/bash
export PATH="/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin"
maxload="20"; # put here the max loadavg permitted
cat /dev/null > loads.txt;
vzlist -o ctid,laverage > loads.txt;
cat loads.txt | while read line; do
vm=$(echo ${line:0:5});
load=$(echo ${line} | cut -d'/' -f3);
load2=$(echo ${load} | cut -d'.' -f1);
if [ $load2 -gt $maxload ]
    then
    echo "restarting $vm - $load";
    vzctl restart $vm;
    echo "$vm - $load" | mail -s "$vm restarted for overload" firstname.lastname@example.com
fi
done
</code>
If I launch it, I get this error:

antiload.sh: line 10: [: too many arguments

I researched a bit on the Internet, and I then tried isolating the variable on line 10 with quotes, thus changing the code like this:
<code>if [ "$load2" -gt $maxload ]
</code>
but I still get an error, as follows:

antiload.sh: line 10: [[: CTID LAVERAGE: syntax error in expression (error token is "LAVERAGE")

Please, can someone help me to debug this script so that I will be able to use it?
Thanks for your attention, time and help.
Comment: It looks like `vlist`'s output isn't in the format the script expects. Can you include a sample of what `vzlist -o ctid,laverage` actually prints on your system?
Comment: Try to put simple brackets around the whole argument of the if condition.
Comment: That said, you should add this line to the start of your file: `set -x` and post the output then. That's how you debug some bash.
Answer:
You're trying to compare array to init value which is odd.
You should print $load2 variable and see what contains.

Error with a specific bash script


Evaluate an increasing sum of binomial coefficients: $\sum_{k=1}^nk\binom{m+k}{m+1}$

Question: I've been working on a problem and got to a point where I need the closed form of

$$\sum_{k=1}^nk\binom{m+k}{m+1}.$$

I wasn't making any headway so I figured I would see what Wolfram Alpha could do. It gave me this:
$$\sum_{k=1}^nk\binom{m+k}{m+1} = \frac{n((m+2)n+1)}{(m+2) (m+3)}\binom{m+n+1}{ m+1}.$$
That's quite the nasty formula. Can anyone provide some insight or justification for that answer?
Comment: It is a consequence of the Cauchy's integral formula and the Cauchy's differentiation formula. See https://en.wikipedia.org/wiki/Cauchy%27s_integral_formula
Comment: There are a lot of interesting answers for your question. So you should evaluate to accept one of them (unless there are aspects on which you want to discuss. In that case, please tell us.)
Comment: @MarcoCantarini, answer accepted! I can't find much information on that contour integral identity. Can you point me in the right direction?
Answer: Using the integral representation of the binomial coefficient $$\dbinom{s}{k}=\frac{1}{2\pi i}\oint_{\left|z\right|=1}\frac{\left(1+z\right)^{s}}{z^{k+1}}dz$$ we have
 $$ \sum_{k=1}^{n}k\dbinom{m+k}{m+1}=\frac{1}{2\pi i}\sum_{k=1}^{n}k\oint_{\left|z\right|=1}\frac{\left(1+z\right)^{m+k}}{z^{m+2}}dz
 $$ $$=\frac{1}{2\pi i}\oint_{\left|z\right|=1}\frac{\left(1+z\right)^{m}}{z^{m+2}}\sum_{k=1}^{n}k\left(1+z\right)^{k}dz
 $$ $$=\frac{1}{2\pi i}\oint_{\left|z\right|=1}\frac{\left(1+z\right)^{m+n+1}}{z^{m+4}}\left(nz-1\right)dz+\frac{1}{2\pi i}\oint_{\left|z\right|=1}\frac{\left(1+z\right)^{m+1}}{z^{m+4}}dz$$ $$
 =n\dbinom{m+n+1}{m+2}-\dbinom{m+n+1}{m+3}
 $$ which is equivalent to your claim. To see that we have the same result, note that holds $$\dbinom{n}{k}=\frac{n+1-k}{k}\dbinom{n}{k-1}.$$
Comment: +1. Quite neat. I like this method a lot. It will be easier whenever you start with the change ${ m + k \choose m + 1} = {-m - 2 \choose k - 1}\left(-1\right)^{k - 1}$ because it moves the $k$-index to the 'lower floor',
Comment: @FelixMarin Thank you. I learned it form your answers :D
Comment: Fascinating! Thanks for the insight.
Answer: For  those who  enjoy integrals  here  is another  approach using  the
Egorychev method as  presented in many posts by  @FelixMarin and also by @MarkusScheuer, where we focus on finding an answer  that differs from the approaches that have already been seen.
Suppose we seek to compute
$$S(n,m) = \sum_{k=0}^n k{m+k\choose m+1}.$$
Introduce
$${m+k\choose m+1}
= \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m+k} \; dz$$
as well as the Iverson bracket
$$[[0\le k\le n]]
= \frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{w^k}{w^{n+1}} \frac{1}{1-w} \; dw.$$
This yields for the sum
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m}
\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{n+1}} \frac{1}{1-w}
\sum_{k\ge 0} k w^k (1+z)^k
\; dw \; dz.$$
For this to converge we must have $|w(1+z)|<1.$ We get
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m}
\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{n+1}} \frac{1}{1-w}
\frac{w(1+z)}{(1-w(1+z))^2}
\; dw \; dz
\\ = \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m+1}
\frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{n}} \frac{1}{1-w}
\frac{1}{(1-w(1+z))^2}
\; dw \; dz.$$
We evaluate the inner integral using the fact that the residues at the
poles sum to zero. The residue at $w=1$ produces
$$-\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m+1}
\frac{1}{(-z)^2} \; dz
= -\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+4}} (1+z)^{m+1} \; dz
= 0.$$
For the residue at $w=1/(1+z)$ we re-write the inner integral to get
$$\frac{1}{(1+z)^2} \frac{1}{2\pi i}
\int_{|w|=\gamma}
\frac{1}{w^{n}} \frac{1}{1-w}
\frac{1}{(w-1/(1+z))^2}
\; dw.$$
We thus require
$$\left.\left(\frac{1}{w^{n}}
\frac{1}{1-w}\right)'\right|_{w=1/(1+z)}
\\ = \left. \left(\frac{-n}{w^{n+1}} \frac{1}{1-w}
+ \frac{1}{w^n} \frac{1}{(1-w)^2}\right) \right|_{w=1/(1+z)}
\\ = -n (1+z)^{n+1} (1+z)/z + (1+z)^n (1+z)^2/z^2.$$
Substituting this  into the outer  integral and flipping signs  we get
two pieces which are
$$\frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m-1} n(1+z)^{n+2}/z \; dz
\\ = \frac{n}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+3}} (1+z)^{n+m+1} \; dz
= n\times {n+m+1\choose m+2}.$$
The second piece is
$$- \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+2}} (1+z)^{m-1}(1+z)^{n+2}/z^2 \; dz
\\ = - \frac{1}{2\pi i}
\int_{|z|=\epsilon} \frac{1}{z^{m+4}} (1+z)^{n+m+1} \; dz
= - {n+m+1\choose m+3}.$$
It follows that our answer is
$$\left(n - \frac{n-1}{m+3}\right) {n+m+1\choose m+2}
= \frac{nm+2n+1}{m+3} {n+m+1\choose m+2}.$$
Remark. Being rigorous we also verify that the residue at infinity
in the calculation of the inner integral is zero. We get
$$-\mathrm{Res}_{w=0} \frac{1}{w^2}
w^{n} \frac{1}{1-1/w} \frac{1}{(1-(1+z)/w)^2}
\\ = - \mathrm{Res}_{w=0}
w^{n-2} \frac{w}{w-1} \frac{w^2}{(w-(1+z))^2}
= - \mathrm{Res}_{w=0}
\frac{w^{n+1}}{w-1} \frac{1}{(w-(1+z))^2}.$$
There is  certainly no pole  at zero here  and the residue is  zero as
claimed (the  term $1+z$ rotates in  a circle around the  point one on
the real axis  and with $\epsilon \lt 1$ it is  never zero). This last
result could  also be obtained  by comparing degrees of  numerator and
denominator.
Comment: Wow, that's intense.
Answer: You can prove this by induction.
Here is the induction step:
$$
\begin{align*}
\sum_{k=1}^{n+1} k  \binom{m+k}{m+1} &= \frac{n((m+2)n+1)}{(m+2)(m+3)}\binom{m+n+1}{m+1} + (n+1)\binom{m+n+1}{m+1} \\
&=\frac{(m+n+2)(m(n+1)+2n+3)}{(m+2)(m+3)} \binom{m+n+1}{m+1} \\
&=\frac{(n+1)(m(n+1)+2n+3)}{(m+2)(m+3)} \cdot \frac{(m+n+2)!}{(m+1)!(n+1)!} \\
&= \frac{(n+1)((m+2)(n+1)+1)}{(m+2)(m+3)}\cdot \binom{m+n+2}{m+1}.
\end{align*}
$$
Comment: Thanks for the reply. But it's not that I couldn't prove it, more that I wanted some insight on why it was true.
Answer: The series can also be seen as the following.
\begin{align}
\sum_{k=0}^{n} k \, \binom{m+k}{m+1} &= \frac{1}{m+1} \, \sum_{k=0}^{n} k \, \frac{(m+1)_{k}}{k!} \\
&= \frac{1}{m+1} \, \left[ \sum_{k=0}^{n-2} \frac{(m+1)_{k+2}}{k!} + \sum_{k=0}^{n-1} \frac{(m+1)_{k+1}}{k!} \right] \\
&= (m+2) \, \frac{(n-1) \, \Gamma(m+n+2)}{\Gamma(n) \, \Gamma(m+4)} + \frac{ \Gamma(m+n+2)}{\Gamma(n) \, \Gamma(m+3)} \\
&= \frac{(m+n+1)!}{(n-1)! \, (m+3)!} \, (m \, n + 2n + 1) \\
&= \frac{m \, n + 2n + 1}{m+3} \, \binom{m+n+1}{n-1}.
\end{align}
Rearranging terms yields the form presented in the proposed problem. The notation used in Pochhammer's notation, namely,
\begin{align}
(x)_{k} = \frac{\Gamma(x+k)}{\Gamma(x)}.
\end{align}
Comment: What is that notation- $(m+1)_{k}$?
Comment: @BoRel A note has been added about the notation.
Answer: Here is a slightly different variation of the theme. It is convenient to use the coefficient of operator $[x^k]$ to denote the coefficient of $x^k$ of a series. This way we can write e.g.
\begin{align*}
[x^k](1+x)^n=\binom{n}{k}\tag{1}
\end{align*}

We obtain
  \begin{align*}
\sum_{k=1}^{n}&k\binom{m+k}{m+1}=\sum_{k=1}^nk[x^{m+1}](1+x)^{m+k}\tag{2}\\
&=[x^{m+1}](1+x)^{m+1}\sum_{k=1}^nk(1+x)^{k-1}\tag{3}\\
&=[x^{m+1}](1+x)^{m+1}D_x\left(\sum_{k=1}^n(1+x)^{k}\right)\tag{4}\\
&=[x^{m+1}](1+x)^{m+1}D_x\left(\frac{1-(1+x)^{n+1}}{1-(1+x)}-1\right)\tag{5}\\
&=[x^{m+1}](1+x)^{m+1}\left(\frac{(nx-1)(1+x)^n}{x^2}+\frac{1}{x^2}\right)\tag{6}\\
&=[x^{m+3}](1+x)^{m+n+1}(nx-1)\tag{7}\\
&=n[x^{m+2}](1+x)^{m+n+1}-[x^{m+3}](1+x)^{m+n+1}\tag{8}\\
&=n\binom{m+n+1}{m+2}-\binom{m+n+1}{m+3}\tag{9}
\end{align*}
Comment:

In (2) we apply the coefficient of operator according to (1)
In (3) we use the linearity of the coefficient of operator and split the binomial conveniently
In (4) we introduce the differential operator $D_x:=\frac{d}{dx}$
In (5) we use the formula for the finite geometric series
In (6) we apply the differential operator $D_x$
In (7) we do some simplifications and use the rule
\begin{align*}
[x^m]x^{-k}A(x)=[x^{m+k}]A(x)
\end{align*}
In (8) we use the linearity of the coefficient of operator and apply the rule above again
In (9) we write the expression using binomial coefficients and obtain a result in accordance with the answer of @MarcoCantarini
Comment: Very cool. I have not seen the 'coefficient of' operator before. Where can I read more on it?
Comment: @BoRel: Take a look at section 2.2. of H. Wilf's *[Generatingfunctionology](https://www.math.upenn.edu/~wilf/gfology2.pdf)*. You might also want to   have a look at a slightly more *[challenging example](http://math.stackexchange.com/questions/1795155/a-strange-combinatorial-identity/1796393#1796393)*.


Compute that Galois group $Gal\left(F/\mathbb{Q}\right)$, with $F$ is the splitting field of the polynomial $X^{4}-2X^{3}-8X-3$

Question: Compute the Galois group $Gal\left(F/\mathbb{Q}\right)$, with $F$ is the splitting field of the polynomial $X^{4}-2X^{3}-8X-3$
Comment: ...and you've already done...?
Answer: $X^{4}-2X^{3}-8X-3=(X-3)(X^3+X^2+3X+1)$.
Then $Gal (F/\mathbb{Q})=Gal (E/\mathbb{Q})$, where $E$ is the splitting field of $X^3+X^2+3X+1$.
Now you can easily solve the exercise proving that an irriducible polynomial with order $p$, where $p$ is a prime , and only two roots in $\mathbb{C}$ has Galois Group $S_p$. (Hint: $S_p$ is generated by a transposition and a p-cycle)
Comment: Well, I didn't calculated the two roots of polynomial, i've only looked at the graph of $y=x^3+x^2+3x+1$.
Comment: Can we do the same with $X^4-3X^2+4$? (Compute the Galois group $Gal(F/Q)$, with $F$ is the splitting field of the polynomial $X^4-3X^2+4$)?
Comment: Ehm, no. You can use the theorem above only if the degree of polynomial is prime. In this case you can easy check the roots putting $t=X^2$ and solve the problem with explicit calculations.
Comment: Can you explain more precisely to me? Please
Comment: Can you tell the two roots of $X^3+X^2+3X+1$


Add to JSON array

Question: How can I append a new element to the existing array using N1QL?
<code>[
{
  "address": "127.0.0.1",
  "time": 0
},
{
  "address": "127.0.0.1",
  "time": 0
}
]
</code>
Answer: You can set to update the data
<code> ARRAY_APPEND(field, { "adress":"127.0.0.1", "time":null })

 where "key you need to use as reference' = "referemce data"
</code>
Comment: this will update the JSON and append the new value to the array
Comment: Could you elaborate a bit and write a full statement example? What type of statement should I use? Update? And how do I format the WHERE condition
Comment: for that you need to elaborate your question, which fields you want to Update? is it adress? time? if you just want to Append, the ARRAY_APPEND() will do that as I said before
Comment: I just want to append yes, so the whole JSON document contains an array with elements consisting of these fields: address & time, but now what's the key I need to use as reference?
Comment: well you are to say which keys you want. if those datas are important you need to have a key to reference them: For example, what is the name of this object? if it has, you can use the name as a key to find it. example: "title": "adventure",
    "custom": [
     {"modified": "a01","time": 200},
     {"modified": "a02","time": 201},
     {"modified": "a03","time": 202},
     ]
    }
Comment: The document id is 'login_history:username' and each element represents a single login. Each time a different login is detected, I'm going to want to append to that array.
Comment: So then: UPDATE `login_history` USE KEYS "username"

ARRAY_APPEND("username",{ "adress":"127.0.0.1", "time":0})

 where "username" = "name of the user you're updating"
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/200187/discussion-between-indrz-and-lucas-soares).

Add to JSON array


Integral Expression of Legendre Polynomials

Question: a) Verify that for $x > 1$, $n \in \mathbb{N}$ the function
$$P_n(x) = \frac{1}{\pi} \int_0 ^ \pi (x + \sqrt{x ^ 2- 1} \cos \phi) ^ n d \phi$$
is a polynomial of degree $n$ (the $n$th Legendre polynomial).
b) Show that
$$P_n(x) = \frac{1}{\pi} \int_0 ^ \pi \frac{d\varphi}{(x - \sqrt{x ^ 2- 1}\cos \varphi) ^ n}.$$
I have solved the first part of the problem but I am stuck on the second part. I have tried making the substitution $r = \varphi - \pi$ in the second integral and using the oddity of $y = \cos x$ to bring the denominator to $(x + \sqrt{x ^ 2 - 1} \cos r) ^ n$, but I have little idea how to proceed from there. Can sombody help? Thanks in advance!
Answer: There must be something wrong. Or maybe I'm wrong.
Using substitution $t=\tan(\varphi/2)$ gives that
$$\int_0^\pi \frac{d\,\varphi}{a+b\cos\varphi}=\frac{\pi}{\sqrt{a^2-b^2}}.$$
So in (b) we can get that $P_1(x)=1$ but in (a) we have obviously $P_1(x)=x$.
Comment: I have just checked that you are probably right.
Comment: Maybe there is an error in the problem.


Reading tips on longitudinal mixed models and mediation

Question: I'm a Swedish PhD student in psychology looking for advice on what to read to understand linear mixed models in a longitudinal context better. We're running a RCT with two active groups and weekly measures that will continue to collect data for a couple of years. When it's over the intention is to investigate a couple of putative mediators in this data. Our analysis plan includes using linear mixed models for this purpose, but I'm early in my career and so far only have a surface level understanding of the method. Since the data collection will not be completed until end of next year, I hopefully have time to learn it.
I would be happy to receive recommendations on what to read to get a deeper level of understanding here, both theoretical and practical. Books, articles, online accessible courses, youtube lectures, anything is welcome.
My background knowledge:

Somewhat proficient in R.
In my opinion a good enough understanding of basic ideas in frequentist null-hypothesis testing and basic methods in inferential statistics.
Good enough understanding of simple and multiple regression.
However, weak background in math. Would not be able to derive or prove anything I'm using  from first principles but can usually follow along with (good) explanations of it.
Answer: For a good overview of issues in longitudinal data analysis, I recommend Chapter 7 of Frank Harrell's Regression Modeling Strategies. Mixed models aren't the only, or even necessarily the best, way to analyze data from studies like yours. There's a helpful table summarizing the strengths and weaknesses of several types of approaches, and references for further reading. Its emphasis is on generalized least squares rather than on mixed models, but I think it's important to understand what you gain and what you lose if you jump immediately to linear mixed models without considering alternatives.
Comment: Thanks! Very helpful
Answer: I like the somewhat old book by Hedeker and Gibbons: Longitudinal Data Analysis and also Gelman and Hill Data Analysis and Multilevel Models.  Frank Harrell's book (recommended by EdM) is excellent, as well, and gives you much more than just material on mixed models.
Answer: Analyzing mediation, under the broader heading of "causal inference," can be tricky. This answer by Robert Long is a superb, concise introduction to the directed acyclic graphs that help clarify your understanding of the subject matter in a way that informs your modeling. For a remarkably helpful introduction to causal inference in general, read Causal Inference: What If by Hernán and Robins. It develops the essential concepts through simple examples "without models" and builds from there through increasingly complicated scenarios. Its 13 pages of references provide many resources for more detailed study.


Criar uma div no topo do blog (wordpress) para flutuar fixamente ao rolar para baixo

Question: Tenho um blog, Queria exibir um anúncio em uma div depois que os usuários rolar para baixo e assim logo do site não esteja visível essa div apareça, e se voltar a subir ela desapareça. link do site http://maroclub.net/
Answer: Olha tem uma solução com jquery
$(function(){
    var nav = $('.classDiv');
    $(window).scroll(function () {
        if ($(this).scrollTop() > 95) {
            nav.show();
        } else {
            nav.hide();
        }
    });
});

Esse código mostrara a div quando o topo do site subir 95px, você pode aumentar o valor caso queira que aparace mais a baixo, no caso, é so trocar ".classDiv" pela div que estiver manipulando.

jQuery(document).ready(function($) {

 $(function(){
  var nav = $('.objeto');
  $(window).scroll(function () {
   if ($(this).scrollTop() > 95) {
    nav.fadeIn();
   } else {
    nav.fadeOut();
   }
  });
 });
});
.conteudo {
  height: 700px;
}
.objeto {
  position: fixed;
  height: 50px;
  width: 50px;
  background-color: red;
  display: none;
  top: 50px;
}

Comment: Por favor evitem longas discussões nos comentários; a conversa de vocês foi [movida para o chat](http://chat.stackexchange.com/rooms/67174/discussion-on-answer-by-victor-pereira-criar-uma-div-no-topo-do-blog-wordpress)
Answer:

<!DOCTYPE HTML>

<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Google Adsense</title>

Answer: Para começar a mostrar o banner basta agir no valor 200 desse linha if($(document).scrollTop()>200){

    var div = $('.banner');
    $(window).scroll(function(){
       if($(document).scrollTop()>200){
          var percent = $(document).scrollTop() / ($(document).height() - $(window).height());
          div.css('opacity', 0 + percent);
       }else{
          div.css('opacity', 0);
       }

    });
.encheLinguissa {
  height: 1200px;
}

.banner {
  position: fixed;
  top: 0;
  width: 100%;
  height: auto;
  background-color: #00e676;
  opacity: 0;
  z-index: 1;
  transition: opacity 1.5s;
}

transition - faz com que a transição ocorra suavemente em um tempo determinado.
  Quanto maior o valor (1.5) em transition: opacity 1.5s; mais suave a transição.


Facebook needs the CURL extension

Question: I'm trying to run my facebook php application on my apache server, on a new machine with Windows 64bit. As mentioned in the title, the error given is Facebook needs the CURL PHP extension. I have uncommented the line extension=php_curl.dll in php.ini and there is no problem in SublimeText, however when I try accessing my localhost, the error is thrown.
I've been looking a bit in base_facebook.php, where the error is thrown:
if (!function_exists('curl_init')) {
  throw new Exception('Facebook needs the CURL PHP extension.');
}

I've been looking on the internet and tried a lot of sites, including a topic with the same problem on stackoverflow:Facebook needs the CURL PHP extension.
There is a comment about this problem with WAMP 64bit, and I tried the link with the fix, but nothing useful- seems like it has changed since.
Does anyone have the same issue? Any idea how to solve this, please?
Answer: Download and replace php_curl.dll with http://www.mediafire.com/?3ay381k3cq59cm2 had the same issue today lol
p.s: To the one who gave me a -1 I took the download link directly from http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Please read what I have mentioned : HAD THIS ISSUE TODAY!!! and it worked.
Comment: I don't think I'd ever install a .dll off MediaFire. Eep.
Comment: I didn't -1, but I think it was done because they were not sure if that file is trustworthy.
Comment: @BujancaMihai: Make sure to virus scan the download first :)
Comment: @Bujanca Mihai:have you uncommented in the php.ini the curl library under wamp\bin\apache\apache2.4.2\bin\php.ini and restarted the server?
Comment: @KA_lin yes, I did.Both in php and apache directories
Comment: @Bujanca Mihai: So you have uncommented in both dirs and copied the php_curl.dll in the php/php[version]/ext/ with a server restart and still nothing? If so try stopping all services and make sure you run wamp with admin privileges...
Comment: I looked upon the other links here and found one that worked for me. Thanks http://www.anindya.com/php-5-4-3-and-php-5-3-13-x64-64-bit-for-windows/
Answer: This tutorial worked for me. Very straight forward too.

Facebook needs the CURL extension


Softmax regression bias and prior probabilities for unequal classes

Question: I'm using Softmax regression for a multi-class classification problem. I don't have equal prior probabilities for each of the classes.
I know from Logistic Regression (softmax regression with 2 classes) that the prior probabilities of the classes is implicitly added to the bias ($\log(p_0/p_1)$).
Usually what I do is to manually remove this term from the bias.
My question is, what is the corresponding term in softmax regression bias?
Thanks.
Answer: As far as I'm aware, the justification for softmax bias initialization is a bit hand-wavy. Recall softmax regression is maximum (log) likelihood estimation for $W,\textbf{b}$, with the model being the following:
$$
\DeclareMathOperator{cat}{Cat}
\newcommand{\norm}[1]{\left\| #1 \right\|}
\newcommand{vsigma}{{\boldsymbol\sigma}}
\newcommand{vx}{{\textbf{x}}}
\newcommand{vb}{{\textbf{b}}}
\newcommand{vz}{{\textbf{z}}}
y\sim\cat(\vsigma(W\vx+\vb)); \;\;\;\sigma_i(\vz)=\frac{\exp z_i}{\sum_j\exp z_j}.
$$
With bias initialization our intention is to find a good value $\vb$ with which $p(\vx, y|W,\vb)\propto p( y|W,\vb,\vx) $ starts out high. Under the assumption that we initialize $W$ with small near-0 values and that $y$ is a label in $[K]$, $W\vx\approx 0$ so:
$$
\log p( y|W,\vb,\vx)=\sum_{k=1}^K1_{y=k}\log \sigma_k(W\vx + \vb)\approx\log\sigma_y(\vb)
$$
Adding up the log-probabilities for all assumed-independent examples $\{(\vx_i,y_i)\}_{i=1}^n$, a good initialization for $\vb$ would minimize the total approximate data log likelihood:
$$
\newcommand{vc}{{\textbf{c}}}
\sum_{i=1}^n\log\sigma_{y_i}(\vb)=\sum_{i=1}^nb_{y_i}-n\log\sum_{k=1}^K\exp b_k$$
The gradient of the above wrt $\vb$ is $\vc-n\vsigma(\vb)$, with $\vc\in\mathbb{N}^K$ the vector of counts of each class. The function above is also concave, see the question here about smooth max for a proof.
The two facts above imply a maximum is available whenever $\vsigma(\vb)=\vc/n$. This, in turn, suggests a viable initialization for the $i$-th term $b_i$ of the bias $\vb$ is indeed $\log p_i$, the proportion of $i$-labelled examples in the training set (aka the marginal statistics). You might see that you can add any constant to $\vb$ and achieve another likelihood-maximizing bias as well; however, a large scale would get in the way of learning $W$. The relationship with the logistic bias is not coincidental --- this tutorial discusses the similarity.


error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory

Question: I am trying to run an application that requires libcurl but I can't start it.
 error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory

I was running centos 5.9 but after update I have now CentOS release 5.11 (Final)
when I run yum install curl i get this:
Package curl-7.15.5-17.el5_9.x86_64 already installed and latest version
Package curl-7.15.5-17.el5_9.i386 already installed and latest version

when running locate libcurl
/usr/lib/libcurl.a
/usr/lib/libcurl.so
/usr/lib/libcurl.so.3
/usr/lib/libcurl.so.3.0.0
/usr/lib/pkgconfig/libcurl.pc
/usr/lib64/libcurl.a
/usr/lib64/libcurl.so
/usr/lib64/libcurl.so.3
/usr/lib64/libcurl.so.3.0.0
/usr/lib64/pkgconfig/libcurl.pc
/usr/local/lib64/libcurl.a
/usr/local/lib64/libcurl.so.4
/usr/local/lib64/libcurl.so.4.2.0
/usr/share/man/man3/libcurl-easy.3.gz
/usr/share/man/man3/libcurl-errors.3.gz
/usr/share/man/man3/libcurl-multi.3.gz
/usr/share/man/man3/libcurl-share.3.gz
/usr/share/man/man3/libcurl-tutorial.3.gz
/usr/share/man/man3/libcurl.3.gz

Comment: centos5 is really old. Your application obviously needs newer version of curl. You might get it from some other third-party repository or build it on your own, but updating system to something more recent sounds like a better idea.
Comment: Yes.. I upgraded to centos 6 and works fine.
Answer: Try with yum whatprovides */libcurl.so.4 and install the packages with matching files. Pay attention to install both i386 and x86_64 packages.
If this does not work, please provide the output of the command above.
Answer: CentOS 5 is really old. Your application obviously needs newer version of curl. You might get it from some other third-party repository or build it on your own, but updating system to something more recent sounds like a better idea.


Euler transform without generating functions

Question: Roughly speaking, if $a_n$ is the number of graphs with some property and $b_n$ is the number of multisets of graphs with the same property, then these numbers are related via a transform of integer sequences which is sometimes called Euler transform. In particular, if $a_n$ is the number of connected graphs with $n$ vertices then $b_n$ is the number of not necessarily connected graphs with $n$ vertices. Or, if $a_n$ is the number of trees then $b_n$ is the number of forests. Or, if $a_n=1$ is the number of totally disconnected graphs with $n$ vertices then $b_n$ is the number of partitions of $n$.
For the description of that transform, see MathWorld, starting from the words "The third type". It is also discussed in section 4.2 of Harary & Palmer's Graphical Enumeration, and the 2nd volume of Stanley's Enumerative combinatorics discusses many variations of the relation between sequences $\{a_n\}$ and $\{b_n\}$.
The explicit formula for this transform is (combining eqs. (7) and (8) from MathWorld and setting $b_0=1$):
$$ b_n = \frac{1}{n} \sum_{k=1}^n b_{n-k} \sum_{d|k} d \, a_d $$
It is usually proved using generating functions.
My question is: can this formula be explained with purely combinatorial reasoning, without using generating functions?
It is clear that (using the first example) there are $a_k$ connected graphs with $k$ vertices and $b_{n-k}$ graphs that make use of the rest of the vertices, so we sum their product over $k$ (similarly to the Catalan numbers recurrence $C_{n+1} = \sum_{k=0}^{n} C_{k} C_{n-k}$), and $\frac{1}{n}\sum_d d\times$ compensates overcounting; but how exactly this compensates overcounting?
Comment: Formula (5) at MathWorld can be proved with combinatorial reasoning, but then it requires some algebraic manipulations to derive the formula that you quoted in the question.
Answer: I think I figured it out.
First let's discuss the Catalan number recurrence. To obtain the formula for $C_{n+1}$ counting the number of correct strings of $n+1$ pairs of parentheses, we highlight the last external parentheses pair in such string and consider the parentheses strings $s_1$ before that pair and $s_2$ inside it: $s_1(s_2)$.
Any nonempty correct parentheses string can be uniquely decomposed into $s_1$ and $s_2$, and we can unambiguously restore $s_1(s_2)$ from any two (possibly empty) correct strings $s_1$ and $s_2$. Note that $s_1$ and $s_2$ are independent in the sense that no relation between them is required except for containing $n$ parentheses pairs in total. So we denote the number of parentheses pairs in $s_2$ as $k$, go through all possible values of $k$, and get the recurrence $
C_{n+1} = \sum_{k=0}^n C_kC_{n-k}
$.
Now regarding the multisets of graphs (or, more generally, multisets of nonisomorphic structures on $n$-sets). In a multiset, we can naturally group graphs by their number of vertices $i$ (and order these groups by size), and within graphs of the same number of vertices we can also group isomorphic graphs together and enumerate these groups somehow (introducing index $j$ for a given $i$; there are $a_i$ such groups, some of them possibly empty). Isomorphic graphs within each group can also be enumerated and ordered somehow.
Although the graphs are now ordered within any multiset, we cannot do what we did with parentheses strings and split the multiset into two independent parts (two multisets or maybe a multiset and a graph): even if we highlight, say, the last graph, or the last group of isomorphic graphs, or the last  group of graphs with the same number of vertices, in any of these cases it would impose serious restrictions on the non-highlighted part. It spoils the independence of the parts and ruins the approach "count ways to construct each of the parts separately, multiply, and sum over the size of one part".
We'll do another way. In a nonempty multiset of graphs, pick one of the $n$ vertices. Set a rule that the whole graph containing that vertex is highlighted, together with graphs isomorphic to it coming after it (they are ordered, remember?). So we have split the multiset into two parts: the residual non-highlighted part, which is a (possibly empty) multiset of graphs, an the highlighted part, which is a block of some nonzero number of isomorphic graphs (on $i$ vertices, of $j$th kind).  Denote the total number of vertices in the block as $k$.
For example, here we have a forest, in which the trees are ordered, and a vertex is picked, which determines the highlighted block of isomorphic trees starting from the one with the picked vertex and others to the right of it:

Note that we can unambiguously restore the original multiset from the residual multiset and the block, and it works for any residual multiset and any block, the only restriction is that the total number of vertices should be $n$. (Just like with Catalan numbers! However, now we need to learn how to count blocks.) On the other hand, any pair consisting of a residual multiset and a block of isomorphic graphs (with $n$ vertices total) can be obtained from some original $n$-vertex multiset in exactly $i$ ways (the number of vertices in a graph from the block). Therefore, if we go through all possible pairs of a multiset and a block with $n$ vertices total and count them with the weight $i$ (determined by the block), then we'll get exactly the number of ways to take an $n$-vertex multiset, order its vertices, and pick a vertex in it, which equals $nb_n$.
So for fixed $k$, $i$, and $j$, the block is determined unambiguously (although it only exists if $i|k$), while the residual multiset can be chosen in $b_{n-k}$ ways. Multiply by the weight factor $i$; sum over $j$ (since the summand does not depend on $j$, this only adds the factor $a_i$); sum over the allowed values of $i$ (i. e. the divisors of $k$; $b_{n-k}$ factors out of this sum); finally, sum over $k$ and divide by $n$ to get $b_n$. After replacement $i\to d$ we get the desired formula from the question.
Updates

The same idea applied to the particular case of rooted unlabeled trees, i. e. $b_n=a_n+1$: https://mathoverflow.net/questions/409418/bijective-proof-of-recurrence-for-rooted-unlabeled-trees/409496#409496  Thanks to O. Kulkov for bringing that to my attention.
Published: A. Zabolotskii, Dendrocombinatorics, Kvant, 2023, №3, 20–23 [in Russian] (doi link).
Comment: The same idea applied to the particular case of rooted unlabeled trees, i. e. $b_n = a_{n+1}$: https://mathoverflow.net/questions/409418/bijective-proof-of-recurrence-for-rooted-unlabeled-trees/409496#409496
Thanks to O. Kulkov for bringing that to my attention.


Strong Topological Conjugacy and Reparameterization of Flows

Question: In discrete dynamics, we say that two systems $f:X \to X$ and $g:Y \to Y$ are topologically conjugate if there exists a homeomorphism $p:X \to Y$ such that $p \circ f = g \circ p$.
My professor was discussing what the corresponding equivalence relation should be for flows. She said that a "naive" definition would be to say that the flows $f: X \times \mathbb{R} \to X$ and $g: X \times \mathbb{R} \to X$ are "equivalent" if there exists a homeomorphism $p:X \to Y$ such that for all $t$ we have $p \circ f_t = g_t \circ p$. This is called being "strongly topologically conjugate", but my professor said that this is too strong; if a flow is a parameterization of another one, then the two flows are not strongly topologically conjugate.
To see why this is true, I investigated an example. Consider the flows $f_t(x) = x + tv$ and $g_t(x) = f_{2t}(x) = x + 2tv$ where $x, v \in \mathbb{R}^2$. It seems to me that if we choose the homeomorphism $p(x) = 2x$, then the equation $(p \circ f_t) (x)= (g_t \circ p)(x)$ becomes
$$p(x+tv) = p(x) + 2tv \implies 2x + 2tv = 2x + 2tv,$$
so these systems are indeed strongly conjugate. Can someone please give me an example, or an intuitive explanation, of why reparameterizing does not necesarily give strongly conjugate systems?
Thank you!
EDIT: Throughout this I assumed that a reparameterization of $f_t(x)$ is a function of the form $f_{kt}(x)$ where $k$ is a real number. Is this the actual definition of a reparametrization?
Comment: Where you quote your professor as saying they are not strongly topologically conjugate, should this say they are not *necessarily* strongly topologically conjugate?
Answer: $\mathbb{R}^2$ is very special because it has $\mathbb{R}^{\times}$ acting on it by dilation. Do the same calculation but for a vector field on $S^1$, which doesn't. Alternatively, pick a vector field which has a zero at some smallest finite time $t_0$; the value of $t_0$ doesn't change under strong conjugacy but it does change under reparameterization.
Comment: Thanks! Would you also mind taking a look at my edit?
Comment: @Blue: that's what I assume a reparameterization of a flow is in this context (more precisely I assume that $k$ should be a positive real number) but I don't know what's standard.
Comment: Okay thanks, I see. My professor never defined it so I just wanted to check.
Comment: $\Bbb R^\times$ being simply a pair of points, right?


Statistical test in R for count data

Question: I am struggling with using the correct test for count data in R. The dataset I have is the number of nymphs produced by three aphid species on wheat.
So this is count data with one response variable (number of nymphs) and one explanatory variable with three levels (i.e. three different species).
I want to test whether there are any differences between the three species with the number of nymphs they produce.
I think that I should not use an ANOVA with count data. I have tried a GLM with QuasiPoisson, but I am struggling to interpret the output and be sure that I have used the correct test. Essentially I want to equivalent for a one-way anova but for count data.
Comment: Do you have just 3 counts, or do you have 3 *sets* of multiple counts? If you are having trouble interpreting the output from a GLM, it might help you to read: [How to interpret coefficients in a Poisson regression?](http://stats.stackexchange.com/q/11096/)
Comment: Hi. I am having trouble adding a table to the posts to show what the data is. I have sixty individual data points, twenty for each of three species. I want to analyse any differences in the mean count between the three species.

I have not seen any examples of Poisson being used where there is only one explanatory variable, which is why i am uncertain.
Answer: I suggest two consideration before modelling.

Are you or not comparing fecundities of species through their lifetime?
Poisson distribution might not be the case here if you do compare in this way, because species might have different lifespan on the same host plant, Poisson however refer to occurrence of events at the same time interval. Non-parametric comparison can be used here but please try to have enough replicates because generally non-parametric methods are more conservative.
If hypothesis on Poisson is met here, it will be better to check whether, overall, the average value of response variable equal to their dispersion. You might consider to use "Negative binomial regression" if your data is over-dispersed.
Answer: I would suggest a Kruskal-Wallis test followed by Dunn Test for multiple comparisons:
library(dunn.test) #available on CRAN

## count data
df <- data.frame(group=LETTERS[1:3], count = c(1,3,5,4,4,6,1,3,5,2,3,5,1,5,3,4,2,5))

kruskal.test(count~group, data=df)

#Kruskal-Wallis rank sum test
#
#data:  count by group
#Kruskal-Wallis chi-squared = 8.7041, df = 2, p-value = 0.01288

# non-formula usage (default "holm" method)
dunnTest(df$count,df$group)

#Dunn (1964) Kruskal-Wallis multiple comparison
#  p-values adjusted with the Holm method.
#
#  Comparison         Z     P.unadj      P.adj
#1      A - B -1.131517 0.257837400 0.25783740
#2      A - C -2.925386 0.003440288 0.01032086
#3      B - C -1.793869 0.072834082 0.14566816

Comment: The dunnTest function is found in the FSA package.  This is a good implementation to use.  One, I like the format of the output, and 2) some of the other implementations in R report one-sided p-values, which you don't want by default.
Answer: I like your original approach. There is a worked example here. I have never done Poisson regression, but that seems to me what you have here, where number of nymphs is your Poisson distributed y and species is your factor variable x.
glm(y~x, family="poisson")

You would interpret the output similarly to how you would interpret an ordinary ANOVA output from R.
Comment: Would Poisson be appropriate where there is only one explanatory variable? I have only seen examples where there are multiple explanatory variables.
Comment: Yes, of course one variable is fine. If your y variable was normal, in R you would do `lm(y~x)`. For a normal y and one categorical x, the usual name is one-way ANOVA. BTW you could also try quasi-poisson, as you did at the start. It deals with 'over dispersion'. But I wouldn't lose sleep about it.
Comment: Sometimes people get confused with the `summary` output in R.  With `glm` objects, it is sometimes helpful to use the `Anova` function in the `car` package to get an anova table, and the `lsmeans` package for post-hoc comparisons.

Statistical test in R for count data


Home recording: Preamp or Dynamic Mic?

Question: I've been recording songs for almost a year now but I still don't know all the secrets of a good home recording.
I'm currently using a Rode NT1-A condenser microphone, a Focusrite Saffire 6 audio interface and a Line 6 Pod HD for my guitar.
I am really satisfied with my gear, yet I'd like to know more about the recording for the vocals:
I'm sure that a condenser microphone is a great thing, but I can't use it with my Pod HD because the XLR-port doesn't provide phantom power, so I can only plug in a dynamic microphone.
I like my microphone, but I always have to add a lot of VST effects to my vocal track because they sound too bright, which is also a minor problem. (I have a 5 bucks dynamic karaoke mic which doesn't need any VSTs to sound full, so it's not about my performance)
My question is, does a preamp make a lot of difference when using a condenser microphone? I think my interface already has a built in preamp, does it make sense to buy a separate preamp? When is it a good idea to get a dynamic microphone for home recording?
Comment: Why do you want to use Pod HD? Why don't you just use Saffire 6?
Comment: You could connect line output to line input of Saffire, as a workaround.
Comment: Can't you also just use the POD to record the guitar parts, then switch to the Saffire for recording with the mic? It supports phantom power so the Saffire is compatible with condenser mics. At this stage you don't really *need* another preamp.
Comment: @el.pescado I can only use one interface at the time in my DAW. It would be nice if I could use only one interface, but that was just an idea :)
Saffire 6 doesn't model the guitar, I don't use it for guitar recording.
Comment: Many condenser mics can use a battery, when phantom power isn't available. You still need XLR, but that's another matter.
Answer: It all depends on what sound you are looking for. "Better sound" is a rather subjective concept.
I do suggest you to get a system with phantom power, not for a "better sound" necessarily, but for increasing your arsenal of options. Your mic choice will vary in different scenarios, and it's very useful to have the option of going condenser.
Vocals are commonly recorded with big diaphragm condensers, but dynamics are sometimes used too. Once you have a system capable of handling both, you will be able to make the decision based on what you are hearing.
Definitely a very good inversion for any studio, of any size.
Answer: Phantom power is here to stay. Condenser mics are better for recording. Dynamic mics tend to be more use in the rough and tumble of live stage situations. To future-proof yourself, it's better to get equipment which can provide phantom power. Better recording mics will generally need it. A pre-amp would do, but eventually you'll be better off with a system that provides p.p. inbuilt.
Answer: A microphone certainly needs a preamp, to provide phantom power and to amplify the signal.  But the preamp in your mixer or in your audio interface is probably just fine.  A recent test in Sound on Sound magazine established that a variety of mic preamps, from utility-priced to boutique, unless set up to deliberately add distortion all sounded exactly the same.
Comment: Two links.

http://www.soundonsound.com/sos/oct12/articles/preamps.htm

http://www.soundonsound.com/sos/dec12/articles/preamp-results.htm
Comment: can you link to that article? it sounds really interesting.
Comment: A lot of people were really upset at these results, and came up with ingenious arguments to prove their expensive gear DID actually add value to their recordings.. SoS continues to review boutique preamps with a straight face.  And hi-fi magazines still advise spending a hefty proportion of a system's cost on "interconnects".  You can't fight religion :-)
Comment: With modern electronic components, it's quite hard to design a preamp that *doesn't* sound good (and have good measured characteristics) - unless you set yourself a real challenge like "the total component costs for the design must be less than 1 US dollar").
Answer: To get a better sound at vocals your best bet would be to sit down and work with what you got. Improve your mixing skills. Your gear is pretty good and there's no reason that you can't get something at least workable out of it.
Comment: Of course I will not stack up my gear until I am satisfied with the sound. My question was just about the possibilities of how I can bring together my gear the most efficient way. I got my answers, but I'll wait quite a while before buying something new so don't worry, I'll practice enough with what I have ;)
Answer: Uh, when I read about you shouting in your NT1A, I cannot but wince.  The NT1A is a large diaphragm condensor with high accuracy and sensitivity.  It's great for picking up stuff faithfully and from a distance with minimal noise.
Which makes it a superb recording mic for, say, a Liederabend.  Put it on a suitable gallows and record piano and singer from near the first seat rows.
That's not what you have here.  Maybe you should take a look for a small amp and a singer's microphone that match your idea of a good sound.  It can still make sense to then record the overall sound (if the room does not mush it up too much) with one or two NT1A after going through suitable voice and instrument amps.
Comment: Very useful hint, I thought that a dynamic mic would solve such a problem, but I don't have one yet. What microphones do you recommend, especially for shouting techniques?
Comment: If you're a shouter, shout into a SM58.  There's probably one lying around!
Comment: The NT1A is typically used as a close vocal or instrumental mic.  You COULD put a stereo pair of them in front of a concert platform I suppose.

Home recording: Preamp or Dynamic Mic?