Generalized Additive Model or non-parametric linear regression?

Question: I have a data set as follows:
Response variable; proportion (i.e., 0.15, 0.94, 0.26)
Predictor variables; both fixed, one continuous (400,700,1000,1300), one catagorical (2-levels of species)
I am interested in the interaction between these two predictor variables.
Code for the model used:
glm_necrosis <- glm(necrosis ~ Sp + Treat + Sp*Treat, family = gaussian)
I have run a linear regression in R and plotted my residuals against predicted values and while there is no clear non-linear trend in the data, homogeneity of variance was violated (classic wedge shape). A q-q plot also showed that the data was highly leptokurtic and non-normal. I tried a number of transformations (arcsine, log, squared, etc.), and nothing could improve on the normality or variance assumptions.
Following the arcsine transformation, this is what the residuals looked like.

I would like to know what my options might be for continuing. Would a generalized additive model be appropriate, or are there non-parametric linear regression alternatives that might would better?
I appreciate any assistance.
Comment: You can't interpret a QQ plot in the presence of heteroskedasticity, so ignore that as your error is more fundamental. You would expect heteroskedasticity with proportions, from two different causes (only one of which would be improved by transformation). Can you show the residual plot you have this wedge shape in?  Are these count-proportions (count on some total count) or continuous proportions (like fraction of land area of a particular type, say)?
Comment: Hi Glen_b, the data are continuous proportions (fraction of live tissue remaining in a sample). I will try to add the residuals plot to this post.
Comment: Is the size of each sample you have the fractions for the same? How are these fractions obtained? (some potential methods might effectively work out as count-proportions anyway). Are there exact 0's or 1's?
Comment: All samples were approximately equal in size. In order to quantify this variable, I subtracted the area of live tissue from the surface area of the sample and then divided by the total surface area. This gave me the proportion of the tissue that had died during the experimental period.
Comment: 1. how did you calculate area? (counting cells or counting squares for example? via some instrument? some other way)  2. Are there exact 0's or 1's?  3. The residuals look much as you'd expect; (I'm somewhat surprised an arcsin-sqrt didn't show a substantial improvement.). ....  I'd be inclined to use beta regression, or 0-1 inflated beta regression if you have exact 1's or 0's, though a quasi-binomial may do for capturing the changing variance
Comment: Area was measured in ImageJ using images of the samples.  I have posted the residuals plot following the arcsine transformation as well.
Comment: Doesn't look like it took. If you go down to the answer box below and upload it there, (but don't press  "post"!), you could then copy and paste the imgur url into a comment and I (or someone else) can put it in your question for you.
Comment: @Glen_b, my apologies, I have posted it now. There still seems to be some skewness. Or does this appear to be good enough now?
Comment: You could still have some skewness; I was mostly looking at the effect on the variances which are substantially improved (though not perfect). This encourages me in thinking that one of the previous suggested possibilities might work. ***Are there any exact 1s or 0's in the data set?***
Comment: Yes, there are exact 1s and 0s.
Comment: Thanks. Then skewness after the transform is no great surprise. I'd be inclined to consider 0-1 inflated beta models  I'll try to write a short answer
Comment: Thank you @Glen_b. This has been a helpful exchange. I am relatively new to advanced statistics. I am performing my analyses in R. Any pointers on coding for this analysis would be helpful.
Comment: There are several discussions on beta regression and 0-1 inflated beta models (and even suggestions on how they might be done in R in some of those). Try some searches, if you can't turn up anything I might be able to find a couple of links
Comment: I found a package (zoib) that can run the data. Quick question though, what constitutes inflated 0s and 1s. I have multiple 0s (probably inflated) but only a couple of 1s. Should I run the model with both 0s and 1s inflated, or just 0s?
Comment: Yep, zoib is one of the packages. A beta distribution -- being continuous on (0,1) -- cannot have any exact 0's or exact 1's. If you have even *one*, you need the inflated bit.
Answer: 1) You may consider a logit transform log(p/(1-p)) because you are dealing with proportions (and, by the way, if you know out of how many sample points these proportions are computed, then consider glm with a binomial family for a logistic regression).
2) What are the plotted residuals you used? The variance inhomogeneity may be due to influential points (corresponding to the rightmost points on your residual plots above). You may consider studentized residuals instead. See http://www.statmethods.net/stats/rdiagnostics.html under Non-constant Error Variance.
3) If that does not work and you may also consider the function gamlss from package gamlss. There is a flexible way for fitting inhomogeneous sigma. I don't have enough practical experience to propose a code here though.
Hope this helps.


Passar uma variável do método construtor para outro método

Question: Estou usando PDO e Quero um método construtor com a conexão com o banco de dados mas a variável da conexão não esta acessível em outro método
class Estoque{
public function __construct(){
    $conn= new PDO("mysql:host=localhost;dbname=caixa","root","");

}

public function listarTodosProdutos(){// seleciona todos produtos do Banco de dados e retorna

    $stmt=$conn->prepare("SELECT * FROM produtos");
    $stmt->execute();
    while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
        echo"Codigo:".$result["id"]." "."
"."Nome do Produto:   "."".$result["nome"]."
".""." de valor de    ".$result["valor"]." Reais "."
"."da categoria    ".$result["descricao"].""."
"."---------------------------------------------------"."
";

    }

}
aqui esta a outra parte que instancio e chamo o método
<?php
require_once"Estoque.php";

$e=new Estoque();
$e->listarTodosProdutos();

?>
Erro apresentado
Notice: Undefined variable: conn in C:\xampp\htdocs\Caixa made in Gabriel\Estoque.php on line
Comment: Use `$this->conn`
Answer: Variáveis instanciadas localmente porém que servem para a classe todas devem ser chamadas com
$this->variável_que_deseja
No seu caso $this->conn
Comment: eu mudei coloquei o $this->  no modo construtor e continua aparecendo   aparecendo o mesmo erro Notice: Undefined variable: conn in C:\xampp\htdocs\Caixa made in Gabriel\Estoque.php on line 8              e                            Notice: Undefined variable: conn in C:\xampp\htdocs\Caixa made in Gabriel\Estoque.php on line
Comment: Tente algo dessa maneira, declarando uma variavel, e logo apos sobrescrevendo seu valor com o valor do construtor
public $conn;

  public function __construct($conn) {

    $this->conn = $conn;

  }
Answer: Exatamente como disseram a solução é colocar o $this na instancia e na atribuição que torna-se uma variável global

    class Estoque{
public function __construct(){
    $this->conn= new PDO("mysql:host=localhost;dbname=caixa","root","");
}
public function listarTodosProdutos(){// seleciona todos produtos do Banco de dados e retorna
$stmt=$this->conn->prepare("SELECT * FROM produtos");
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
    echo"Codigo:".$result["id"]." "."
"."Nome do Produto:   "."".$result["nome"]."
".""." de valor de    ".$result["valor"]." Reais "."
"."da categoria    ".$result["descricao"].""."
"."---------------------------------------------------"."
";

}

}
aqui esta a outra parte que instancio e chamo o método

listarTodosProdutos();
?>


What does axis=[1,2,3] mean in K.sum in keras backend?

Question: I'm trying to implement a custom loss function for my CNN model. I found an IPython notebook that has implemented a custom loss function named Dice, just as follows:
from keras import backend as K
smooth = 1.

def dice_coef(y_true, y_pred, smooth=1):
    intersection = K.sum(y_true * y_pred, axis=[1,2,3])
    union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])
    return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)

def bce_dice(y_true, y_pred):
    return binary_crossentropy(y_true, y_pred)-K.log(dice_coef(y_true, y_pred))

def true_positive_rate(y_true, y_pred):
    return K.sum(K.flatten(y_true)*K.flatten(K.round(y_pred)))/K.sum(y_true)

seg_model.compile(optimizer = 'adam',
              loss = bce_dice,
              metrics = ['binary_accuracy', dice_coef, true_positive_rate])

I have never used keras backend before and really get confused with the matrix calculations of keras backend. So, I created some tensors to see what's happening in the code:
val1 = np.arange(24).reshape((4, 6))
y_true = K.variable(value=val1)

val2 = np.arange(10,34).reshape((4, 6))
y_pred = K.variable(value=val2)

Now I run the dice_coef function:
result = K.eval(dice_coef(y_true=y_true, y_pred=y_pred))
print('result is:', result)

But it gives me this error:
ValueError: Invalid reduction dimension 2 for input with 2 dimensions. for 'Sum_32' (op: 'Sum') with input shapes: [4,6], [3] and with computed input tensors: input[1] = <1 2 3>.

Then I changed all of [1,2,3] to -1 just like below:
def dice_coef(y_true, y_pred, smooth=1):
    intersection = K.sum(y_true * y_pred, axis=-1)
    # intersection = K.sum(y_true * y_pred, axis=[1,2,3])
    # union = K.sum(y_true, axis=[1,2,3]) + K.sum(y_pred, axis=[1,2,3])
    union = K.sum(y_true, axis=-1) + K.sum(y_pred, axis=-1)
    return K.mean( (2. * intersection + smooth) / (union + smooth), axis=0)

Now it gives me a value.
result is: 14.7911625

Questions:

What is [1,2,3]?
Why the code works when I change [1,2,3] to -1?
What does this dice_coef function do?
Comment: `[1,2,3]` means that the sum (seens as an aggregation operation) runs through the second to fourth axes of the tensor.
Comment: Likewise `axis=-1` in `sum` means that the sum runs over the last axis.
Answer: Just like in numpy, you can define the axis along you want to perform a certain operation. For example, for a 4d array, we can sum along a specific axis like this
>>> a = np.arange(150).reshape((2, 3, 5, 5))
>>> a.sum(axis=0).shape
(3, 5, 5)
>>> a.sum(axis=0, keepdims=True).shape
(1, 3, 5, 5)
>>> a.sum(axis=1, keepdims=True).shape
(2, 1, 5, 5)

If we feed a tuple, we can perform this operation along multiple axes.
>>> a.sum(axis=(1, 2, 3), keepdims=True).shape
(2, 1, 1, 1)

If the argument is -1, it defaults to performing the operation over the last axis, regardless of how many there are.
>>> a.sum(axis=-1, keepdims=True).shape
(2, 3, 5, 1)

This should have clarified points 1 and 2. Since the axis argument is (1, 2, 3), you need a minimum of 4 axes for the operation to be valid. Try changing your variables to something like val1 = np.arange(24).reshape((2, 2, 2, 3)) and it all works.
The model seems to calculate the Binary Cross Entropy Dice loss and dice_coeff(), as the name suggests, calculates the Dice coefficient. I'm not sure what the purpose of smooth is, but if it was for the purpose of avoiding divisions by 0, you'd expect a small number, like 1e-6.
Answer:
What is [1,2,3]?

These numbers specify which dimension we want to do the summation. The smallest number shows the outer dimension and the biggest shows the inner. See the example:
import tensorflow as tf

tf.enable_eager_execution()

    a = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

    print(tf.reduce_sum(a, axis=2).numpy())
    #[[ 3  7]
    # [11 15]]
    print(tf.reduce_sum(a, axis=1).numpy())
    #[[ 4  6]
    # [12 14]]
    print(tf.reduce_sum(a, axis=0).numpy())
    #[[ 6  8]
    # [10 12]]

In the above example, axis = 2 means, inner entries which are: [1,2] , [3,4], [5,6], and [7,8]. As a result, after summation, we have the tensor: [[3, 7], [11, 15]]. The same idea applies to other axes.

Why the code works when I change [1,2,3] to -1

When we did not specify any axis or on the other hand specify all axis means that we sum over all tensor elements. This result our tensor converted to a single scalar. See example:
a = tf.constant([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(tf.reduce_sum(a).numpy()) # 36
print(tf.reduce_sum(a, axis=[0,1,2])) # 36

If we have 3 dimension [0, 1, 2], axis = -1 is equal to axis = 2.  See here for complete tutorial on python indexing.

What does this dice_coef function do?

See here for a complete explanation about dice_coef.
Answer: First two parts of your question are already explained. I'll explain the last one.

What does this dice_coef function do?

dice_coef function is calculation dice similarity coefficient which is a loss function. I'll explain context of image segmentation tasks so, dice similarity coefficient is a measure of how well two contours overlaps.
img Source: Coursera
It's value ranges from 0 to 1.

0 means complete mismatch i.e they don't overlap at all
1 means perfect match i.e they completely overlap

In general, for two sets A and B, the Dice similarity coefficient is defined as:
DSC(A,B)=( 2 × |A ∩ B| )  /  ( |A|+|B| ).
To avoid division by zero ϵ is added which is a small number
DSC(A,B)= ( 2 × |A ∩ B| + ϵ )  /  ( |A| + |B|+ ϵ ).
In your case:

A is y_true

B is y_pred

ϵ is smooth


How not to trigger the Bootstrap tab click on click?

Question: I am trying not to trigger bootstrap tab click in asp.net. Here is my HTML

Step 1: Details

    li id="li2" class="deactiveLink">Step 2: Photos

Step 3:Add. Info

Step 4: Preview

and here is my javascript function
    function getit() {
        return false;
    }

I have tried this in getit()
   $('.addNewTab >.nav-tabs > li:nth-child(5)').find('a').trigger('click');

I am new to Bootstrap therefore I am unable to do my task. I do not want to use divs for that. I want to use tab  which cannot be clicked. Am I missing something here in my code? What do I need to do?
Comment: Simply remove href from  tag and it will become unclickable
Comment: If you want to make it "unclickable" why use tabs?
Answer: According to bootstrap 3 docs http://getbootstrap.com/javascript/#tabs you can active the tabs either manually be javascript or by adding data-toggle="tab" or data-toggle="pill" on an element.
So you can not add the data-toggle="tab" or data-toggle="pill" but rather active them with javascript when you need it.
As already mentioned in the comments you can remove the href from  elements to prevent browser's attemts to navigate to a given url on click, or assign onclick handler to these a elements and use event.preventDefault()


Migrate to google CDN (external origin ) without DNS change

Question: We are using AWS cloudfront and planning to migrating to Google cloud CDN as we have opted google cloud as the cloud provider. At the moment our DNS is registered with 3rd party provider. However I identified while configuring LB back-end service in google cloud that to enable the backend service with external origin we should do it via google cloud Public DNS . Is there any way I can continue with current DNS provider and migrate to google cloud CDN
Comment: Have you checked this article [Setting up Cloud CDN with an external origin](https://cloud.google.com/cdn/docs/setting-up-cdn-with-external-origin)? If not, please provide a link to the document you've followed.
Comment: @SerhiiRohoza https://cloud.google.com/load-balancing/docs/negs/internet-neg-concepts#limitations Please check the limitations . An internet endpoint with an FQDN defined must be resolvable by Google Public DNS.
Comment: You don't need to move to Google DNS. Your hostname (domain) just needs to be _resolvable_ - e.g. queryable - by public DNS. An internal hostname that isn't public would not meet this need.
Comment: Thanks for the reply. Hostname is public. Could you please give some details? Do I need to change something in my current DNS configuration?
Answer: Please have a look at the documentation again:

An internet endpoint with an FQDN defined must be resolvable by Google
Public DNS. Names that cannot be resolved by the public DNS system
will not be usable as an internet endpoint.

As a result, yes, you can continue with current DNS provider and migrate to google cloud CDN if your domain name public and can be resolved by the public DNS system. To check it please go here or run commands:
host -a your.fqdn.domain.name 188.8.131.52
host -a your.fqdn.domain.name 220.127.116.11

In addition, please have a look at the documentation section Authenticating requests:

Query the _cloud-eoips.googleusercontent.com DNS TXT record using a
tool like dig or nslookup. Note the CIDRs (following ip4:) and ensure
these ranges are allowed by your firewall or cloud Access Control List
(ACL).

$ dig TXT _cloud-eoips.googleusercontent.com
...
;; ANSWER SECTION:
_cloud-eoips.googleusercontent.com. 3600 IN TXT "v=spf1 ip4:18.104.22.168/20 ip4:18.104.22.168/18 ~all"

and at the section IP address resolution for FQDN endpoints:

The external HTTP(S) load balancer attempts to connect to the first IP
address in the DNS response. If that IP address isn't reachable, the
load balancer returns an HTTP 502 (Bad Gateway) response. This is true
even if other IP addresses from the DNS response are available.

The external HTTP(S) load balancer uses a DNS resolver in a Google
Cloud region that is closest to its client on the internet. If the DNS
record for your INTERNET_FQDN_PORT endpoint returns different IP
addresses based on the location of the client, make sure that each of
those IP addresses can be reached by the load balancer.

So, allow access from 22.214.171.124/20, 22.214.171.124/18 and be sure that IP address in the DNS response are highly available. No special configuration of DNS is needed.


On the order of natural functions {f:N→N}

Question: Define a partial order on natural-valued functions (or sequences, depends on how you see it): $f<g$  iff $\exists x:\forall n(n>x\rightarrow f(n)<g(n))$.
Intuitively, $f<g$ if $g$ increases more than $f$.
Now, a set $A$ of functions is cofinal if it contains arbitrarily 'large' functions- $\forall f$ , $\exists g\in A:f<g$.
My question is, how big do these cofinal sets have to be?
$A$ clearly can't be finite; If it has a maximal element $g$, then the function $h$ defined by $h(x)=g(x)+1$ is bigger than $g$. However, I don't know whether $A$ can be countable or not. If it can, is there a way to construct such an $A$, or does it rely on nonconstructive tools (Axiom of Choice)?
What happens when we generalize the question, for say real-valued sequences $\{f:\mathbb{N}\rightarrow \mathbb{R}\}$ or even real-valued functions?
Comment: I can't imagine the situation changes when we consider maps $f: \mathbb{R} \to \mathbb{R}$ since $\mathbb{N} \subseteq \mathbb{R}$ is cofinal
Comment: @basket See the end of my answer. It does change!
Comment: I've added the set-theory and logic tags, since this question certainly should have them.
Comment: Note that this partial order is not really concerned with _rate of growth_ since we can define the same relation without referencing the ordering of the function arguments: $f<g$ iff $\{n\mid f(n) \ge g(n)\}$ is a finite set.
Answer: Great question! This is connected with what are known as cardinal characteristics of the continuum; specifically, you're asking about the dominating number, $\mathfrak{d}$ -  the least size of any dominating family (in your terms, "cofinal family"). See also https://mathoverflow.net/questions/29624/how-many-orders-of-infinity-are-there.
We can in fact show that $\mathfrak{d}$ is uncountable, as follows. Fix any countable set $\{f_i: i\in\mathbb{N}\}$ of functions on $\mathbb{N}$. Now let $g$ be defined as $$g(n)=1+\sum_{i<n}f_i(n).$$ It's easy to see that $g$ dominates every $f_i$.
Conversely, we clearly have $\mathfrak{d}\le 2^{\aleph_0}$. In the presence of the continuumy hypothesis "$\aleph_1=2^{\aleph_0}$," this of course determines $\mathfrak{d}=2^{\aleph_0}$; however, we can ask what happens in the absence of the continuum hypothesis.
The answer, perhaps surprisingly, is: practically anything! It is consistent with ZFC, for instance, that $\mathfrak{d}=\aleph_1<2^{\aleph_0}$.
Things get much more interesting if we ask how $\mathfrak{d}$ can interact with other cardinal characteristics of the continuum, such as:

The smallest $\kappa$ such that the union of $\kappa$-many measure-zero sets is not measure zero.
The smallest $\kappa$ such that there is a family of $\kappa$-many functions not dominated by any single function (the "dual" of $\mathfrak{d}$, the bounding number $\mathfrak{b}$).
The smallest cardinality of a maximal almost disjoint family - a family of infinite subsets of $\mathbb{N}$ which have finite pairwise intersections, and is maximal with this property.
Etc.

When we ask about comparing pairs of cardinal characteristics of the continuum, this is very well-understood; see Cichon's Diagram https://en.wikipedia.org/wiki/Cicho%C5%84%27s_diagram. For instance, even though they sound very similar, ZFC proves $\mathfrak{b}\le\mathfrak{d}$, and it is consistent with ZFC that $\mathfrak{b}<\mathfrak{d}$, so there is an asymmetry there.
When we ask about three or more cardinal characteristics at once, this gets very hard, and until relatively recently very little was known; see https://mathoverflow.net/questions/37188/consistency-results-separating-three-cardinal-characteristics-simultaneously.
EDIT: You also asked about finding dominating sets. Well, we can certainly just take the set of all functions $\mathbb{N}\rightarrow\mathbb{N}$, so this doesn't take any real axiomatic power. But what about families of minimal cardinality? Well, here things get interesting; for one thing, without the axiom of choice there might not be any dominating families of minimal cardinality ($\mathfrak{d}$ could be undefined)! See https://mathoverflow.net/questions/191545/cardinal-characteristics-without-choice. And even with AC, we can show that if $\mathfrak{d}<2^{\aleph_0}$ then any minimal-cardinality dominating family is really hard to define (e.g., non-Borel, and - assuming large cardinals - non-projective as well) simply because so is every set of cardinality between $\aleph_0$ and $2^{\aleph_0}$.
So there doesn't seem to be a really solid answer to "How hard is it to find nontrivial dominating families?", but certainly "Pretty hard" is a good start.

As to generalizations:
Certainly the dominating number for $\mathbb{N}\rightarrow\mathbb{R}$ is just $\mathfrak{d}$ again. Given $f: \mathbb{N}\rightarrow\mathbb{R}$, let $f':\mathbb{N}\rightarrow\mathbb{N}: n\mapsto\lceil f(n)\rceil$. Then

Any dominating family $\{f_i: i\in I\}$ of maps $\mathbb{N}\rightarrow\mathbb{N}$ is also a dominating family $\{f_i: i\in I\}$ of maps $\mathbb{N}\rightarrow\mathbb{R}$.
Meanwhile, if $\{g_i: i\in I\}$ is a dominating family of maps $\mathbb{N}\rightarrow\mathbb{R}$, then $\{g_i': i\in I\}$ is a dominating family of maps $\mathbb{N}\rightarrow \mathbb{N}$.

However, if we look at maps $\mathbb{R}\rightarrow\mathbb{R}$, things get much messier. First of all, we need to refine our notion of domination of functions: by "$f<g$" do we mean $$f(x)<g(x)\mbox{ for all but finitely many $x$}$$ or $$f(x)<g(x)\mbox{ for all but boundedly-many $x$}$$ or $$f(x)<g(x)\mbox{ for all but bounded-from-above many $x$}$$ or something else?
To just play around for a moment, let's look at the first case: $f<g$ if $f(x)<g(x)$ for all but finitely many $x$. In this case, any dominating family must have size $>2^{\aleph_0}$ (so the number does change, quite a lot). To see why, let $\{f_i: i< 2^{\aleph_0}\}$ be any family of continuum-many maps from $\mathbb{R}$ to $\mathbb{R}$. Now build $g$ such that $g(x)>f_i(x)$ for infinitely many $i$, as follows: write $\mathbb{R}$ as a partition of continuum-many infinite sets $A_i$, and let $g(x)=f_i(x)+1$ for each $x\in A_i$. Certainly $g$ doesn't dominate $f_i$ - this is a difference from the argument that the original dominating number is uncountable! - but also clearly $f_i$ doesn't dominate $g$.
We can use similar arguments on every other notion of domination I can think of. However, the relationships of the exact values of the generalized bounding numbers is not clear to me. For instance;

Let $\le_0$ and $\le_1$ be the orderings on $\mathbb{R}^\mathbb{R}$ defined as follows: $f\le_0g$ if $f(x)\le g(x)$ for all but finitely many $x$, and $f\le_1g$ if $f(x)\le g(x)$ for all but bounded-from-above-many $x$. Is it consistent with ZFC that the corresponding dominating numbers are different?

Note the switch from "$<$" to "$\le$", which I think is more natural for a variety of reasons.
Such "higher" cardinal characteristics have been studied a little, although (as far as I can tell) not extensively; see e.g. http://www.sciencedirect.com/science/article/pii/016800729500003Y.
Comment: In your last, I think the natural extension is $f(x) \le g(x)$ for all $x \gt \text {some } X$ as that captures the notion of eventually larger than in my mind.


Themes, blocks, and content ... Oh my!

Question: I am a newbie to Drupal/Acquia Dev Desktop. Please excuse me if this is a dumb question.
I'm trying to grasp the relationship between themes (the one I chose is Corked Screwer), blocks, and content. In Corked Screwer there are images on the top half of the page/node and my content is at the bottom.
Am I understanding correctly that Content/main page content is where my typed-in content is displayed? I can control this with Visibility Settings/Content Types, etc. Yes?
How do I go about customizing the top half of the page to replace the default images with my own? Can you point me to a good video tutorial?
Thanks!
Answer: Yes, the Main page content block is where your content will render. Yes those visibility settings control on what page/content type/role will show that block content area. Typically, you want to leave this block alone since it's the main presentation of your content (what's the point of having a page if it doesn't have any content?).
It looks like the CorkedScrewer's default home page is more a demo template to demonstrate its block regions; you can't replace the images without overwriting the existing ones in its images folder.  It can vary based on the theme developer, but usually you can control a theme's slideshow images from its settings page in /admin/appearance.
Comment: The second video was not very helpful. It talked about using Firebug. Firebug may be somewhat useful. There are settings for slideshow at admin/appearance, but none for the images presented. The Views module is not installed so I cannot click Views/Block. I did find all this in page.tpl.php. Perhaps the best way I can fool around with this theme is to make a sub-theme. The first video (above) helped me do that. I copied page.tpl.php into it and made changes, but they don't seem to work as I expect. Is there a better video or tutorial you can suggest?
Answer: The "Corked Screwer" is a theme, and slideshow is created by Views Block. You should able to change the image by modify that slideshow page, because each slide is created by a slideshow node.
Comment: OK. I found an image labeled slider-img1.png in C:\Users\Sam\Sites\devdesktop\drupal-7.36\sites\all\themes\corkedscrewer\images\local. I replaced it with one of my images. It worked. I then found https://www.drupal.org/node/1907040 that pointed me to page.tpl.php. I'll check into it tomorrow. I also found some videos that are helpful https://www.youtube.com/watch?v=R0i5P3QGm5s &  https://www.youtube.com/watch?v=yYSSM3pNBTI. I've not yet watched the second one. Have to sign off until tomorrow.
Answer: OK. Now that I've learned a bit more about Drupal and got into the inside of Open Outreach I decided to use the Open Outreach theme and have learned how it works. The Open Outreach them uses Panels & Mini Panels. I don't know much about them, but I learned from http://openoutreach.org/section/blocks is that this theme uses the Context UI module. I followed the instructions to customize my home page.

Themes, blocks, and content ... Oh my!


I don't understand the bottom number in a time signature

Question: I've learned that 4/4 means 4 beats with the kind of beat being a crotchet. However, I've seen pieces with that time signature that don't just use crotchets, but minims, quavers, etc. I am still a beginner in music theory, so there's a lot I don't know, and I've not seen anyone ask this question anywhere, which is making me feel dumb.
I know that a semibreve has a time value of 4, minim 2, crotchet 1 etc. I just don't understand the purpose of the bottom number in the time signature. For example, 4/4 is telling me the crotchet is the kind of beat, but crotchets don't need to be used. At this point I'm starting to ignore the bottom number and only rely on the top number (number of beats) as that seems to be the only thing that matters rule-wise.
Comment: Has anyone posted an answer where the "bottom number" is not a power of 2 yet?
Comment: upvoted to 19, and it's a duplicate question
Comment: @JudyN [Adam Neely](https://youtu.be/cQ9yI4dtuGQ) has a really good video on "irrational" time signatures
Comment: @JudyN. In traditional notation it is not possible for the bottom number to be anything other than a power of two.  That possibility only arose with the experimental avant guard of the 20th century.
Answer: To put it very simply, the bottom number tells you what the top number is referring to. It is a little clearer to use the fractional way of discussing notes, so:

minim = half (1/2) note
crotchet = quarter (1/4) note
quaver = eighth (1/8) note

So a measure of 4/4 has four quarter notes (4 x 1/4) and a measure of 2/2 has two half notes (2 x 1/2). Technically, the measures both contain the same number of quarter notes, but the measures will be counted differently as ttw described.
But the bottom number does not always equate to the beat. It just tells you what the top number is referring to. So you can have music in 5/4 with five quarter notes per measure and music in 5/8 with five eighth notes per measure, but these measures will each have a different number of beats - usually 5/4 will have five beats and 5/8 will have two beats of unequal length.
Comment: "the bottom number does not always tell you the number of beats in a measure": in fact, it _never_ tells you that.
Comment: @phoog Thank you. I have clarified my answer.
Comment: And I'm not sure that 6/4 will have six beats; it's more likely to be two (like 6/8) albeit a bit slower. What may be worth pointing out is that 6/4 and 3/2 are not the same thing at all.
Comment: Okay so I'm as guilty of this as everyone else in this thread (and starting to doubt my position as a result of it), but/so -- can anyone actually turn up an example of 6/4 in the wild? I'm kinda starting to think that this is such a rare time signature that any normative comment about its interpretation is, uh, lacking a real norm.
Comment: @PeterSmith Brahms Piano Concerto No.1 first movement and Chopin Prelude Op.28 No.13 are also two examples in 6/4.
Comment: @AndrewLeach Specific ways of interpreting various time signatures is outside the scope of my answer. The main point is in bold.
Comment: Sure, but... 6/4 is still almost never going to be 6 beats. The fact that the finer points of interpretation are "outside the scope of your answer" doesn't mean it's okay to have factual inaccuracies. 7/8 vs. 7/4 is probably the only case where the differing lower numbers most likely indicates a different interpretation (5/8 vs. 5/4 can also be an irregular vs. simple thing, but the majority of 5/4 is irregular).
Comment: @PeterSmith - can't see why 5/8 v 5/4 comes into the equation. They're both irregular - being 5, it has to be. And the 8 or 4 is down to tempo and composer.
Comment: @PeterSmith I have changed the example used in the answer to skirt this controversy. 6/4 can be interpreted multiple ways (which was my point), but I think the debate takes away from the actual point of the post.
Comment: @Tim "irregular" as in "beats of different length". Simple pentuple -- five beats of equal length, divided by powers of two -- is very rare but it certainly does exist, and while a composer "could" write it in 5/8, that's like saying they "could" write the same metre in 10/2 -- it would be highly unusual at best, and most likely harm readability.
Comment: @PeterSmith: I would expect 6/4 to generally have six beats per measure, grouped as a set of four and a set of two, with a stronger quarter-note pulse than would be present in 3/2; I would *not* expect it to have two clear groups of three beats per measure.
Comment: @PeterSmith I agree, it's rare. This little debate inspired me to dig a bit, and I realized I was basing my generalization off the song Footprints by Wayne Shorter, which I first learned from the New Real Book, Vol. 1 published by Sher Music Co. in 1988. It's in 6/4 in that book, but every other source I find seems to be use 3/4. So I think that's my bias.
Answer: You're nowhere near the first, and won't be the last, to be mystified by the numbers shown on time signatures. Maybe they started off rather like fractions - and still look like that, but the numbers are only part of the picture.
As in other answers, the bottom number tells what the denominations are, while the top tells how many of each is contained in each bar. So far, so clear. As in 4/4, the denomination is the crotchet, or quarter note, exactly as it would be in a maths fraction. And the top number (numerator), tells that there are four crotchets per bar. That's perhaps where the confusion starts. There doesn't have to be four crotchets - anything which amounts up to their equivalent is good - two minims, eight quavers, one minim and one crotchet and four semiquavers, or any other of many combinations - as long as they add up to equivalent of those four crotchets.
3/4 works the same way - there are three crotchets (1/4 notes) or equivalent in each bar. Often called 'three quarter time', for good reason. Although I've never come to terms with pieces that don't have any full bars in them, if you understand what I mean!
So far, so good. Then it starts to go awry. Most beginners consider that 3/4 and 6/8 are the same. Yes, and no! True, they work out exactly the same mathematically, but music is more than maths. There had to be a way in which to signify a particular rhythm that went 1 2 3 4 5 6. It couldn't be counted like 3/4 time, as there were six 'beats', or 'sub-beats'. So the top number would be 6. 6 what? Quavers, which then made the bottom 8. Hence 6/8. To me (and my students), it's more of a code that says 'think Humpty Dumpty' (an English nursery rhyme in that rhythm). 12/8 has a similar problem/solution.
So, that bottom number simply tells what sort of notes each bar is going to contain, the top one telling how many of them there will be (or equivalent). There aren't that many different time signatures used regularly, so it may be a good idea just to treat each as its own case, and work from there. Then when 5/4, or 7/4, or 9/8 come along, work them out individually too.
Comment: haha, I more consider 3/4 to be the same as 3/8 and not 6/8. Once I realized that this is true (after seeing some songs written e.g. in both 2/4 and 2/2), I finally understood what the time signature really is.
Comment: @ColeJohnson - if it ain't broke, don't mend it. But if it's music, go with the flow. We're powerless...I stopped looking for complete logic decades ago. Thus I'm only half insane  - at the moment!
Comment: @ColeJohnson in fact, as this answer implies, time signatures did originate as fractions describing the relationship between the note values and the tactus, so 3/2 was 50% faster.  Faster than what?  The fraction was applied to the mensuration sign, which could be a full circle or a broken circle (which looked like a C, giving rise to the symbol that many believe incorrectly to denote "common time"), and which could have a dot inside it or a slash through it (giving rise to the symbol that people associate these days with "cut time"). The logic we use today developed during the early baroque.
Comment: @yo' - that is a good way to regard it!
Comment: Please write a book, Tim!
Comment: @yo': The first piece I encountered in 3/8 time was "I feel pretty", from West Side Story, which the director conducted with one baton stroke per per dotted-quarter-note measure.  If one were to drop about half of the bar lines, the piece could have been in 6/8 but with occasional 3/8 measures at the ends of odd-length phrases.
Comment: It's understandable why people see them as fractions. We refer to 3/4 as "three _quarter_ notes," but give no reference as to what a "whole note" is. In 6/4, a "whole" note only takes up 2/3 of the bar. "But it's a _whole_ note, no?" one might ask, "So it should take up all _six_ beats, not four!" The language could be better, IMO, but after a few months of interacting with different time signatures, it becomes second nature.
Comment: @cmp - I'll try again, as the last response disappeared. About what in particular? Wonder how long this will last - and  why the last one disappeared, at whose hands...Anonymity is a wonderful thing.
Comment: @Tim Comments do disappear yes, I thought I was going mad. "Not for extended discussion, moved to chat" will follow shortly I expect ;-) You just have a very good way with explaining the basics without complication. It's hard to do, most can explain simply but explaining trying topics and being clear at the same time is hard to do.
Comment: A great answer.  I was considering something similar.  It is tempting to view time signatures mathematically but it's not really useful.  A knowledge of maths can be helpful for understanding music but it can also lead you astray.  This is a case.
Answer: The denominator represents the note that would get a single beat. In 4/4 time, there are 4 quarter-notes (or crochets) worth of time in a single measure. Although the measure is 4 crochets long, any notes that add up to the correct length are fine. The measure could have 8 eighth notes (8 quavers) or 2 minims or 1 semi-breve or 3 quavers plus a crochet and three more quavers.
In simple time signatures (4/4, 3/4, 3/2, 2/4, 3/8...) the lower number gives the pulse-unit and the upper number gives the number of such units in a measure. It helps to organize the music (it's easier to think of 4 objects than 47 objects, usually). There is an implied accent on the first beat of 2/4 and 3/4 and an implied light accent on the beat 3 of a 3/4 measure. This becomes important with other time signatures. All this is has been historically developed. For example, 6/8 not only means 6 quavers in a measure but also signifies that these are grouped into two groups of three.  (Mostly I mention this to show that 3/4 is not equivalent to 6/8.)
Comment: A bit concerned about 4/4 having '3 quavers, a crotchet and 3 more quavers'. True, a lot is written like that now, but it's better if 4/4 bars can be seen to have two halves. A lot of us understand what you meant, but a beginner? Just being pedantic!
Comment: When using the word *denominator* for the number below, I think one can use the word *numerator* for the number above. In fact, a time signature with 3 as upper number and 4 as lower number means a 3/4 measure, which literally means that each bar fits notes and pauses which sum up to 3/4, as in a [fraction](https://en.wikipedia.org/wiki/Fraction).
Comment: Your 1st para.: in 6/8, the 8 doesn't really represent a single beat. It *could*, but often a dotted crotchet does instead. Trouble is, there's no denominator for dotted crotchet...
Comment: @rexkogitans - those terms can be used, although the numbers don't really mean those words as it's not maths. Although funnily enough, here we all are, typing them as fractions!
Answer: The textbook answer I always received was, "The top number tells you how many beats per measure, and the bottom number tells you what value note receives one beat."  So 3/4 time means "three beats per measure, and a quarter-note receives one beat."  That tells you that each measure will contain three quarter-notes or the equivalent thereof.
From my point of view as a hobby musician (I don't read music very well), I look at it this way:  The top number gives you the rhythmic feel of the song, which is generally the most important thing to know.  The top number can (theoretically) be any integer, but the most common ones are 2, 3, 4, 6, 8, and 12.  Occasionally you'll see other numbers, such as 5, 7, and 9.  There's a Wikipedia article that lists lots of songs with unusual time signatures, with "unusual" most often defined in terms of the top number.
The bottom number is more about how the composer chose to write the actual sheet music, in conjunction with the feel given by the top number.  If the composer found it easier (or more explanatory) to write most passages using quarter-notes, the bottom number will more likely be a 4.  If eighth-notes better suit the composition, the bottom note will be an 8.  It's largely a judgement call.  Sometimes composers will write in unusual time signatures as an exercise, and sometimes an unusual time signature will be used to add an extra beat (or two or more) to a phrase.  Both of these cases can be seen in the above-linked Wikipedia article.
Often I will try to reverse-engineer a song without referring to the original sheet music.  The most frequent variable I've encountered when doing so is whether the bottom number is a 2 or a 4, but I've also found some variability between 4 and 8.  There can also be ambiguity about the top number:  I've sometimes thought a song was in 2/4 when it turns out to have been written in 4/4.  I've also sometimes thought a song was in 3/4, 6/8, or 12/8, only to find that it's written in X/4 time, with lots of triplets.  (A triplet is when a note's time is divided into three notes, usually written as three barred eighth-notes with a small number 3 above or below the bar. Think of the "merrily, merrily, merrily, merrily" part of "Row, Row, Row Your Boat.")
But another very important factor is something the OP didn't ask about:  the tempo notation.  On sheet music you'll often see, at the top of the piece, a quarter-note followed by an equal sign followed by a number, as shown here:

This gives us very firm guidance on the tempo of the song:  90 quarter-notes (or 90 beats) per minute.  You can set that number on a metronome and you'll know that you're at the tempo the composer wanted.  But nearly as often, you'll just see a verbal description of the tempo, such as "Moderately," "Brightly," "Quickly," or some such.  Most classical compositions use Italin words to describe the tempo, such as "Andante," "Presto," "Lento," and so forth.  Classically trained musicians develop a feel for what each of these means, but there are also guidelines available through a simple online search.
Answer: The bottom number may be thought of as the unit of measure, while the top is the measurement.  Changing the bottom number (for example from 3/4 to 3/2) is analogous to changing a distance from 3 mm to 3 cm.  The number of units is the same, but the size of the unit is different.  With time signatures, however, it is a factor of two rather than a factor of ten.

for example 4/4 is telling me the crotchet is the kind of beat, and yet crotchets don't need to be used.

Suppose you're covering a tear in a sheet of paper with adhesive tape.  The total length of the tear is 4 cm.  That doesn't mean that you need to use four 1-cm pieces of tape to cover the tear!  You can use any combination of different lengths of tape as long as the sum of all the lengths is 4 cm.  Similarly, when the time signature says that a measure has a total duration of a 4 crotchets, that means that the notes (and rests) in the measure must sum to the same duration as four crotchets.
It may be that time signatures are a bit more intuitive if you use the American system (which we got from German music teachers) wherein a semibreve isn't worth 4 but 1 (a "whole note"), and a crotchet isn't worth 1 but 1/4 (a "quarter note").  You can still ascribe these values to the notes even if you continue to call them by their traditional English names.

At this point I'm starting to ignore the bottom number and only rely on the top number (number of beats) as that seems to be the only thing that matters rule-wise.

That is a fairly reasonable way to approach it, but the bottom number does have useful information.  Time signatures that are mathematically equivalent when considered as fractions do specify the same total duration of each measure, but they are not equivalent because they also give information about how the measure is organized.
The clearest example of this is 3/4 vs 6/8.  In both cases, a measure filled with quavers would contain 6, but in the first case, they would normally be grouped in three groups of two, while in the latter case they would be in two groups of three.
Another example is 4/4 (often given as C) as opposed to 2/2 (often given as C with a vertical line).  In both cases, a measure full of quavers has 8 of them, but in the first case, if you're tapping along with the music you'd tap four times in each measure, on every other quaver, and in the second case you'd tap at half the rate, twice in each measure, on every fourth quaver.
Comment: So why not call it the German system?
Comment: @mirabilos I suppose it is because English speakers are most commonly exposed to the system through its use by Americans.
Answer: You can think of the time signature as describing the length of the bar as a fraction of a whole note.
Let's use American (whole note, quarter note etc.) names.  It helps in explaining time signatures!
4/4 is 4 X quarter note.   A 4/4 bar adds up to a whole note.   Fill it with any combination of whole, half, quarter, eighth notes (or rests) that you like, as long as it all adds up to a whole note.
3/4 will add up to 3 X quarter note.    6/8 will add up to 6 X eighth notes.    But remember, that doesn't mean there MUST be 6 X eighth notes in each bar, just notes and rests that add up to that.   Remember those 'how many ways can you make up a dollar from coins' questions at school?  Same idea.  And yes, I'm sure you just noticed that 3 X quarter notes and 6 X eighth notes add up to the same thing.  Read on...
Now, it can get more complicated than a simple count-up.   We use both 4/4 and 2/2 time signatures.  Both add up the same.  Two halves or four quarters both add up to one whole.   And you'll see both 3/4 and 6/8.   Both add up the same.  And I'd love to be able to tell you that 3/4 means three quarter-note beats in the bar, 6/8 means six eighth-note ones.  But 6/8 is actually TWO beats in the bar, two groups of three eighth-notes each.
I can't throw this all at you in one post and expect you to understand.   Get a music rudiments textbook and work through it from the beginning. Most of all, PLAY music written in different time signatures.  You can't learn notation apart from playing it.  Would be like learning the letters but never reading a book!
Answer: The bottom number is a naming convention: in n/4 you decided to consider the "basic note" (not an official term!) to be a 4th note (aka crotchet), in n/8 you decided that to be an 8th note (quaver). But other than that, 4/4 and 4/8 are basically the same thing.
The only information the composer gives in the bottom number is some (rough) idea about how heavy the "basic note" is: you'll hardly have all 8th notes heavy even if it's the basic note, but it's completely expected for a half note (minim) to be heavy. But that's already a feeling you might have.
The top number is how many of the "basic notes" you count in each bar. And there are some common conventions (non-strict conventions!) considering how "basic notes" and "beats" compare:

2/d and 6/d is commonly 2 equally long beats (unless 2/d has only one beat per bar)
3/d is 1 or 3 (or two, first one twice as long as the second one, 2+1)
4/d and 12/d is 4 (or three as 1+2+1)
8/d could be e.g. 3+3+2, but also 8*1, it really depends.

The bottom line: When looking at music, consider 3/4 to be closer to 3/8 with doubled notes than to 6/8.
Answer: The number below the time signature or bottom number of a time signature indicates which note gets the beat that is equivalent to one beat by which the length or value of notes like; Whole note,Half note, Quarter note etc will be decided(except compound time).Since no note has a set duration, the value of all notes without the bottom number or beat unit is zero.So
bottom number of a time signature plays a very important roll in a music piece that says how a music will be counted and played.
Comment: 'No note has a set duration'? That kind of confuses me. A  semibreve has a time value of 4 beats right?

And it's still confusing how people describe the bottom number of a time signature as indicating 'which note gets the beat'. This is one thing in music theory that I don't get, no matter how many times people explain it the exact same way. I need an adult to explain it to me like I am a toddler at this rate.
Comment: I'd like to tell you that a whole note or semibreve would be equal to 4 beats only when the quarter note or crochet becomes the beat unit which is equivalent to one beat,such as; in 4/4, 3/4, 2/4 etc  time signatures quarter note gets the beat because bottom 4 represents quarter notes as whole notes relative value. As we know the quarter note is 1/4 of a whole note and for the same reason a whole note's value is equal to 4 beats.If half note becomes the bottom number of the time signature like 4/2, 2/2 ...then whole note is 2 beats long. To know more you can contact me at 91 7980292419(India).
Answer: Time Signatures aim to tell us what the beat is and how many beats there are in a measure. There are two types of time signatures. Compound and Simple. Compound means the beat has a dot and Simple means it does not.
You get as a basis two, three, and four time. You also get beats of quavers (8th notes), crotchets (quarter notes), and minims (half notes). Each with a time signature with and without a dot.


JQuery Post to ASP.NET Core results in CORS error

Question: I have an ASP.NET Core API and a html-css-js client side. I try to send a post request to said API, but Firefox throws an error that the same origin policy forbids reading of external resource.
The Startup.cs looks like this:
public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddControllers()
            .AddNewtonsoftJson(options =>
                   {
                       options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                   });

    IGameManager gameManager = new GameManager();

    services.AddTransient<IGameManager>(gm => gameManager);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors(options =>
                   options.WithOrigins("https://localhost:44314").AllowAnyMethod());
    app.UseHttpsRedirection();
    app.UseRouting();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
                         { endpoints.MapControllers(); });
}

And the jQuery request:
var data = {
    Name : "Test"
};
$.ajax({
    type: "POST",
    url: "https://localhost:44314/api/test",
    data: data,
    success: (data, status, xhr) => {alert("SUCCESS!")},
    contentType: 'application/json',
    dataType:'json'
  });

I know the url and body are correct, I can see the API reacting by initializing the corresponding controller and I think I get a ACK response for the connection:

But before even entering the Method with the Attribute [HttpGet] Firefox throws the error.
When I do the same request in Postman, everything works just fine, though I could imagine, that postman routes every request through their servers, with would eliminate any CORS problems.
Interestingly I get two errors: (sorry, they are German)
Comment: have you try `builder.WithOrigins("https://localhost:44314").AllowAnyHeader().AllowAnyMethod();`
Comment: I tried your suggestion, but it sadly didn't change anything
Comment: have you the same problem with chrome...?
Comment: Using Chrome does not work either:
Access to XMLHttpRequest at 'https://localhost:44314/api/test' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Comment: at least you are sure the problem is coming from your program settings
Comment: Do I? I'm not sure, what causes the problem
Comment: you are using https so, make sure the servers have valid and trusted SSL certificates. Even if CORS is enabled correctly on the server, some browsers (such as Firefox) do not complete cross-origin requests if the SSL certificate itself is invalid.
Comment: Ah yes, I already checked that. I made an exception inside of firefox. But I got it working now and posted an answer. Thank you all für your suggestions! :)
Answer: Alright, so changing the code from
app.UseCors(options =>
   options.WithOrigins("https://localhost:44314").AllowAnyMethod());

to
app.UseCors(
   options => options
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
  );

did the trick. Apparently the url I had provided as an exception was not correct (?). I still don't know, WHY my code didn't work, but this is the solution for me. If someone can explain, what I did wrong, please leave a comment, I would like to know!


Change IAP type

Question: I accidentally registered an IAP as nonconsumable, supposed to be consumable.
The app is not yet submitted. But it seems there is no way to edit the type. All we can do now is delete the IAP and create another one, right? The problem here is the IAP product ID cannot be reused so with each mistake like this a new IAP product ID has to be created...
No workaround?
Comment: Yes, delete & add a new one.
Comment: Ok... it is a bit inconvenient, especially in this case cause this app is created by a 3rd party and we have to ask them to change the hardcoded IAP product ID just because of this :-/ We have to run an extra lap. Dohhh
Answer: Only solution: delete & add a new one
Note that a new unique product ID has to be used.

Change IAP type


How to convert a JSON string into object in Cucumber

Question: I have a Java 8 Spring-batch application with Cucumber testing framework.
<code>Spring 4.3; cucumber-juni 1.2.5; cucumber-java 1.1.8
</code>
My backing class implements a Spring Framework Rest Template, which calls the api under test and returns a rather large JSON string.
My question is - what facilities come packaged in Cucumber framework for converting the JSON payload into a POJO?
I'd really appreciate an example on how to do that in Cucumber without bringing in other dependencies from outside, please.
Answer: There is nothing (as far as I know) in Cucumber to do this. Its just not something Cucumber should be doing. However you can easily get Cucumber to call something that will do this for you by writing a helper method that your step definitions can use to do this.
You have the whole of your programming language available to you in your step definitions. Use that to convert responses into POJO's if thats what you need to do.
Comment: Thx - just making sure I'm not overlooking into something that already exists.


How do you remove a user's input from a list?

Question: I am working on this code and I cannot get the "removeLetter" to delete the letter the user chooses from the "chosen" list. I figured out I can't use list functions with strings, but I don't know how to go about making the
start.remove() code to work without converting the user's string input to match the item he/she would like to be removed from the "chosen" list. Can someone help me please?
import random

oneList = "a ", "b ", "c "
twoList = "d ", "e ", "f "
threeList = "g ", "h ", "i "
fourList = "j ", "k ", "l "

# Selects a letter at random from each list
oneRandom = random.choice(oneList)
twoRandom = random.choice(twoList)
threeRandom = random.choice(threeList)
fourRandom = random.choice(fourList)

# Displays chosen letter from each list
print("These are your letters.")
chosen = oneRandom + twoRandom + threeRandom + fourRandom
print(chosen)

# First user input
start  = input("Would you like to remove a letter? y or n? ")

# If start = yes then do this.
if start == 'y':
    removeLetter = input("What letter would you like to remove? ")

    # Removes user's chosen letter.
    keptLetters = chosen.remove(removeLetter)

    # Displays kept letters.
    print(keptLetters)

Comment: You might be getting tripped up because `oneList` through `fourList` aren't lists, they're tuples. Importantly, lists can be mutated (for example, items can be removed from them), and tuples can't.
Comment: lists are surrounded by `[]`, try running `type()` and you will see what @Kevin is saying
Comment: Also, instead of doing `start.remove`, you probably want to slice out from `chosen` instead.
Answer: You have an error in your code specifically in this line:
keptLetters = start.remove (removeLetter)

You are calling the variable start but the variable chosen is the one with the list of letters. So this should work:
keptLetters = chosen.remove (removeLetter)

Comment: There's more issues than that. Especially since `chosen` is a string.
Comment: @Anderson Although that was a valid error you pointed out along with, I am still having trouble. I should've realized that I am also using tuples like others have said .Do you have any other suggestions?
Comment: look this https://stackoverflow.com/questions/21682804/pop-remove-items-out-of-a-python-tuple
Answer: You have a few issues in your code. I took the liberty to make it more pythonic for you.
Python 2
import random

letter_sets = (("a", "b", "c"),
               ("d", "e", "f"),
               ("g", "h", "i"),
               ("j", "k", "l"))

# Selects a letter at random from each list
chosen = map(random.choice, letter_sets)

# Displays chosen letter from each list
print "These are your letters."
print " ".join(chosen)

# First user input
start = raw_input("Would you like to remove a letter? y or n?")

# If start = yes then do this.
if start[0].lower() == 'y':
    while(len(chosen) == 4): #Keep looping until a letter is chosen
        removeLetter = raw_input("What letter would you like to remove?")
        try:
            # Removes user's chosen letter.
            chosen.remove(removeLetter)
            # Displays kept letters.
            print " ".join(chosen)
        except ValueError: #If removeLetter is not in chosen
            print removeLetter, "is not in the list of letters"

Python 3
import random

letter_sets = (("a", "b", "c"),
               ("d", "e", "f"),
               ("g", "h", "i"),
               ("j", "k", "l"))

# Selects a letter at random from each list
chosen = list(map(random.choice, letter_sets))

# Displays chosen letter from each list
print("These are your letters.")
print(" ".join(chosen))

# First user input
start = input("Would you like to remove a letter? y or n?")

# If start = yes then do this.
if start[0].lower() == 'y':
    while(len(chosen) == 4): #Keep looping until a letter is chosen
        removeLetter = input("What letter would you like to remove?")
        try:
            # Removes user's chosen letter.
            chosen.remove(removeLetter)
            # Displays kept letters.
            print(" ".join(chosen))
        except ValueError: #If removeLetter is not in chosen
            print(removeLetter, "is not in the list of letters")

Having multiple lists, and repeating your code is not very pythonic. So I've made the "lists" as a tuple of tuples (since you may not plan on modifying this). If so, then change to lists by denoting them with square brackets [] instead of parentheses ().
Since you're performing the same operation on multiple lists, you can use the map() function to get the results from all of them into a list.
chosen should remain a list, instead of a string, since you'll be manipulating it in the future by removing a letter.
You can easily join() all the items in a list together as a string separated by a single space " ".
Since list.remove() can send back a ValueError if the value isn't in the list, you'll want to handle that in a try..except block.
Can surround your logic with a while loop to keep asking for a letter to remove if the previous attempts failed.
chosen.remove changes the original array, so you don't need to save it into keptLetters.

I hope this helps you out!
Edit: Added equivalent Python 2 code
Comment: I appreciate this and think I understand what you are saying. However, I get this error with your code. Traceback (most recent call last):
  File "G:\lettersTwo.py", line 25, in
    removeLetter = input("What letter would you like to remove?")
  File "", line 1, in
NameError: name 'b' is not defined
Comment: Are you *sure* you copied the code correctly? I assume you're running Python 3. I made a [repl](https://repl.it/repls/BiodegradableSpryConference) for this.
Comment: Alright, I am sorry. I was actually running Python 2. I don't know why I still have it. I do have 3 installed though. Your program worked thank you!
Comment: @NickAndrulewicz, I updated my answer for Python 2. `map` result is a bit different, and `input` does as well. You can see in this [repl](https://repl.it/repls/WorseScholarlyIntercept). Please accept the answer if you feel like it has helped!
Answer: Je pense que sa  doit être ça
import random oneList = "a ", "b ", "c "
twoList = "d ", "e ", "f "
threeList = "g ", "h ", "i "
fourList = "j ", "k ", "l "
# Selects a letter at random from each list
oneRandom = random.choice(oneList)
twoRandom = random.choice(twoList)
threeRandom = random.choice(threeList)
fourRandom = random.choice(fourList)
# Displays chosen letter from each list
print("These are your letters.") chosen = oneRandom + twoRandom + threeRandom + fourRandom print(chosen)
# First user input
start = input("Would you like to remove a letter? y or n? ")
# If start = yes then do this.
if start == 'y': removeLetter = input("What letter would you like to remove? ")
# Removes user's chosen letter.
keptLetters = chosen.remove(removeLetter)
# Displays kept letters.
print(keptLetters)


GetHashCode() problem using xor

Question: My understanding is that you're typically supposed to use xor with GetHashCode() to produce an int to identify your data by its value (as opposed to by its reference). Here's a simple example:
class Foo
{
    int m_a;
    int m_b;

    public int A
    {
        get { return m_a; }
        set { m_a = value; }
    }

    public int B
    {
        get { return m_b; }
        set { m_b = value; }
    }

    public Foo(int a, int b)
    {
        m_a = a;
        m_b = b;
    }

    public override int GetHashCode()
    {
        return A ^ B;
    }

    public override bool Equals(object obj)
    {
        return this.GetHashCode() == obj.GetHashCode();
    }
}

The idea being, I want to compare one instance of Foo to another based on the value of properties A and B. If Foo1.A == Foo2.A and Foo1.B == Foo2.B, then we have equality.
Here's the problem:
Foo one = new Foo(1, 2);
Foo two = new Foo(2, 1);

if (one.Equals(two)) { ... }  // This is true!

These both produce a value of 3 for GetHashCode(), causing Equals() to return true. Obviously, this is a trivial example, and with only two properties I could simply compare the individual properties in the Equals() method. However, with a more complex class this would get out of hand quickly.
I know that sometimes it makes good sense to set the hash code only once, and always return the same value. However, for mutable objects where an evaluation of equality is necessary, I don't think this is reasonable.
What's the best way to handle property values that could easily be interchanged when implementing GetHashCode()?

See Also
What is the best algorithm for an overridden System.Object.GetHashCode?
Answer: First off - Do not implement Equals() only in terms of GetHashCode() - hashcodes will sometimes collide even when objects are not equal.
The contract for GetHashCode() includes the following:

different hashcodes means that objects are definitely not equal
same hashcodes means objects might be equal (but possibly might not)

Andrew Hare suggested I incorporate his answer:
I would recommend that you read this solution (by our very own Jon Skeet, by the way) for a "better" way to calculate a hashcode.

No, the above is relatively slow and
  doesn't help a lot. Some people use
  XOR (eg a ^ b ^ c) but I prefer the
  kind of method shown in Josh Bloch's
  "Effective Java":
public override int GetHashCode()
{
    int hash = 23;
    hash = hash*37 + craneCounterweightID;
    hash = hash*37 + trailerID;
    hash = hash*37 + craneConfigurationTypeCode.GetHashCode();
    return hash;
}

The 23 and 37 are arbitrary numbers
  which are co-prime.
The benefit of the above over the XOR
  method is that if you have a type
  which has two values which are
  frequently the same, XORing those
  values will always give the same
  result (0) whereas the above will
  differentiate between them unless
  you're very unlucky.

As mentioned in the above snippet, you might also want to look at Joshua Bloch's book, Effective Java, which contains a nice treatment of the subject (the hashcode discussion applies to .NET as well).
Comment: @ja72: yes, it probably should be in an unchecked block.  The default is unchecked, but a compiler option (or runtime  environment setting?) can change that default.
Comment: This is a very good answer and highlights some important points. however it is lacking an example.  If you wish, please edit your answer to include my example (or something similar) and I will delete my answer.  (+1, by the way).
Comment: Does this need to be in an unchecked block?
Comment: Done - and wiki'ed the answer as a result.
Comment: the link to 'this solution' is dead, [here is the new link](http://www.aspnet-answers.com/microsoft/Csharp/29483139/override-gethashcode.aspx)
Comment: So it does not _need_, but it would be good for code clarity.
Comment: Also would it work with `^` (xor) in place of `+` (add). Like `37*x ^ y ..`
Answer: Andrew has posted a good example for generating a better hash code, but also bear in mind that you shouldn't use hash codes as an equality check, since they are not guaranteed to be unique.
For a trivial example of why this is consider a double object. It has more possible values than an int so it is impossible to have a unique int for each double. Hashes are really just a first pass, used in situations like a dictionary when you need to find the key quickly, by first comparing hashes a large percentage of the possible keys can be ruled out and only the keys with matching hashes need to have the expense of a full equality check (or other collision resolution methods).
Answer: Hashing always involves collisions and you have to deal with it  (f.e., compare hash values and if they are equal, exactly compare the values inside the classes to be sure the classes are equal).
Using a simple XOR, you'll get many collisions. If you want less, use some mathematical functions that distribute values across different bits (bit shifts, multiplying with primes etc.).
Answer: Read Overriding GetHashCode for mutable objects? C# and think about implementing IEquatable<T>
Answer: There are several better hash implementations.  FNV hash for example.
Answer: Out of curiosity since hashcodes are typically a bad idea for comparison, wouldn't it be better to just do the following code, or am I missing something?
public override bool Equals(object obj)
{
    bool isEqual = false;
    Foo otherFoo = obj as Foo;
    if (otherFoo != null)
    {
        isEqual = (this.A == otherFoo.A) && (this.B == otherFoo.B);
    }
    return isEqual;
}

Comment: Yes, but if I had 50 properties I was trying to compare, this would get pretty ugly. I was hoping to just implement GetHashCode() and then leave Equals() nice and simple. It appears this might be a pipe dream.
Answer: A quick generate and good distribution of hash
public override int GetHashCode()
{
    return A.GetHashCode() ^ B.GetHashCode();         // XOR
}

GetHashCode() problem using xor


MySQL Count that includes months not within the date range

Question: Supposed I have a table that contains the following table:
+----+-----------+---------+-------------------------+
| id |  item     |  ....   | dateLogged              |
+----+-----------+---------+-------------------------+
|  1 | 2015-001  |  ....   | 2015-06-01 12:09:00     |
|  2 | 2015-001  |  ....   | 2015-06-01 12:09:00     |
|  3 | 2015-002  |  ....   | 2015-06-30 15:40:02     |
|  4 | 2015-002  |  ....   | 2015-06-30 15:40:03     |
|  5 | 2015-003  |  ....   | 2015-07-02 13:38:22     |
+----+-----------+---------+-------------------------+

I want to search the number of items based on the year, month and count from the dateLogged, with the expected data:
+--------+----------+----------------+
| year   |  month   |     total      |
+--------+----------+----------------+
|  2015  | January  |      0         |
|  2015  | February |      0         |
|  2015  | March    |      0         |
|  2015  | April    |      0         |
|  2015  | May      |      0         |
|  2015  | June     |      4         |
|  2015  | July     |      1         |
|  2015  | August   |      0         |
|  2015  | September|      0         |
|  2015  | October  |      0         |
|  2015  | November |      0         |
|  2015  | December |      0         |
+--------+----------+----------------+

But I am only getting this based on the following SQL:
SELECT DATE_FORMAT(dateLogged, '%Y') as 'year', MONTHNAME(dateLogged)
as 'month', COUNT(id) as 'total' from item a where dateLogged >= '2015-06-29 00:00:00'
and dateLogged <= '2015-07-02 23:59:59'
GROUP BY DATE_FORMAT(a.dateLogged, '%Y%m');

+--------+---------+----------------+
| year   |  month  |  No of items   |
+--------+---------+----------------+
|  2015  | June    |      4         |
|  2015  | July    |      1         |
+----+-------------+----------------+

I've tried searching elsewhere from stackoverflow, but wasn't able to get any answers, or probably have missed. Wanna know if there is any solution to this, thanks.
I am using Java to compute this, so any suggestions using Java to compute the above is also welcomed.
Comment: Just handle the logic of the missing dates in Java
Answer: You could change your query to return the 0 values as well using loops to iterate over months and years and then find the count. Something like this:
Map<String, Integer> values = new HashMap<String, Integer>();
for(int year = 2015; year < 2017; year++)
{
    for(int month = 1; month <= 12; month++)
    {
        rs = stmt.executeQuery("SELECT COUNT(id) as 'total' from item where
                 MONTH(dateLogged) = " + month + " and YEAR(dateLogged) = " + year + ";";
        rs.next();
        int count = rs.getInt("total");
        String time = Integer.toString(year) + "-" + Integer.toString(month);
        values.Add(time, count);
    }
}

This would return you a map like this:
values['2015-1'] = 0;
values['2015-2'] = 0;

.. and so on.
Of course, you could store the returned count with year and month however you want, depending on how you wish to use it further.
Answer: One idea is to, somehow, create a calendar table, and use it, so that you get a row for each month of year 2015:
SELECT DATE_FORMAT(m, '%Y') as 'year',
       MONTHNAME(m) as 'month',
       COUNT(id) as 'total'
FROM (SELECT '2015-01-01' AS m UNION ALL SELECT '2015-02-01' UNION ALL
      SELECT '2015-03-01' UNION ALL SELECT '2015-04-01' UNION ALL
      SELECT '2015-05-01' UNION ALL SELECT '2015-06-01' UNION ALL
      SELECT '2015-07-01' UNION ALL SELECT '2015-01-08' UNION ALL
      SELECT '2015-09-01' UNION ALL SELECT '2015-10-01' UNION ALL
      SELECT '2015-11-01' UNION ALL SELECT '2015-12-01') AS x
LEFT JOIN item a
ON DATE_FORMAT(a.dateLogged, '%Y%m') = DATE_FORMAT(x.m, '%Y%m')
   AND dateLogged >= '2015-06-29 00:00:00'
   AND dateLogged <= '2015-07-02 23:59:59'
GROUP BY DATE_FORMAT(x.m, '%Y%m');

The above query makes use of sort of an inline calendar table for year 2015. This table is used as a basis in the FROM clause, so that the query returns a row for each of the months of year 2015.
Demo here
Comment: Based on the above SQL, is it possible to make the "SELECT '2015-01-01' AS m UNION ALL SELECT '2015-02-01' UNION ALL..." dynamic? i.e. as the dateLogged >= startDate and dateLogged <= endDate (The startDate and endDate is dynamic, so it is possible to do the list dynamically?)
Comment: @progricebowl You can create calendar tables of any date range, but it gets more complicated as you have to use variables for this purpose.


Generating function for sequence

Question: I just need confirmation on whether I am approaching this question correctly.I am not sure how to simply $\sum nx^n$ though. Would it be $\frac{6x}{(1-x)^2} ?$
Find the generating function for:
$$ a_n = 6n + 2018 $$
My solution:
$$ \sum a_nx^n = \sum6nx^n+ \sum2018x^n $$
$$\sum a_nx^n  = \sum6nx^n+ \sum2018x^n$$
$$ g_{an}(x) = 6\sum nx^n+ 2018\sum x^n + a_0$$
$$ g_{an}(x) = \frac{6x}{(1-x)^2}+ \frac{2018}{1-x} $$
Any guidance would be greatly appreciated.
Answer: You are correct that $\sum nx^n=x/(1-x)^2$. Here's how you derive this. Starting from $1/(1-x) = \sum_n x^n$, differentiate both sides, obtaining
$$
\frac1{(1-x)^2}=\sum nx^{n-1},
$$
then multiply both sides by $x$.

By the way, you shouldn't subtract $a_0$ from the left hand side, the correct equation is
$$
\sum a_nx^n = \sum 6nx^n + \sum2018 x^n
$$
The only time you subtract $a_0$ is when you have a recurrence equation, like $a_{n+1} = 2a_n +1$.
Comment: That makes sense to me. Thank you!

Generating function for sequence


Taxonomy filter exposed to user that dynamically only includes terms attached to currently published content

Question: Background:
a) Taxonomy: I have built as site that allows users to tag content of a particular content type with tags.  The system started with a pre-existing taxonomy before any content was added, but has grown organically as users add content and terms of their own.  What this means, of course, is that at any time, some of the terms in the taxonomy, may not be attached to any currently published content.
b) View with Exposed Tag Filter:  As a means to allow users to find material of interest, I have exposed the Tag Field as a filter for a tabular view of the content.  The Filter is a drop down list.  When a user selects a tag from the list, the view is appropriately filtered to the matching items.
Problem:
As the taxonomy has grown, a good proportion are not, at any time, attached to any content.  Thus, it is frustrating for the user to filter the table with a tag list that includes these terms, as they yield 0 results.
Requested Help:
Therefore, I am looking for a way, that the terms shown in the tag filter are dynamically limited to only those that are attached to currently published content.  It is not clear to me how to do it.  I would greatly appreciate any advice on how this may be accomplished.
Answer: You should have a look at Views Selective Exposed Filters, part of the Views Hacks module. It will limit the taxonomy terms to those in your view's result set.
Comment: Thanks. The module certainly intends to address the issue that I'm trying to solve.  However, the "Limit list to result set" checkbox doesn't get added to the filter options after the module has been installed. Perhaps this is a known bug in the alpha software?  Any insights into known bugs and workarounds for the module?  I don't think I'm doing anything unusual with the filters or taxonomy in the view I've constructed.
Answer: The best answer would be:
Search API Views.
List of nodes using faceted taxonomy term filters. By default faceted taxonomy filter will show only for terms 'in use'.
Still, if you really need to show a filter to terms only in published nodes, I believe this is gonna be achieved by code using some hook to alter the facets, or, automatically, if the current user does not have permission to view unpublished nodes the facet filter won't show the term.


how do I dynamically create an object tag with jquery and add alternate content to it?

Question: I am trying to embed a pdf into my webpage using an object that will fallback to an iframe which loads the pdf through an external rendering service for users that do not have acrobat installed.
I am trying to do it like this:
var container = document.createElement("div");
var object = document.createElement("object");
var iframe = document.createElement("iframe");

$(container).append(object);
$(object).append(iframe);
$("body").append(container);

This works in firefox but causes an error in IE in the jquery core code.  It breaks when I append the iframe to the object.
I need to create the content in a way that will give me access to both the object and the iframe element because I do not have a reliable way to detect if the user has acrobat or not, so I am depending on the browser to display the correct content and just styling both the iframe and the object so that either one will look okay.
What is an alternate and cross-browser approach?
Answer: have you tried it like this?
var object = $("<object>");
var container = $("
").append(object);
$(object).append("");
$("body").append(container);

Comment: It causes the same error for me in IE.  Does it work for you?  It fails if I try to use $(object).html("") as well.

This is the error-- Invalid argument. (line 4075) (jquery-1.4.2.js):

 append: function() {
  return this.domManip(arguments, true, function( elem ) {
   if ( this.nodeType === 1 ) {
    this.appendChild( elem );
   }
  });
 },


Who was the man of the series for the India vs New Zealand test match series 2014?

Question: I want to know who got the man of the series award for the India vs New Zealand test match series 2014.
I can't find that in cricinfo.
Comment: Both the man of the match for 2nd test as well as man of the series was Mccullum
Comment: It might be Mccullum.
Comment: McCullum scored a double century in the first test, and a NZ record 302 in the second of the two test series. Man of the Series is rather an understatement, I would think.
Answer: They have not awarded a man of the series award.
Look at the commentary of awards presentation. Only MoM is awarded. http://www.espncricinfo.com/new-zealand-v-india-2014/engine/match/667653.html?innings=4;page=2;view=commentary
Comment: Ya, they havent awarded Man of the Series award source: http://www.bcci.tv/match/nz-ind-2014/07
Answer: As per BCCI.TV Brendon McCullum was declared man of the series. Go to Match Home tab -> In the commentary box, search for "Man of the Series".
Here it is clearly written: "Man of the Series: Brendon McCullum". See the screenshot here.
Comment: Will you please point me to that please...i am trying to find but couldn't
Comment: @Jatin - As I have pointed in the answer Go to the `Match Home` tab -> Here in the `Match stream` you can see "**Man of the Series**: Brendon McCullum" See my updated answer.


Valores dos atributos de um objeto duplicados

Question: Estou com o seguinte problema, tenho uma classe chamada Cliente com vários atributos e uma classe chamada DAO_Cliente que retorna um determinado cliente (MySQL). O problema é quando eu tento colocar os valores nos atributos desse objeto, ou seja, quando eu seto o $id e o $nome (somente) por exemplo todos os atributos ficam com valor do NOME, assim como se eu setar o atributo $telefone1 novamente todos os atributos ficaram com o valor do TELEFONE. Estou usando o php4.
Segue abaixo a estrutura das classes:
Classe Cliente:
<?php
    include_once "endereco.php";

    class Cliente{
        public $id;
        public $nome;
        public $dataNasc;
        public $cpf;
        public $identidade;
        public $oEndereco;
        public $telefone1;
        public $telefone2;
        public $referencia;
        public $status;
        public $inscricaoEstadual;
        public $celular;
        public $email;
        public $dataVencimento;
        public $dataVisitaTecnica;
        public $valorMensalidade;
        public $regimeTributario;
        public $observacao;
        public $qtdeEcf;
        public $modelo;
        public $possuiNFe;

        function __construct() {
            $id = 0;
            $nome = '';
            $dataNasc = 0;
            $cpf = '';
            $identidade = '';
            $oEndereco = new Endereco();
            $telefone1 = '';
            $telefone2 = '';
            $referencia = '';
            $status = '';
            $inscricaoEstadual = '';
            $celular = '';
            $email = '';
            $dataVencimento = 0;
            $dataVisitaTecnica = 0;
            $valorMensalidade = 0;
            $regimeTributario = '';
            $observacao = '';
            $qtdeEcf = 0;
            $modelo = '';
            $possuiNFe = '';
        }
    }
?>

Classe Dao_Cliente:
    <?php
    include_once "../conexao.php";
    include_once "../model/cliente.php";

    class DAO_Cliente{
        public function consultar($lcodCli){
            $lconexao = conexao::getInstance();
      $sql = "SELECT * FROM CLIENTES c WHERE c.codigo_cli = '".$lcodCli."'";
      $lconexao->$result = mysql_query($sql) or die("erro de consulta");
      if ($consulta = mysql_fetch_array($lconexao->$result)){
        $auxCliente = new Cliente();
        $auxCliente->$id = $consulta[CODIGO_CLI];
        $auxCliente->$nome = $consulta[NOME];
        $auxCliente->$dataNasc = $consulta[NASCIMENTO];
        $auxCliente->$cpf = $consulta[CPF];
        $auxCliente->$identidade = $consulta[IDENTIDADE];
        $auxCliente->oEndereco->$logradouro = $consulta[ENDERECO];
        $auxCliente->oEndereco->$cep = $consulta[CEP];
        $auxCliente->oEndereco->$bairro = $consulta[BAIRRO];
        $auxCliente->oEndereco->$cidade = $consulta[CIDADE];
        $auxCliente->$telefone1 = $consulta[TELEFONE1];
        $auxCliente->$telefone2 = $consulta[TELEFONE2];
        $auxCliente->$referencia = $consulta[REFERENCIA];
        $auxCliente->$status = $consulta[STATUS];
        $auxCliente->$inscricaoEstadual = $consulta[Inscricao_Estadual];
        $auxCliente->$celular = $consulta[Celular];
        $auxCliente->$email = $consulta[Email];
        $auxCliente->$dataVencimento = $consulta[Dvencimento];
        $auxCliente->$dataVisitaTecnica = $consulta[DVisitaTecn];
        $auxCliente->$valorMensalidade = $consulta[Valor_da_mensalidade];
        $auxCliente->$regimeTributario = $consulta[Regime_tributario];
        $auxCliente->$observacao = $consulta[Observacao];
        $auxCliente->$qtdeEcf = $consulta[QUANT_ECFs_INST];
        $auxCliente->$modelo = $consulta[Modelo];
        $auxCliente->$possuiNFe = $consulta[NFe];

        mysql_free_result($lconexao->$result);

                return $auxCliente;
      }

      return null;

    }
?>

E aqui a chamada onde os valores dos atributos estão duplcicados:
if ($auxCliente != null){
      echo $auxCliente->$id." - ".$auxCliente->$nome." - ".$auxCliente->$dataNasc." - ".$auxCliente->$cpf." - ".$auxCliente->$identidade." - ".$auxCliente->oEndereco->$logradouro." - ".$auxCliente->oEndereco->$bairro." - ".$auxCliente->oEndereco->$cep." - ".$auxCliente->oEndereco->$cidade." - ".$auxCliente->$telefone1." - ".$auxCliente->$telefone2." - ".$auxCliente->$referencia." - ".$auxCliente->$status." - ".$auxCliente->$inscricaoEstadual." - ".$auxCliente->$celular." - ".$auxCliente->$email." - ".$auxCliente->$dataVencimento." - ".$auxCliente->$dataVisitaTecnica." - ".$auxCliente->$valorMensalidade." - ".$auxCliente->$regimeTributario." - ".$auxCliente->$observacao." - ".$auxCliente->$qtdeEcf." - ".$auxCliente->$modelo." - ".$auxCliente->$possuiNFe;
    }

Answer: Sugiro que adicione aspas simples em todos os acessos do array do banco e também atribua os valores nas propriedades do objeto cliente.
Mude as ocorrências de:
$auxCliente->$id = $consulta[CODIGO_CLI];

Para
$auxCliente->id = $consulta['CODIGO_CLI'];

------------^               ^----------^
cifrão removido             aspas adicionadas

Ao fazer um teste parcial foi retornado os seguintes erros/warnings:

Undefined variable: id in

e

Cannot access empty property in

phpfiddle - exemplo dos erros.
O mesmo vale para iniciar os atributos no construtor, da forma que está você está basicamente criando um monte de variaveis que perderam o valor após o construtor ser invocado.
Mude:
function __construct() {
   $id = 0;

Para:
function __construct() {
   $this->id = 0;

Comment: Infelizmente a versão 4
Comment: Não precisa! Já foi resolvido! Muito obrigado rray. O problema estava justamente no cifrão, tanto na atribuição $auxCliente->id = $consulta['CODIGO_CLI']; quanto na chamada $auxCliente->id. Como sou novo em php acho que acabei me confundindo e chamando sempre $atributo
Comment: Eu retirei as aspas simples dos acessos do array do banco de dados justamente para testar, mas com ou sem aspas o erro persiste...
Comment: @Robson Removeu o cifrão?
Comment: Sim, do jeito que você disse, só que agora os atributos do objeto Cliente não possuem mais valor nenhum! Já no objeto Endereço (dentro de Cliente) os valores do atributo logradouro estão duplicados! Muito estranho
Comment: Bom, o que eu percebi foi que se eu tirar o cifrão os valores dos atributos tipo que não atribuem, perdem os valores...
Comment: Qual vesão do php está usando?
Comment: Aaaaa por isso... vou altera a resposta, ela é voltada para o php5.
Comment: Deu certo agora?


SQL Server : delete user

Question: I'm trying to write a query to delete a user registration from my SQL Server database, but when I try to delete a user, I get this error:

System.InvalidOperationException: 'ExecuteReader: Connection property has not been initialized.'

My code:
Public Class DeleteForm
Private Sub btnDelete_Click(sender As Object, e As EventArgs) Handles btnDelete.Click
    Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")

    Using cmd = New SqlCommand("SELECT * FROM tblLogin WHERE username = " & txtUsername.Text, conn)
        conn.Open()
        Dim reader As SqlClient.SqlDataReader = cmd.ExecuteReader

        If reader.Read = True Then
            If txtUserPass.Text = txtCheckPass.Text Then
                Dim deleteOk As Integer = MessageBox.Show("This cant be undone!" & vbCrLf & "Are you sure?", "Warning!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
                If deleteOk = DialogResult.Yes Then
                    Dim queryDelete As String = "DELETE FROM tblLogin WHERE username = " & txtUsername.Text & " and password = " & txtPassword.Text
                    Dim cmdDelete As New SqlClient.SqlCommand(queryDelete, conn)

                    If conn.State = ConnectionState.Closed Then conn.Open()
                    reader.Close()
                    cmdDelete.ExecuteNonQuery()
                    MsgBox("Cancellazione eseguita correttamente!")
                    cmdDelete.Dispose()
                    conn.Close()
                ElseIf deleteOk = DialogResult.No Then

                End If
            Else
                MsgBox("The passwords arent matching!")
            End If
        Else
            MsgBox("User not found")
            conn.Close()
            txtUsername.Clear()
            txtUsername.Focus()
            txtUserPass.Clear()
            txtCheckPass.Clear()
        End If
    End Using
  End Sub
End Class

Comment: Just a suggestion. I would separate this in multiple method. One that look if the user exists, an other that just delete and one that calls them and handle error.
Comment: Be aware of SQL injection! Always use parametrized queries.
Comment: Not using parameters is just awful. This is wide open to sql injection and my friend [Bobby Tables](http://bobby-tables.com/) loves this style of coding. And passwords should be salted and hashed, not stored in clear text.
Comment: Which line is it erroring on?
Comment: Never ever store passwords as plain text either - salt them and hash them
Answer:
You need to open connection before you can create a command.
i.e.
Dim conn = New SqlConnection("Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=dbProject;Integrated Security=True")
conn.Open()
Using cmd = New SqlCommand(....

However your current code contains SQL Injection. You should not concatenate strings go get your SQL. You should use parameters. See this answer for better explanation about the application.
Also it is never a good practice to store passwords in plain text. Ever. You should store hash of password only and compare the hashes rather than plain-text. Read this answer for reference. And more background info on why you should hash
Comment: "You need to open connection before you can create a command." I know you have way more experience than I but, I do not agree. An instantiated connection can be sent to the Command constructor. It does not need to be open. I never open a connection until the last possible moment; right before the Execute.
Comment: @Mary Huh, you are absolutely correct here - I did not realise that, I always opened connection before passing it to commands (though this is a very rare occasion I writ this low-level code)

SQL Server : delete user


Feeds event subscriber stopped working

Question: For some reason my feeds event subscribers have just stopped working.
My code looks like this, the dpm for debugging never gets fired so I think the function isn't being run.
I can't work out what's changed.

namespace Drupal\partshub_feeds_modifications\EventSubscriber;

use Drupal\feeds\Event\EntityEvent;
use Drupal\feeds\Event\FeedsEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Reacts to feeds events to modify feed properties.
 */
class FeedsSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [];
    $events[FeedsEvents::PROCESS_ENTITY_PRESAVE][] = 'presave';
    $events[FeedsEvents::PROCESS_ENTITY_POSTSAVE][] = 'postsave';

    return $events;
  }

  /**
   * Acts on presaving an entity.
   *
   * @param Drupal\feeds\Event\EntityEvent $event
   *   The feed event.
   */
  public function presave(EntityEvent $event) {
    dpm($event);
    // Get the feed object.
    $feed = $event->getFeed();
    // Get the entity being operated on.
    if ($feed->type->entity->id() === 'parts') {
      $entity = $event->getEntity();
      // Get the unchanged entity.
      $unchanged_entity = \Drupal::entityTypeManager()
        ->getStorage('node')
        ->loadUnchanged($entity->id());
      // Check if the entity is new.
      if (!$entity->isNew()) {
        // Only if part is not new check values.
        if ($feed->type->entity->label() === 'Parts') {
          if ($entity->get('title')->value === 'empty') {
            $entity->get('title')->value = $unchanged_entity->get('title')->value;
          }

          // Part fitment/makes field.
          if ($entity->get('field_make')->isEmpty()) {
            $makes = $unchanged_entity->get('field_make')->referencedEntities();
            foreach ($makes as $index => $term) {
              $tid = $term->id();
              if ($index == 0) {
                $entity->set('field_make', $tid);
              }
              else {
                $entity->get('field_make')->appendItem([
                  'target_id' => $tid,
                ]);
              }
            }
          }

          // Part group code.
          if ($entity->get('field_group_code')->isEmpty()) {
            $codes = $unchanged_entity->get('field_group_code')
              ->referencedEntities();
            foreach ($codes as $index => $code) {
              $code_id = $code->id();
              if ($index == 0) {
                $entity->set('field_group_code', $code_id);
              }
              else {
                $entity->get('field_group_code')->appendItem([
                  'target_id' => $code_id,
                ]);
              }
            }
          }

          // Cross references.
          if ($entity->get('field_cross_references')->isEmpty()) {
            $references = $unchanged_entity->get('field_cross_references')
              ->referencedEntities();
            foreach ($references as $index => $reference) {
              $reference_id = $reference->id();
              if ($index == 0) {
                $entity->set('field_cross_references', $reference_id);
              }
              else {
                $entity->get('field_cross_references')->appendItem([
                  'target_id' => $reference_id,
                ]);
              }
            }
          }
        }
        elseif ($feed->type->entity->label() === 'Physical attributes') {
          if ($entity->get('title')->value === 'empty') {
            $entity->get('title')->value = $unchanged_entity->get('title')->value;
          }
          // Part weight.
          if ($entity->get('field_weight')->isEmpty()) {
            $entity->get('field_weight')->value = $unchanged_entity->get('field_weight')->value;
          }
          // Part Height.
          if ($entity->get('field_height')->isEmpty()) {
            $entity->get('field_height')->value = $unchanged_entity->get('field_height')->value;
          }
          // Part Width.
          if ($entity->get('field_width')->isEmpty()) {
            $entity->get('field_width')->value = $unchanged_entity->get('field_width')->value;
          }
          // Part Depth.
          if ($entity->get('field_depth')->isEmpty()) {
            $entity->get('field_depth')->value = $unchanged_entity->get('field_depth')->value;
          }
        }
      }
    }
  }

  /**
   * Acts on presaving an entity.
   *
   * @param Drupal\feeds\Event\EntityEvent $event
   *   The feed event.
   */
  public function postsave(EntityEvent $event) {
    $feed = $event->getFeed();
    $feeds = ['oe_references', 'sub_components', 'dimensions'];
    $id = $feed->type->entity->id();
    if (in_array($id, $feeds)) {
      $entity = $event->getEntity();
      $parent_field_name = $entity->parent_field_name->value;
      $parent_id = $entity->parent_id->value;
      $vid = \Drupal::entityTypeManager()->getStorage('node')->getLatestRevisionId($parent_id);
      $part = \Drupal::entityTypeManager()->getStorage('node')->loadRevision($vid);
      $paragraph_references = $part->get($parent_field_name)->referencedEntities();
      $paragraph_references_id = [];
      if ($paragraph_references) {
        foreach ($paragraph_references as $paragraph_reference) {
          $paragraph_references_id[] = $paragraph_reference->id();
        }
      }
      if (!in_array($entity->id(), $paragraph_references_id)) {
        $fields = [
          'field_oe_references', 'field_sub_components_', 'field_dimensions'
        ];
        if (in_array($parent_field_name, $fields)) {
          if ($part) {
            $part->{$parent_field_name}[] = $entity;
            $part->save();
          }
        }
      }
    }
  }

}

I also have a service definition as follows.
services:
  # Name of this service.
  parthsub_feeds_modifications_events_subscriber:
    # Event subscriber class that will listen for the events.
    class: Drupal\partshub_feeds_modifications\EventSubscriber\FeedsSubscriber
    # Tagged as an event_subscriber to register this subscriber with the event_dispatch service.
    tags:
      - { name: event_subscriber }

Comment: The custom module with this code is enabled, right?
Comment: yeah :-) so strange as it all worked before, checked all the basics cleared cache etc. I had a look at some examples and I've seen some service names with . in so I've also tried changing the service name to `parthsub_feeds_modifications.events_subscriber` but that doesn't work either.
Answer: No answer to this, I was getting validation errors before the presave was fired which meant this code never fired.

Feeds event subscriber stopped working


Declare and define a delegate in one line (without using Action/Func)

Question: Is there a way to shorten the following:
public class Test
{
    /* declares a delegate type (named MyDelegateType) which has a single parameter of
        type float and doesn't return anything. */
    public delegate void MyDelegateType(float f);

    /* defines a reference to an object of type MyDelegateType */
    private MyDelegateType MyDelegateRef;

    ... // say we have a Property to set and get MyDelegateRef, and a method
        // for executing its target
}

into one line, without using Action/Func types?
I'm asking this to understand if there's an equivalent to what we can do in C++ (or C) with a function pointer:
class Test
{
   /* defines a pointer (named MyFP) to a function with a single
      parameter of type float, and doesn't return anything */
   void(*MyFP)(float);

   ... // say we have a Setter & Getter functions, and an Execute
       // function for executing MyFP
}

Comment: The C# language in general does not permit declaring a type in the same statement as declaring an object of that type.  Works in C++ but a never-ending source of very hard to diagnose compiler errors, particularly so if the declaration is in a header file and is missing a semi-colon after the closing brace.  Everybody forgets.  The C# team was made up from very experienced programmers that knew C++ well, including all its traps.  And aimed to avoid them.  Using the Func<> type works because that one is of course already declared.  You'll get used to it easily.
Comment: Why don't you want a 'Func'? As far as I understand with very limited C++ knowledge a function pointer also is some kind of a 'Func' type.
Comment: Why without those type that do just what you want?
Comment: @ThomasSchremser, a function pointer can function either as `Action` or `Func` type. It's not that I don't want a `Action`/`Func`, this question is purely asked to understand the syntactic possibilities.
Comment: Just adding this for a related reference: Eric Lippert's [post](http://stackoverflow.com/a/36560177/6474510) about (not) supporting function pointers in C#
Answer: No, that's why Action<T> and Func<T> were included in the framework.