Why do modules have bug reports?

Question: A good question was raised in this comment by EGHDK:

Why do these modules have bug reports. Shouldn't this be a simple task for a module to complete with no errors?

He was referring to limiting the viewing of pages to users of a certain role, but the question applies broadly.
Answer: There's a big difference between creating a custom module for just one site (your own, let's say) and creating one that will be able to be used on many different sites.
For example, let's say I want to limit access to a certain content type to only users of a certain role. Let's say that content type is 'awesome_thing' and the role is 'awesome_person'. There are two ways to go about this.

My own module that no one else will ever see or use

This would probably consist of something like a hook that gets called for each page, examines the $node object to see if it's 'awesome_thing' and then, if it is, examines the $user object to see if it's an 'awesome_person' and, if so, loads the page or whatever.

A module that is fit for contribution to d.o contrib

This would have to include a configuration interface that allows users to specify which content types they want to restrict, and which roles they want to allow on those content types. If there's more than one combination of role and nodetype then you have to deal with that. Then, since you've given a mouse a cookie, people are going to have feature requests, or maybe they'll write patches that add features and you think they're cool and you want to integrate them into a new version of your module.
Then say your module has a dependency on another module for some of these features, or your naming conventions conflict with another module's. On most sites this won't be noticeable so you probably wouldn't ever encounter it as a problem just on your own site. But by the law of large numbers, if you let a whole bunch of people use your module, they're more likely to discover corner cases where things work in unexpected ways than you are to think of every possible use case.
And then someone might look at your module and see that you violated a coding standard or namespace convention. Or they might see that you used 5 lines of code to do something that could be better done in 3 lines, or that you did something that's going to be expensive on performance if the module is used on a large-scale site with higher traffic than yours.
The tl;dr is that writing your own snippet for your one little use-case is exponentially less complex than writing, say, a patch for public consumption which itself is exponentially less likely than a full-blown module to both contain bugs and to have its existing bugs noticed and called out.
Answer: I have been involved with the F/OSS community for 20+ years, and it has a dirty little secret:
There is often very little incentive for the original authors to maintain code unless they are actively using it themselves or are affected by bugs themselves.
I have several patches on issues that have sat for well over a year.  There are also some really serious problems (for some people) in core that have patches that won't get committed.
When authors are committed to projects, they grow.  When they get help they grow.  When they encounter bugs that may affect them down the line, they accept patches.
When they don't use projects anymore, they stagnate.  When they move onto other things, they die.
Answer: Inherently humans are flawed, humans write code, therefore code is flawed. This creates bugs.
Personally I suffer from "can't see the wood for the trees", when I code a new module I find it difficult to find every single use case for the module therefore I don't think of every issue that might crop up.
Answer:
Why do these modules have bug reports. Shouldn't this be a simple task for a module to complete with no errors?

I disagree that creating a module without errors is that simple, if not in the cases the module's code is really simple.
For that to happen, you should test the module in different conditions, which would also mean to test it in a test site running other modules as well, and with different versions of those modules. There are so much modules that is impossible to test all the possible combination of modules, especially because it's not a matter of testing the module you wrote with any combination of two other modules. Theoretically, you should test your module with a combination of infinite modules.
Writing tests for your module helps fixing the errors in the module you are developing, but that doesn't catch all the possible errors caused from the combination of two running modules.
If the test infrastructure used on Drupal.org allows you to do that, you can test your module requiring another module to be installed, but it would be up to you to decide which other module you want installed during the test, and you cannot foresee any possible problem with other modules. Also, you cannot test your module with random combinations of modules, considering that the test servers are thought to test not just your module, but all the modules hosted on Drupal.org.

Why do modules have bug reports?


How can I get the node ID from a path alias?

Question: I want to be able to get the nid but the only information I have is http://example.com/this-is-the-alias.
Is there a way to get either the internal path of /node/*  for that alias if I am not on the page?  Or is there a way to just get the nid from that alias right away?
Answer: I'm not sure if there's a direct function, but one route is to use the path alias manager service to lookup the internal path then regex it for a valid node id to perform an object load on:
<code>$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias');

if (preg_match('/node\/(\d+)/', $path, $matches)) {
  $node = \Drupal\node\Entity\Node::load($matches[1]);
}
</code>
Drupal 9
In Drupal 9 the service has been renamed.
<code>$path = \Drupal::service('path_alias.manager')->getPathByAlias('/this-is-the-alias');
</code>
Comment: For some reason, `$path` is sometimes equal to `/this-is-the-alias`. Once was when the root path (`node/{id}`) was another alias #migrationstruggles, but it was also present with other aliases.
Comment: Please remember, if you are using Drupal 8 with translated pages, you need to inform the language in the second parameter:
$path = \Drupal::service('path.alias_manager')->getPathByAlias('/this-is-the-alias', $langcode);
Answer: You can use the following code to get and load an entity and have access to its values.
<code>  use \Drupal\Core\Url;

  $alias = \Drupal::service('path.alias_manager')->getPathByAlias('/etapes-de-la-vie');

  $params = Url::fromUri("internal:" . $alias)->getRouteParameters();
  $entity_type = key($params);
  $node = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
  //to use dpm you need the devel module
  dpm($node->nid->value);
</code>
References

Drupal 8: get entity object given system path?
Comment: You don't need to resolve the alias, just feed the relative URL into the `Url::fromUserInput` and then call the `getRouteParameters`
Answer: Install the devel module and then use the devel toolbar item Current route info.
This results in this url, which you can type in directly and provide any path known to your drupal installation as query parameter:
<code>/devel/routes/item?path=alias
</code>
When it is a node you find the node id in the raw parameters at the end of the listed route variables.
Answer: This is what I do, so you avoid direct regexs.
<code>$parsed_url = UrlHelper::parse($alias);
$path = \Drupal::service('path_alias.manager')->getPathByAlias($parsed_url['path']);
$params = Url::fromUserInput($path)->getRouteParameters();
$entity_type_id = array_key_first($params);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type_id)->load($params[$entity_type_id]);

</code>


Area under the ROC curve or area under the PR curve for imbalanced data?

Question: I have some doubts about which performance measure to use, area under the ROC curve (TPR as a function of FPR) or area under the precision-recall curve (precision as a function of recall).
My data is imbalanced, i.e., the number of negative instances is much larger than positive instances.
I am using the output prediction of weka, a sample is:
<code>inst#,actual,predicted,prediction
1,2:0,2:0,0.873
2,2:0,2:0,0.972
3,2:0,2:0,0.97
4,2:0,2:0,0.97
5,2:0,2:0,0.97
6,2:0,2:0,0.896
7,2:0,2:0,0.973
</code>
And I am using pROC and ROCR r libraries.
Comment: Note: it seems you want to choose between ROC curves (TPR as a function of FPR over the entire operating range) and PR curves (precision versus recall over the entire operating range). Terminology like "*AUC-ROC of precision and recall*" is very misleading, so I've edited this. Please revert it if I misunderstood.
Comment: You forgot to mention what you want to achieve with any of these curves.
Answer: The question is quite vague so I am going to assume you want to choose an appropriate performance measure to compare different models. For a good overview of the key differences between ROC and PR curves, you can refer to the following paper: The Relationship Between Precision-Recall and ROC Curves by Davis and Goadrich.
To quote Davis and Goadrich:

However, when dealing with highly skewed datasets, Precision-Recall (PR) curves give a more informative picture of an algorithm's performance.

ROC curves plot FPR vs TPR. To be more explicit:
$$FPR = \frac{FP}{FP+TN}, \quad TPR=\frac{TP}{TP+FN}.$$
PR curves plot precision versus recall (FPR), or more explicitly:
$$recall = \frac{TP}{TP+FN} = TPR,\quad precision = \frac{TP}{TP+FP}$$
Precision is directly influenced by class (im)balance since $FP$ is affected, whereas TPR only depends on positives. This is why ROC curves do not capture such effects.
Precision-recall curves are better to highlight differences between models for highly imbalanced data sets. If you want to compare different models in imbalanced settings, area under the PR curve will likely exhibit larger differences than area under the ROC curve.
That said, ROC curves are much more common (even if they are less suited). Depending on your audience, ROC curves may be the lingua franca so using those is probably the safer choice. If one model completely dominates another in PR space (e.g. always have higher precision over the entire recall range), it will also dominate in ROC space. If the curves cross in either space they will also cross in the other. In other words, the main conclusions will be similar no matter which curve you use.

Shameless advertisement. As an additional example, you could have a look at one of my papers in which I report both ROC and PR curves in an imbalanced setting. Figure 3 contains ROC and PR curves for identical models, clearly showing the difference between the two. To compare area under the PR versus area under ROC you can compare tables 1-2 (AUPR) and tables 3-4 (AUROC) where you can see that AUPR shows much larger differences between individual models than AUROC. This emphasizes the suitability of PR curves once more.
Comment: @M.A edited my answer to clarify.
Comment: I think there is a mixup in the equation for recall between TPR and FPR, no?
Comment: Thanks for the explanation. The question now, why PR curves are more informative for imbalanced data? For me, ROC should be more informative because it considers both TPR and FPR.
Comment: In addition, these two articles make me more confused!
http://onlinelibrary.wiley.com/doi/10.1111/j.1466-8238.2007.00358.x/abstract

http://riceanalytics.com/db3/00232/riceanalytics.com/_download/Is%20the%20AUC%20the%20Best%20Measure.pdf
Comment: You're right, it should be: recall = ... = TPR, not FPR.  @Marc Claesen, I think only you can change that, because when I try to do it, I'm informed that: "Edits should have at least 6 characters", so it's impossible to correct small typos, such as this one.
Comment: @SimonThordal yes you're completely right, fixed! (albeit kinda late)
Comment: Using both would be my recommendation as the reader of the paper may be interested in different things
Answer: ROC curves plot TPR on the y-axis and FPR on the x-axis, but it depends on what you want to portray.  Unless there is some reason to plot it differently in your area of study, TPR/FPR ROC curves are the standard for showing operating tradeoffs and I believe they would be most well received.
Precision and Recall alone can be misleading because it does not account for true negatives.
Answer: I consider the largest difference in ROC and PR AUC the fact the ROC is determining how well your model can "calculate" the positive class AND the negative class where as the PR AUC is really only looking at your positive class.  So in a balanced class situation and where you care about both negative and positive classes, the ROC AUC metric works great.  When you have an imbalanced situation, it is preferred to use the PR AUC, but keep in mind it is only determining how well your model can "calculate" the positive class!


Get interact sliders from jupyter notebook to work in the bokeh html file

Question: Hello this is my first question (iam noob in everything) and iam kind of nervous not to get on your nervouse.
My overall goal is to create a 30 min lesson (part) where pupils can see:

interactive graphics and the super-fency CODE.

get attracted to become software engineers_innen or at least start to read the code. (me Measure the impact)

For this i think Jupyter notebook is the best weapon. For usability reason and different levels of interactivity i started to think about creating html-files to have remote access (my admins will kill me before letting me install sth. more on the school enviroment)
So i saw this:
from bokeh.plotting import figure
from bokeh.resources import CDN
from bokeh.embed import file_html

plot = figure()
plot.circle([1,2], [3,4])

html = file_html(plot, CDN, "my plot")

to create a html out of a bokeh figure.
But how to get nice interact sliders to this standalone html-file.
So how to (even if its non-sense) convert this example:
from ipywidgets import interact
import numpy as np

from bokeh.io import push_notebook, show, output_notebook
from bokeh.plotting import figure
output_notebook()

In [ ]:

x = np.linspace(0, 2*np.pi, 2000)
y = np.sin(x)

In [ ]:

p = figure(title="simple line example", plot_height=300, plot_width=600, y_range=(-5,5))
r = p.line(x, y, color="#2222aa", line_width=3)

In [ ]:

def update(f, w=1, A=1, phi=0):
    if   f == "sin": func = np.sin
    elif f == "cos": func = np.cos
    elif f == "tan": func = np.tan
    r.data_source.data['y'] = A * func(w * x + phi)
    push_notebook()

In [ ]:

show(p, notebook_handle=True)

In [ ]:

interact(update, f=["sin", "cos", "tan"], w=(0,100), A=(1,5), phi=(0, 20, 0.1))

Into sth. like this: https://demo.bokeh.org/sliders
Thanks for every comment. sry my english is not as good as look like, but iam not as smart as i look like
Answer: There's not any straightforward way that I know of to make this work in standalone HTML with Jupyter interactors. However, you can make standalone output that accomplishes this with Bokeh's own widgets:
https://docs.bokeh.org/en/latest/docs/gallery/slider.html
There is some ongoing work that should be out with Bokeh 2.0 that will allow Jupyter interactors to work with Bokeh server apps (not standalone output).
Comment: The link is broken as of the time of writing this comment. (Returns 404)
Comment: The gallery has has had to be re-organized to accommodate a sizeable increase in the number of examples in the intervening half-decade. You can can find many widget examples by browsing https://docs.bokeh.org/en/latest/docs/gallery.html
Comment: Thank you. None of their interactive examples work. That said, if I rerun the cell that calls `show`, it seems that the interaction works, but the chart does not get refreshed unless the cell is ran again explicitly.
Comment: All of the examples work for me. It's not really clear at all what sequence of steps you are taking or what you are doing (are you using classic notebook? jupyterlab? did you install the jupyter Bokeh extension?) so it's not possible to speculate whether you are seeing an actual problem, or having a usage issue. You might find the Bokeh Discourse a better forum for general new user discussions: https://discourse.bokeh.org/
Comment: I have tried with vscode Jupyter extension. I also tried with installing Jupyter and running it via `jupyter notebook`. It just does not work (interactively without any manual intervention) no matter what I do.

I suspect it might have something to do with the combination of jupyter/bokeh version - but I also am using latest versions of both, so at this stage - I am not investing time in investigating which is the case.
Comment: What is "it"? Some specific notebook? Is it using an embedded Bokeh server app to drive the widgets? Then that can't possibly function without actual cell exectutions. I suppose your expectations here are just off the mark, but without actual details (e.g. the actual code you are using) then you are correct that no investigation can help.


Suggestions for writing trumpet parts

Question: When writing a passage for the brass quartet, what are some of the rules that should be observed with regards to the trumpets.  I've noticed that due to the trumpet's piercing sound, my quartet passages sound harsh.  Should they be not as loud as the other brass parts?
Thanks
Comment: Never, ever, ever trust programs like Sibelius or Finale to play a score back as it will sound when played live, by real musicians. They are brilliant bits of software, and I use Sibelius every day (in my answer for instance!), but they can either: make a certain instrumentation sound better than it really will, giving you a "false sense of security"; or make it sound worse, when you have actually orchestrated quite well. These programs are useful for giving you an overall sense of what the instruments will sound like, and are brilliant for checking that you haven't made silly mistakes...
Comment: …but, in the end, they are primarily intended for use as **notation** software.
Comment: I would have considered that a lot the fault of your trumpet player, in a quartet environment! Perhaps pitch could be a consideration - are the parts unusually high, for a trumpet?
Comment: Or it could be the fault of the Finale 2012 software, which I am writing in.  Even when the trumpet part is in the middle C range, the quartet sounds harsh.
Comment: Ah, you haven't had it played by actual people yet? Then yes - I'd assume the software is to blame!
Answer: One of the best bits of advice I've had about writing good, comfortable sounding trumpet parts is "keep it on the stave". Sure, the trumpet range extends beyond this, both above and below the stave, but the range on the stave is comfortable and will generally blend well with other instruments.
Back when I started composing and arranging (a pretty long time ago!), the excerpt below was suggested to me by a trumpet player, as an example of comfortable trumpet writing:

It's from the Third Part of Stravinsky's ballet Petrushka.
Of course, mutes can greatly help your trumpet part to blend well with the other instruments, too. An understanding of Straight, Cup, Harmon and Bucket mutes (and the sounds they produce) is a good start. I would suggest asking a trumpeter to show you what different mutes sound like, but there are loads of clips online showing you what different mutes sound like. This is just one example...
Answer: If you're not a brass player yourself, one rule that may not be obvious is to make sure that your brass parts, trumpets especially, incorporate rest at regular intervals.
Playing, especially loud or high, requires quite a lot of muscle strength in the lips, as the lips need to hold the tension for the note, and the higher the note, the taughter the tension.
Imagine lifting a heavy weight in the gym.  If you get a short time after each time you lift the weight, you could probably repetitively lift that weight for quite a while before it got too heavy for you. Compare this to having to lift that weight continuously - you will run out of strength a lot more quickly.  It's exactly like that.
If you have friends/contacts who are going to play your music, I would recommend asking them for feedback on whether the parts are ok, stamina-wise. Obviously how much stamina a player has will vary considerably, from occasional amateur to professional. Put it this way: the more strenuous you make the part, the more you restrict the pool of players who can play your music towards the professional end of the spectrum.

Suggestions for writing trumpet parts


Converting $i$ to exponential form

Question: How would I convert the irrational number $'i'$ to exponential form, or $e^{i\theta}$?
I'm working a little in De Moivre's theorem.
Comment: What would be the argument of $i$?
Comment: Yes, with $r$ being the length(distance) associated with it. What would be this in the case of $i$?
Comment: https://en.m.wikipedia.org/wiki/Atan2#Definition_and_computation
Comment: @zzuussee it would be $\frac {\pi}{2},$ correct?
Comment: Yes, exactly, a quarter turn to the left.
Comment: @zzuussee thank you! If I'm not mistaken it would just be $re^{i\frac{\pi}{2}}$!
Comment: @zzuussee Just 1. The magnitude of $i$ is the distance from it to the origin, so we get $1$. Thanks a million!
Answer: As you've already shown the effort in the comments and found the solution yourself, I'll use the answer box to post a picture and elaborate a little:

The argument, the angle of the rotation between the $\mathbb{R}^2$-vector(associated with the complex number) is thus simply a $\pi/2$(or $90^\circ$) turn. As you've said yourself, the coefficient $r$ of the representation of a complex number using the complex exponential is the associated magnitude, i.e.
$$|i|=|0+1\cdot i|=\sqrt{0^2+1^2}=1$$
Attribute for the picture: By Original: GuntherDerivative work: Wereon - This file was derived from: Euler's formula.png:, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=821342

Converting $i$ to exponential form


Satisfiability of the resolvent

Question: What would be a way to prove the following statement:
S = {$C_1$, $C_2$}
and C is the resolvent of $C_1$, $C_2$. By resolvent I mean the result of the resolution operation.
The theorem: if S is satisfiable, C is satisfiable too.
Thanks in advance
Answer: What is a resolvent of a set $S = \{ C_1, C_2 \}$ of two clauses (where the clauses are disjunctions of literals or negated literals) ?
Suppose that the clauses $C_1$ and $C_2$ are disjunctions with a literal $X$ occurring in $C_1$ and $\lnot X$ occurring in $C_2$.
The resolvent $C$ is obtained from $C_1$ and $C_2$ building a single disjunction from them, after deletion of all occurrences of $X$ and $\lnot X$.
If $S$ is satisfiable, we have a valuation $v$ such that $v(C_1)=v(C_2)=TRUE$; but clearly it is impossible thaa $v(X)=v(\lnot X)=TRUE$.
Assume that $v(X)=TRUE$; thus, there exists a literal or negated literal $Y$ in $C_2$ (obviously different from $X$) such that $v(Y)=TRUE$.
Thus, by the construction of $C$, $Y$ occurs in it and we have that : $v(C)=TRUE$, i.e. the resolvent $C$ is satisfiable.

Satisfiability of the resolvent


mdadm fail, disk won't show up

Question: One of my disks failed in my raid array:
cat /proc/mdstat:
Personalities : [raid1]
md1 : active raid1 sda2[2](F) sdb2[1]
      488086720 blocks [2/1] [_U]

md0 : active raid1 sda1[0] sdb1[1]
      192640 blocks [2/2] [UU]

When i tried to remove then re-add the drive the following happened:
mdadm: hot removed /dev/sda2
host:# mdadm /dev/md1 --add /dev/sda2
mdadm: add new device failed for /dev/sda2 as 2: Invalid argument

fdisk -l /dev/sda returns nothing.
Can you tell me what's happening now, especially because md0 looks fine. Tried to Google it but nothing interesting come up.
Update (just for verbatim), now md0is failed too:
Personalities : [raid1]
md1 : active raid1 sdb2[1]
     488086720 blocks [2/1] [_U]

md0 : active raid1 sda1[2](F) sdb1[1]
     192640 blocks [2/1] [_U]

Comment: @DerfK: Thank you. Looks like it's totally dead? `end_request: I/O error, dev sda, sector 976559000, md: disabled device sda2, could not read superblock.`
Comment: Does `dmesg` or `/var/log/kern.log` shed any light on this with regards to drive errors?
Comment: @upvoter: now is the time when i'm not too happy because of a +1 :(
Answer: Sounds like the sda drive is dead.  I'm guessing md0 was for booting, which means it probably didn't get accessed much so its driver doesn't know sda1 is dead too.
Before you reboot the computer, make sure that you've installed grub to sdb since the BIOS probably isn't going to be able to boot off of that first drive.
If you didn't already do this, you'll need to run grub, then on grub's command prompt do:
root (hd1,0)
setup (hd1)

(From the guide here for grub 0.95, I'm not sure if this has changed in newer versions of grub)  (Note: hd1 assumes that sdb is the second drive in the system, if you've mixed IDE (hda) and SATA/SCSI drives, then you might have to figure this one out on your own)
Comment: thank you for your detailed answer. I'm in really trouble now because the cube is about 200kms from me. Now i must to build a secondary server in a blazing fast speed and dump everything onto it. Thank you, again.
Answer: You need to replace sda. It's pooched.

mdadm fail, disk won't show up


getting different column names from 2 tables in sql server

Question: I have Item and Sales tables with different columns like,
Item
ItemName
Itemcost
ItemQty

Sales
 SalesName
 SalesDate
 SalesQty

In the above tables there is not common column,but i need to get output as
ItemName,ItemCost,SalesName,SalesDate.

I tried with union,
select ItemName,ItemCost from Item
union
select SalesName,SalesDate from Sales

but am getting only 1 table columns like ItemName,ItemCost
Please help me on this issue
Thanks In Advance
Venkat.
Comment: Looks like a duplicate - see [Combine two tables that have no common fields](http://stackoverflow.com/questions/1198124/combine-two-tables-that-have-no-common-fields/1198234#1198234) for an answer.
Comment: Hi,

You want data from both the table.Please clarify it.I guess there is common column, U should use join,Instead of UNION
Comment: You really should specify how you expect your data to look in the end. The answers below are Cartesian products, which are almost always something to avoid.
Answer: Use below sql query :
select i.ItemName, i.ItemCost, s.SalesName, s.SalesDate
from Item as i, Sales as s;

Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was discontinued with the ANSI-**92** SQL Standard (**20 years** ago!). ***Please*** stop using it
Answer: Use the below query :
This will join every row in table1 with table2 (the Cartesian product) returning all columns.
Select im.ItemName, im.ItemCost, sl.SalesName,sl.SalesDate from Item as im, Sales as sl;

Comment: [Bad habits to kick : using old-style JOINs](https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins) - that old-style *comma-separated list of tables* style was discontinued with the ANSI-**92** SQL Standard (**20 years** ago!). ***Please*** stop using it


show that the function $f$ is the solution to the partial differential equation.

Question: Given that $f(x,y)=\phi(xy)$ where $\phi(xy):\Bbb R \rightarrow \Bbb R$ is a differentiable function. Show that $f$ is the solution to the equation: $$\frac{1}{x} \frac{\partial{f}}{\partial{y}} - \frac{1}{y} \frac{\partial {f}}{\partial{x}}=0$$
Answer: \begin{eqnarray*}
\frac{\partial f}{\partial y} &=& \frac{d\phi}{dz} (z=xy) x\\
\frac{\partial f}{\partial x} &=& \frac{d\phi}{dz} (z=xy) y\\
\frac{1}{x} \frac{\partial f}{\partial y} &=& \frac{d\phi}{dz} (z=xy)\\
\frac{1}{y} \frac{\partial f}{\partial x} &=& \frac{d\phi}{dz} (z=xy)\\
\end{eqnarray*}
Answer: Let $\phi:\mathbb{R}\to \mathbb{R}$ be a differentiable function, and for any $a\in \mathbb{R}$ let $\phi_a:\mathbb{R}\to \mathbb{R}$ be defined by $\phi_a(t)=\phi(at)$. Then you have $\phi_a'(t)=a\phi'(at)$. By definition of partial derivative, you now have
$$ \frac{\partial f}{\partial x} (x,y)=\phi_{y}'(x)=y\phi'(xy),$$
$$ \frac{\partial f}{\partial y} (x,y)=\phi_{x}'(y)=x\phi'(xy).$$
Therefore, the identity follows.


How do I override a view template in my theme folder properly?

Question: I do not know if I am something missing, but I have a View in Drupal 8 and wanted to make a Template override in my theme, where I would print-out the image URL of one field and set it as "background-image" via inline CSS.
So I turned on theme debugging to see the template suggestions and picked views-view-field.html.twig, copied the file to my theme, renamed it to match the suggestion, cleared the cache and it looks like the template override is working.
But all the variables I am trying to print-out are blank, even after clearing the cache the field just disappeared. When I try to dump() or kint() any variable written in the file (view, field, row, output) it prints "null" or completelly nothing.
What am I doing wrong?
I am sure template override works, because when I type regular text in a file it gets printed out, but all the variables are somehow missing and I can not print anything out of them.
Comment: Does `kint()` print anything for you? It should at least print the vars you have access to in the scope of this template file.
Comment: No, it only prints "null" and nothing else. It prints it out in Kint layout so I know Kint is working but nothing else for some reason.
Comment: Does the field happen to be excluded from Views display?
Comment: No it is not. It is normally visible and displaying when I for example remove template override I can see it.
Comment: Are you trying to display some content type, paragraph? If you are using a display mode of a content type in your view, make sure this mode has the fields you want to display (i.e. the image) enabled
Comment: Well, I am using Views to display a list of articles and I want image URL to be as background-image property. So I need plain URL (easy to do via formatter) and I want it to be displayed in DIV as inline-style property. Thats where I need template overrides.  So in theory view should have access to the field with no problems.
Answer: Copy the content of the previous template used and start from there.
It is most likely that the variable you are trying to display are not available in that template.
Consider adding variables using hook_preprocess.
Comment: Thats what I did. I copied file views-view-field.html.twig from core to my theme and flushed the cache. It does not ouput anything. I do not understand why it is like that. In Drupal 7 it worked nicely. Probably I came across some bug?
Comment: I am sure you have already tried this but have you added the actual field name for the views-view-field.html.twig template? E.g.  views-view-field--field-image.html.twig?


Is it possible to redirect after "pushing" a file to the user?

Question: I've got a setup where a site generates internal analytics about site usage. Users are able to request a download of their personal analytics, and because this information is sensitive I do not create any files, I generate a CSV file in a variable and then "push" it to the user with this:
<code>function _cex_download( $output, $filename )
{
  header("Pragma: public");
  header("Expires: 0");
  header("Cache-Control: private");
  header("Content-type: application/octet-stream");
  header("Content-Disposition: attachment; filename=$filename");
  header("Accept-Ranges: bytes");
  echo $output;
  exit;
}
</code>
This causes the user's browser to pop a "save file" dialog, and the user gets the file created on their end. This works fine, except the site's administrators are able to trigger 'destructive exports' - and in that situation I have a secondary confirmation form the admin needs to accept before the destructive export executes.
The problem is that this "push download" routine ends the Drupal page processing. There does not appear any way to redirect the admin to some page after that push download routine is called. Admins get a 'save file' dialog popped by their browser, but they remain on the confirmation form.
I tried going the multi-step form route, but after a day of dinking around with strange redirects, I backed out of that confusion. Started looking at ChaosTool's multi-step form logic too. But something tells me that the issue really is that this "push downloading" is a guided-process-killer.
Perhaps a jquery confirmation dialog that intercepts the initial 'Export' button click, do the confirmation entirely in javascript, forget out having a php/FAPI confirmation form, and when the user confirms in jquery I programmatically submit the Export I intercepted?
Answer: As far as I know, that is not possible. You can either send content (in your case a file), or redirect. Not both. This is a limitation of the HTTP protocol
Answer: There seem to be some tricks, no idea how well they work inside Drupal.
See for example http://www.willmaster.com/blog/automation/one-link-download-and-redirect.php
Comment: Your link looks very promising. I try it later and report back.
Answer: I think your best bet might be to generate a token when the user submits the form, and then have the token store all the necessary information to generate the CSV file. Have the form redirect the user to the appropriate page, and use drupal_set_message() to provide a link that contains the token.
When the link is clicked, the CSV file can be generated and sent to the user at that time. Granted, it's more complicated than just generating it on form submit, but as Fuzzy76 says, you're up against a limitation of the HTTP protocol. Doing it this way might be simpler than trying to make a JavaScript-based solution.
Answer: This is how I Achieved it in Drupal via Jquery / JS
My Answere here -> I achieved it via JS, Fine my answer here -> https://stackoverflow.com/questions/822707/php-generate-file-for-download-then-redirect/25843144#25843144


spring-data jpa's deleteAll() method call records are not audited in hibernate envers

Question: By default for save(), delete(), saveAll() hibernate envers audit the record change.
But for deleteAll() it is not auditing.
Answer: In application.properties override org.hibernate.envers.store_data_at_delete
<code>org.hibernate.envers.store_data_at_delete = true
</code>
Default value is false

"org.hibernate.envers.store_data_at_delete"   Should the entity data be stored in the revision when the entity is deleted (instead of only storing the id and all other properties as null). This is not normally needed, as the data is present in the last-but-one revision. Sometimes, however, it is easier and more efficient to access it in the last revision (then the data that the entity contained before deletion is stored twice).


How to initialize the elements of the filter matrix?

Question: I'm trying to better understand convolutional neural networks better by writing up Python code that doesn't depend on libraries (like Convnet or TensorFlow), and I'm getting stuck in the literature on how to choose values for the kernel matrix, when performing a convolution on an image.
I'm trying to understand the implementation details in the step between feature maps in the image below showing the layers of a CNN.

According to this diagram:

The kernel matrix kernel "steps" over the image, creating a feature map, where each pixel is the sum of all element-wise products between each weight of the kernel (or filter matrix) and the corresponding pixel value of the input image.
My question is: how do we initialize the weights of the kernel (or filter) matrix?
In the demonstration above, they are simply 1s and 0s, but I assume this is simplified from the diagram's sake.
Are these weights trained in some preprocessing step? Or chosen explicitly by the user?
Answer: One typically initializes a network from a random distribution, typically mean zero and some care is taken with regards to choosing its variance. These days with advances in optimization techniques (SGD+Momentum among other methods) and activation nonlinearities (ReLUs and ReLU-like activations allow for better backproagation of gradient signals, even in deeper networks), one is able to actually train state of the art convolutional neural networks from a randomized initialization.
Key properties are the following:

Why random? Why not initialize them all to 0? An important concept here is called symmetry breaking. If all the neurons have the same weights, they will produce the same outputs and we won't be learning different features. We won't learn different features because during the backpropagation step, all the weight updates will be exactly the same. So starting with a randomized distribution allows us to initialize the neurons to be different (with very high probability) and allows us to learn a rich and diverse feature hierarchy.
Why mean zero? A common practice in machine learning is to zero-center or normalize the input data, such that the raw input features (for image data these would be pixels) average to zero.
We zero-centered our data, and we will randomly initialize our network's weights (matrices as you referred to them). What sort of distribution should we choose? The distribution of the input data to our network has mean zero since we zero-centered. Say we also initialize our bias terms to be zero. When we initialize the training of our network, we have no reason to favor one neuron over the other as they are all random. One practice is to randomly initialize our weights in a way where they all have zero activation output in expectation. This way no one neuron is favored to "activate" (have positive output value) than any other neuron while simultaneously breaking symmetry due to the random initialization. Well a simple way to accomplish this is to choose a mean zero distribution.
How do we choose the variances? You don't want to choose the variance to be too large, even if it is mean zero. Extreme values in a deep nets weights can result in activation outputs that are exponentially increasing in magnitude, and this issue can compound with the depth of the network. This can wreak havoc on the training of our network. You also don't want to choose it to be too small as this may slow down learning since we are computing very small gradient values. So there's a balance here, especially when it comes to deeper networks as we do not want our forward or backward propagations to exponentially increase or decrease in depth.
There are two very popular weight initialization schemes: Glorot Uniform (Understanding the difficulty of training deep feedforward neural networks) and the He Normal initializer (Delving Deep into Rectifiers: Surpassing Human-Level Performance on ImageNet Classification).
They are both constructed with the intent of training deep networks with the following core principle in mind (quote is from the Delving Deeper into Rectifiers article):

"A proper initialization method should avoid reducing or magnifying the magnitudes of input signals exponentially."

Roughly speaking, these two initialization schemes initialize the variance of each layer so that the output distribution of each neuron is the same. Section 2.2 of the Delving Deep into Rectifiers provides an in-depth analysis.

A final note: sometimes you will also see people use Gaussian with standard deviation equal to .005 or .01, or some other "small" standard deviation, across all the layers. Other times you will see people fiddle with the variances by hand, basically performing cross validation to find a best performing configuration.
Comment: But what about the "X" shape (made by 1's) of the yellow filter in the GIF above? I understand this is what I would want to use to detect "X" shapes anywhere in the picture, but how do I know that "X" is the shape I want? I'm under the impression that the filter shape is learned automatically, but I don't know how.

Maybe this was the OP's question too?
Answer: I can't comment because of low reputation and so I am writing this in response to Felipe Almeida's question. After Indie AI's perfect answer, there is nothing much to add. If you want to detect specific shapes (like an X), you can pre define a specific filter, as is the case with edge detection. But this is the beauty of deep learning, there are so many layers, so many filters and so many iterations that the filters learn almost every object shape necessary on it's own. So theoretically, if there is an X to be detected, one of the filters will learn to detect an X (as the yellow filter)


Check if user enter sixteen correct unique words

Question: I need help in coding this situation:
I need to get words from user input loop until I get 16 unique words to put in a list. I also need to print "duplicates" every time the word inputted by the user is already a duplicate then keep asking until I get 16 unique words.
I don't need to print the unique list afterwards, as I will use them for the next part of my codes , we're also not allowed to use set()
Here's what i've tried by far:
mylist = []
def func():
while True:
    words = input()
    mylist.append(words)
    if len(mylist) == 16:
        break

Comment: Can you add your approach or any code with the question?
Comment: Just as with ```set```, the ```list``` supports the ```in``` operator. ```if newword in wordlist: print("dup")```
Answer: Try this
words = [] # creates the list for the unique words
while len(words) != 16: # runs until the length of the list of unique words is equal 16
    new_word = input("Add a new word: ") # asks the user for a new word and stores the input in a variable
    if new_word not in words: # checks if the inputted word is not in the unique words list already
        words.append(new_word) # if it is not, the word gets appended to the list of unique words
    else:
        print("dups") # otherwise "dups" gets printed

Answer: 1.Create a function
2.Input from user will be taken only if length of duplicates is less than sixteen
3.We check if word is in duplicates words, if it's tell user its a duplicate to
enter another
4.else we add that to list
duplicate_words = []
while len(duplicate_words) < 16:
    word = input("Enter a unique word: ")
    if word in duplicate_words:
        print("Duplicate word , enter another word")
    else:
        print("Word is correct!")
        duplicate_words.append(user)
    if len(duplicate_words) == 16:
        print("Sixteen words correct,Good Bye!")
        break


VPS versus Cloud

Question: Could a cloud enable me to copy/paste a VPS from one physical server to another?
I run a few VPS machines and am curious to know if a cloud would benefit me.
What would be really cool is if a cloud would enable me to copy/paste a VPS from one physical server to another, rather like how Oracle VM Virtualbox allows virtual machines to be duplicated, started and stopped.
Please don't mock me. I have read lots of info from cloud suppliers but all I can find is sales and marketing crap. I want technical stuff.
Nigel
Comment: I'm not sure how [water suspended in the atmosphere](http://en.wikipedia.org/wiki/Cloud) could help you 'copy/paste' VMs. ;) There is no technical stuff; it's all sales jargon. If you're talking about migrating VMs, many hypervisors will do that. Take a look at Hyper-V or VMWare.
Comment: In the good old days of the early internet the "cloud" was just the internet or anything outside your company.  You drew a diagram of your network and it had a line drawn between your router and a "cloud" (the internet).  Obviously you've gotten hold of some marketing guff and gotten really confused!
Comment: @Matt I should just draw a flow chart :)
Comment: My problem with cloud is that I can never get my servers to stay in it for very long.  They keep falling back the ground and breaking in impact.  Maybe I need more helium balloons.
Answer:
Please don't mock me. I have read lots of info from cloud suppliers but all I can find is sales and marketing crap.

That's because the difference between "Cloud" and "VPS" is purely "sales and marketing crap".
If you're looking for "copy and paste" on your VPS, though, you might want to look in to concepts like "live migration" or building new server images from snapshots.
Comment: ...that's far too many quote marks for a sensible answer.
Comment: +1 for attacking your own punctuation.
Answer: You can move VMs to and from Servers all day long. That would not be a cloud. A cloud basically is a bunch of servers working together to balance out resources to create scaleability for applications.
Cloud Computing:
http://en.wikipedia.org/wiki/Cloud_computing

The cloud also focuses on maximizing the effectiveness of the shared resources. Cloud resources are usually not only shared by multiple users but are also dynamically reallocated per demand. This can work for allocating resources to users. For example, a cloud computer facility that serves European users during European business hours with a specific application (e.g., email) may reallocate the same resources to serve North American users during North America's business hours with a different application (e.g., a web server). This approach should maximize the use of computing power thus reducing environmental damage as well since less power, air conditioning, rackspace, etc. are required for a variety of functions. With cloud computing, multiple users can access a single server to retrieve and update their data without purchasing licenses for different applications.

What you want is to setup a bunch of dedicated servers that would work as a cluster that would allow you to migrate VMs to and from servers.
Comment: What about [My Cloud](http://m.wdc.com/en/product/1140)?
Comment: I assume that is a sarcastic comment lol? But yea, to comment on my post above. Cloud has become a marketing plow and commonly refers to a backup solution. I work with so many small businesses and their understanding of the word "cloud" makes me facepalm so many times a day.
Comment: Thanks but the wikipedia quote doesn't really help me. **"maximizing the effectiveness of the shared resources"**. That doesn't mean anything. Likewise **"maximize the use of computing power thus reducing environmental damage"**
Answer: What you are looking for is typically called "cloning" a server. All the major (and a vast majority of the smaller) providers support this. Your comment below reads:

I've looked at Linode, DigitalOcean and Rackspace but there does not
  appear to be a "clone" facility on their VPS offerings. I'd be
  delighted if there were.

That is demonstrably false, as you'll see:
Linode
Contrary to your comment below, there's a great big "Clone" button on the Linode management web interface for your server.
DigitalOcean
Take a snapshot of a droplet, then restore then create a new droplet from that snap.
Rackspace
Create an image of a server, then you can restore that image.
AWS/EC2
Right-click on a server, choose "create image", then you can launch a new server from that image.

(Old answer, regarding live migration, is below)
VMware vSphere, Hyper-V, and Xen (others too, I'm sure) all have mechanisms by which virtual machines can be live-migrated between machines. Without getting too much into the technical detail, the mechanisms behind this are broadly:

two physical servers connected to a shared storage device. This storage device is where the VM's backing disks are kept.
migration is initiated by the user or perhaps by the virtualization resource planning system (VMware vSphere DRS, for example), at which point the source server starts copying the VMs RAM, CPU state, etc. to the target system over the network
when the two servers are in agreement about whether or not the VM is ready to be "moved", that VM's state is moved from source to target and the VM has now moved hardware
at the moment the switch happens, the VM's networking MAC address (or addresses) is moved from one server to the other. This can involve some networking gymnastics on the part of the hypervisors to ensure that the upstream switches know where the MAC's new location is on the network

If you're using a well-configured and well-resourced infrastructure, live migration can be done without even dropping as much as a single ping.
None of this really has anything to do with "cloud". Cloud is a nebulous term used to describe a collection of servers, working together in some fashion. No more or no less can be said about it.
Most "cloud providers" do not support live-migration of virtual machines. If this is a requirement, you likely need to run your own virtualization infrastructure or retain the services of one of the few very high-end (read: expensive) providers that do support live migration.
Comment: @NigelAlderton - then start looking for that requirement when choosing a provider. Linode, DigitalOcean, AWS, Rackspace, etc. They all support this.
Comment: @NigelAlderton - Are you serious? I'm beginning to think you're trolling here. Look at [this screenshot](http://photos.smugmug.com/photos/i-FqBQJK6/0/O/i-FqBQJK6.png) I just took of one of my Linode accounts.
Comment: Live migration is more than I need. What I would like is VPS copy/paste between physical servers. Regarding server cloning, I've used many VPS providers and I have never seen a "clone" button.
Comment: I've looked at Linode, DigitalOcean and Rackspace but there does not appear to be a "clone" facility on their VPS offerings. I'd be delighted if there were.
Comment: @NigelAlderton You're not looking particularly hard in their docs, then. In most cases it'll be called "snapshots". You can snapshot a VM and launch exact copies of it.

VPS versus Cloud


Dynamically update a list used in multiple Select Inputs in Shiny

Question: I have the following problem related to this relatively simple code that doesn't work:
server.R
library(shiny)

server <- function(input, output) {

  list_of_stuff=c("Car","Cat","Dog","Hat","Baby","Tractor")
  reactive_stuff_list <- eventReactive({list(input$select_1,input$select_2,input$select_3)},{

    selection_1=input$select_1
    selection_2=input$select_2
    selection_3=input$select_3

    list_of_stuff=list_of_stuff[! list_of_stuff %in% selection_1]
    list_of_stuff=list_of_stuff[! list_of_stuff %in% selection_2]
    list_of_stuff=list_of_stuff[! list_of_stuff %in% selection_3]
    return(list_of_stuff)
  })

  output$select1 <- renderUI({
    selectInput(inputId = "select_1", label = "Select some stuff",
              choices=reactive_stuff_list(), selected = NULL, multiple = TRUE)
  })

  output$select2 <- renderUI({
    selectInput(inputId = "select_2", label = "Select some stuff",
                choices=reactive_stuff_list(), selected = NULL, multiple = TRUE)
  })

  output$select3 <- renderUI({
    selectInput(inputId = "select_3", label = "Select some stuff",
                choices=reactive_stuff_list(), selected = NULL, multiple = TRUE)
  })

}

ui.R
ui <- mainPanel(
  uiOutput('select1'),
  uiOutput('select2'),
  uiOutput('select3')
)

WHAT I WOULD LIKE IT TO DO:
I start with some list of elements. Then as soon as I select some elements in one of the "selectInputs" (say number 1) the initial list gets updated in the other ones as well so I can't select the ones I selected in number 1 in number 2/3.
Sadly I have no idea how to achieve this; tried some stuff but didn't get anything usable.
Basically I want them to be kind of linked so they are seperate but work together.
If I'm not clear, I can try to explain it differently.
Any guidance would be very much appreciated
Answer: The problem with your code is that the way it's written, all of your selectInput elements get re-rendered every time any of their inputs change (i.e. when your reactive_stuff_list() changes). The re-rendering changes the selection back to NULL, since that's the value you set in the selectInput calls in your renderUIs.
Below is an implementation that works around that issue by retaining the current input when updating the available choices.
library(shiny)

server <- function(input, output) {

  # Stuff lists

  LIST_OF_STUFF = c("Car", "Cat", "Dog", "Hat", "Baby", "Tractor")

  # Update available choices

  other_select <- function(inputId) {

    # Return a reactive list of input values from all 'select_#' input elements,
    # except for the input element given as the inputId argument.  This allows
    # updating a 'select_#' input element whenever any other 'select_#' input
    # element changes.

    reactive({
      select_ids <- grep("^select_\\d+$", names(input), value = T)
      other_select_ids <- setdiff(select_ids, inputId)

      # Single bracket indexing doesn't work for reactive lists: can't simply
      # select inputs based on character vector.  Work around by iterating with
      # double bracket indexing.

      purrr::map(other_select_ids, purrr::partial(`[[`, input))
    })

  }

  render_select <- function(i, label = "Select some stuff") {

    # A selectInput named 'select_' that re-renders whenever _other_
    # selectInputs named 'select_#' change.  Removes choices that have been made
    # in the other selectInputs named 'select_#', while preserving the existing
    # selections.

    renderUI({

      # Save current input; isolated so that changing own input won't cause the
      # object to re-render.

      this_id <- paste0("select_", i)
      this_input <- isolate(input[[this_id]])

      # Update choices based on selections made in other 'select_#' elements.

      selected_elsewhere <- unlist(other_select(this_id)())
      available_choices <- setdiff(LIST_OF_STUFF, selected_elsewhere)

      selectInput(inputId = this_id, label = label, choices = available_choices,
        selected = this_input, multiple = TRUE)
    })
  }

  output$select_1 <- render_select(1)
  output$select_2 <- render_select(2)
  output$select_3 <- render_select(3)

}

ui <- mainPanel(uiOutput("select_1"), uiOutput("select_2"), uiOutput("select_3"))

shinyApp(ui, server)

Comment: I accept this answer since this is what worked best for me. I adapted it into my code and it does great.
Answer: ?updateSelectInput is your friend here... a simple example:
stack.shiny <- function(){
  dat_set <- mtcars

  all_cars <- row.names(dat_set)

  car_brands <- unique(stri_extract_first_words(all_cars))

  server <- function(input, output, session) {

    output$car_brands <- renderUI({
      selectInput(inputId = 'select1', label = 'choose brand',
                  choices = car_brands)
    })

    output$cars <- renderUI({
      selectInput(inputId = 'select2', label = 'choose car',
                  choices = all_cars)
    })

    observeEvent(input$select1, {
      x <- input$select1
      find_pat <- sprintf('^%s', x)
      these_cars <- all_cars[grepl(find_pat, all_cars, perl = TRUE)]
      # Can also set the label and select items
      updateSelectInput(session, "select2",
                        choices = these_cars,
                        selected = NULL)
    })
  }

  ui <- fluidPage(
    uiOutput('car_brands'),
    uiOutput('cars')
  )

  shinyApp(ui, server)

}

Comment: I tested your example and I'm not sure it does what I need it to do. I will play around with `updateSelectinput` some more though, thanks.
Comment: Thank you. It is good advice, using `observeEvent` with `updateSelectInput`.


Jest Testing Meteor React Component which is using withTracker in Container (meteor/react-meteor-data)

Question: I am testing component using withTracker in its container.
An error happens:

TypeError: (0 , _reactMeteorData.withTracker) is not a function.

I think I haven't mock the react-meteor-data/withTracker yet. Can someone tell me how to mock it? Or is there any solution for this?
Comment: It has been quite a while, but how have you solved this? Thanks.
Answer: Inspired by How is Meteor's withTracker function executed differently than the former reactive container function createContainer?
I managed to upgrade the tests from createContainer to withTracker using the following:
In your mocked react-meteor-data.js file.
const createContainer = jest.fn((options = {}, component) => component );

const withTracker = jest.fn(Op => jest.fn(C => createContainer(Op, C)));

Then export withTracker instead of createContainer.


Help changing views HTML output

Question: I have View set up to display a list of images that are related to nodes elsewhere in my site, and I've styled them so that hovering over them darkens the image and displays the node's title. Unfortunately, the title div obscures the image, and making the title into a link only affects the title text.
What I'd like to do is wrap the title div in  tags, so this:

Title

Turns into this:

Title

I have an inkling that I'll have to do this either with hooks or in one of the views.php files, but I'm not sure where to start; can anyone help me?
Answer: Filter title and use token like:
[Title]

Help changing views HTML output


matplotlib has no attribute 'pyplot'

Question: I can import matplotlib but when I try to run the following:
matplotlib.pyplot(x)

I get:
Traceback (most recent call last):
   File "<pyshell#31>", line 1, in <module>
       matplotlib.pyplot(x)
AttributeError: 'module' object has no attribute 'pyplot'

Answer: pyplot is a submodule of matplotlib, but it doesn't get imported with import matplotlib only:
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'
>>> import matplotlib.pyplot
>>>

However, it is recommended to alias it as plt:
import matplotlib.pyplot as plt

Then, you can use the various functions and classes it contains:
p = plt.plot(...)

Comment: This looks like your installation is corrupt, maybe try a clean reinstall.
Comment: Worked it out.. apparently the current matplotlib version from the installer is not compatible with the 64-bit version of Python so downloaded 32-bit version and works perfectly now. Thanks for the help though.
Comment: Tried this originally, get an ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/_path.so, 2): no suitable image found.  Did find:
    /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/m
Comment: I'm happy to improve on this answer :-).  Leave a comment about what's wrong and I'll do my best to address it!
Answer: Did you import it? Importing matplotlib is not enough.
>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but
>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.
pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.
The most common form of importing pyplot is
import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.
plt.plot([1,2,3,4,5])

instead of
matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above
Comment: I have the same problem with pyplot. But "import matplotlib.pyplot as plt" still doesn't work for me. I get the same error.
Comment: Had tried this and it wasn't the problem. Worked it out.. apparently the current matplotlib version from the installer is not compatible with the 64-bit version of Python so downloaded 32-bit version and works perfectly now. Thanks for the help though.
Comment: Sure, always install the the version of a library corresponding to the version of you interpreter...
Answer: simple answer worked for me if you are importing 'librosa' library, just import it before 'import matplotlib.pyplot as plt'. That worked for me and couple others for similar issue
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

matplotlib has no attribute 'pyplot'


How to run WMI command on local system with elevated privileges from GPO login script?

Question: I want to run WMI queries from a GPO deployed user login script to gather user information.
Problem is that users must be a member of the administrators group to be able to run WMIC and I can't give these specific domain users admin rights.
Is it possible to run WMIC with elevated privileges in a GPO login script on local Windows XP systems so that it will work when limited (non-admin) users login?
To clarify, this question is not about WMI connections to remote systems. It's about running WMIC on the system locally.
Answer: Really interesting, good question. Unfortunately, the answer is "no, this cannot be done". The login scripts are always run with the user's credentials.
As a workaround, you could instead have the login script "notify" or flag a monitoring script that user X has logged in, which would then begin a reciprocal WMI session to the computer that the user logged into. Then WMIC would launch on management server with admin rights, and run against the host that just sent the login. Of course, WMI permissions get very picky, and you'll need to run them by setting impersonationLevel=Impersonation in the code.
Answer: Did you try to use PowerShell?
Basic example that can be run from CMD:
powershell.exe -command "gwmi win32_userprofile"


Random product variations "not available"

Question: Of ~800 Commerce product variations, ~30 are not available for purchase on their respective display pages. These offending variations are completely set up like their brothers & sisters, Title, pricing, sku, and status. I see nothing wrong with them, through the /admin/ gui. But when visiting the display pages, for these offending products, Add to Cart is displayed as Product not available.
I can't find any information online concerning a similar problem. I'm also novice enough, to not know the best way to go about solving this issue.
Drupal and Commerce are the latest versions. If there's any other information I can offer, please let me know.
Comment: nothing to do with stock?
Comment: @DanielHarper you beat me ;) zer0, have you checked how many of them your site thinks you have available for sale?
Comment: @DanielHarper No stock modules installed.
Comment: @Molot the last list I saw of the problem products was at 28, but I think there were two others, not on the list.
Comment: And what's in the status field? [Screenshot that shows field I'm talking about](http://www.drupalcommerce.org/sites/default/files/docs/Prod-Attr-Step2.png), don't mind what's written on the image, it's unrelated to this issue.
Comment: [Here is the Manage Fields page for the product type.](http://imgur.com/jHNMoZq) [Here is the status through the admin pages, of one of the problem products.](http://i.imgur.com/1XI4cmj.png)
Comment: Ok, to pile onto this confusion, I installed Devel and opened up my DB workbench, hoping to narrow down an incorrect value hiding somewhere. There weren't any that I could pick out. Every variation I looked at, that chose it's own availability, returned a value of "1."

On another site, someone suggested placing debug code on the page, to help identify the problem. Anyone know an example of what code I would need to include on my page to those messages?
Comment: I found the resolution to this issue, and had to follow my digital breadcrumbs of frustration to fix the issue, again.

It turns out this was being caused by Commerce Price table not handling price tables with single price values ($19.95 for qty 1 to -1) the fix is a patch here: https://www.drupal.org/files/commerce_price_table-accept_single_valued_fields_in_rules_configurations-1981934-2.patch

I got this issue again after updating to v1.2. The patch has not been committed, yet. Hopefully the maintainers are willing to include it in the next update.
Comment: 3 years later....

I'm having this issue again. Only this time, the problem is not longer isolated to products with single price/qty values. Now, this occurring on a new product with 2 prices/qtys, and the patch linked above no longer applies correctly. This is a deeper problem than originally thought.
Comment: I've hit this bug as well. The patch did not work for me. I know this is old, but @zer0 or others, did anyone solve this issue definitively? How did you get past the issue in 2019?
Comment: @blue928 iirc it was similarly related to the answer from planettucker, below. i believe i fixed it by removing product variations that were no longer available, eith erby a rule or manually. hard to recall, i happily left that gig behind me and moved on to better things. sorry i can't be of more help :(
Answer: The actual issue here is that Commerce products cannot have a price of 'NULL' or empty. Commerce has requirements that typically prevents the price field from ever being null or empty, but certain modules or pricing calculations can override this default required behavior and basically leave the Price field "orphaned."
For my use case, it was with the Commerce Pricing Table module. The module removes the default requirement for Price and has a configuration option to hide it so that its pricing tables take precedence. The design flaw in that module is that it operates on Commerce Line Items but forgets to set a price for the Price field, even though that field is never used.
For us, we created a simple Rule.
-> Event: When saving a new product
-> Condition: if Empty Value = Price field
-> Action: set price to 0
In Commerce 1.x since a variation is simply an independent product with specific attributes, this makes sure that all items have at least a price of 0 and will function as expected.
Answer: In my case it depended on which variation I physically have first in the variation list. If the product I have first in the variation list has a price and positive stock number, then I get an Add To Cart button for all variations.
If the product I have first in the variation list does NOT have a price greater than $0 and positive stock number then for ALL variations I get "Product Not Available".
So for me physically dragging and changing the order of the variations is what changed whether I saw Add to Cart, or Product not Available - I had to have an eligible product listed first in the variation order.
The only catch is, it allows you to click the Add To Cart button on products that are not eligible for checkout, however it does not add anything to the cart or functionally mess things up.
Naturally I would prefer the Add To Cart button change dynamically depending on the status and info of that variation, but technically this works.


How to Get Input Text on Login Screen From RoundedTextField in React Native

Question: export default function LoginScreen() {
  return (
    <Screen>
      <View style={styles.containerView}>
        <Text style={styles.headerText}>LOGIN</Text>
        <Image
          style={styles.logoStyle}
          source={require("../assets/logo.png")}
        />
        <RoundedTextField placeholder={"Mobile Number"} />
        <Text>{**"Wants RoundedTextField's Text Here"**}</Text>
      </View>
    </Screen>
  );
}

export default function RoundedTextField({ placeholder }) {
  const [text, setText] = useState("");

  return (
    <TextInput
      style={styles.textInput}
      placeholder={placeholder}
      onChangeText={(newText) => setText(newText)}
      defaultValue={text}
    />
  );
}

Answer: You can pass a callback function from the parent LoginScreen component to the RoundedTextField component that will update the state of LoginScreen with the value entered in the RoundedTextField.
export default function LoginScreen() {
  const [mobileNumber, setMobileNumber] = useState("");

  const handleMobileNumberChange = (newMobileNumber) => {
    setMobileNumber(newMobileNumber);
  };

  return (
    <Screen>
      <View style={styles.containerView}>
        <Text style={styles.headerText}>LOGIN</Text>
        <Image style={styles.logoStyle} source={require("../assets/logo.png")} />
        <RoundedTextField
          placeholder={"Mobile Number"}
          onTextChange={handleMobileNumberChange}
        />
        <Text>{mobileNumber}</Text>
      </View>
    </Screen>
  );
}

export default function RoundedTextField({ placeholder, onTextChange }) {
  const [text, setText] = useState("");

  const handleTextChange = (newText) => {
    setText(newText);
    onTextChange(newText); // invoke callback function to update state in parent component
  };

  return (
    <TextInput
      style={styles.textInput}
      placeholder={placeholder}
      onChangeText={handleTextChange}
      value={text} // use "value" instead of "defaultValue" to set the initial value
    />
  );
}


Questions on JavaScript hoisting

Question: While I was reading about JavaScript hoisting, I tried the following. I am not sure why the first one and second one output differently. (I am not even sure that this is related to hoisting).
var me = 1;
function findme(){
   if(me){
    console.log( me );//output 1
    }
  console.log( me ); //output 1
}
findme();

However the following outputs undefined:
var me = 1;
function findme(){
 if(me){
    var me = 100;
    console.log(me);
    }
  console.log(me);
}
findme();
// undefined

Comment: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
Comment: The second internal `var` "hoists" `me` to the `findme` scope, so when the script is run after parsing, `me` in `findme` in the second example is "reserved" to the local, not global, `me`. Which is really `window.me`.
Comment: Because `if (me)` tests an `undefined` local variable reserved to that function scope. So the `if` never runs, because in that situation, `window.me` would reference your "other" global `me` in a way that is not ambiguous with `me` locally. It makes perfect sense if you lock onto that "hoisting" reserves a variable directly to it's local scope, but variables are set `undefined` until they are assigned directly. Functions hoisted, though, may be called as normal, if hoisted.
Comment: Thanks to all who replied to my questions. I feel so stupid because that's what I was reading whole day about the hoisting and I still didn't get it. Mmmm, I'm dumb.
Comment: @shin—the term "hoisting" is misleading jargon, it infers that the entire statement is moved to the top of the enclosing scope. What actually happens is that variable and function declarations are processed before any code is executed. So all declared variables are created and assigned a value of *undefined*, then the code is run (which may subsequently assign a different value).
Answer: Variable declarations get hoisted to the top of every function, but the value assignments stay where they are.  So the second example is run like this:
var me = 1;
function findme () {
    var me;  // (typeof me === 'undefined') evaluates to true
    if (me) { // evaluates to false, doesn't get executed
        me = 100;
        console.log(me);
    }
    console.log(me);
}
findme();

Comment: It's brought to the top of findMe.  This is why you always should declare your vars at the top of any function.
Comment: Very well explained.
Answer: The  declaration of thee local variable in the if block in the second example is hoisted to the entire function.
Thus, me in the function always refers to the local variable, not the global.
However, the value of the variable is not hoisted, so it's always undefined and the if is never entered.
Answer: Hoisting of a var does NOT hoist the assignment, just the declaration.  So it's being parsed like this:
function findme(){
  var me;
  if(me){
    me = 100;
    console.log(me);
  }
  console.log(me);
}

When the if statement runs, me is decalred local to the function, but is undefined (has no value). undefined is falsy so your condition is never true.
This is why it's customary to always declare your local variables at the top of functions, because that's where they go anyway, if you like it or not.
Comment: Declared variables are [initially assigned a value of *undefined*](http://ecma-international.org/ecma-262/5.1/#sec-10.5), they never have "no value". ;-)
Answer: I feel like the true answer to this question is often abstracted away by the term "hoist". Here is what is REALLY happening.
Every time a function is ran in JavaScript, a new execution context is created for that funciton which is pushed onto the execution stack. So in your second example you have the following code:
 var me = 1;
 function findme(){
    if(me){
       var me = 100;
       console.log(me);
    }
    console.log(me);
 }
 findme();
 // undefined

At the very beginning of the execution of this code (assuming this is the entirety of the JavaScript), the first thing to happen is that the JavaScript engine creates a global execution context. During it's creation it allocates the memory for all functions and variables within that context. Functions are allocated and initialized the way you may imagine, but variables are only allocated first (not properly initialized).
So after the creation of the global execution context in this example the function findme() would be allocated in memory in its entirety BUT the variable "me" would be allocated with an initial value of undefined. After the global execution context is created, the code is then ran. It finds var me = 1; and updates the "me" variable from undefined to 1. It really doesn't do anything with the function definition, but, then it finds a function invocation of "findme();".
At this point, we enter the findme() function. And really, the same thing happens all over again. An execution context is created for this function, which is pushed onto the global execution stack, and this becomes the running code. If you understood the first part of my discussion I think you will realize that the "console.log(me);" call after the "if" statement IS undefined. Why? Because when the findme() function execution context was being created it initially created the "me" variable because it saw within its context by the "var me = 100;" statement. However, "if" statements do not get dedicated execution contexts in terms of the global execution stack. Thus, when the "console.log(me);" OUTSIDE of the if is ran the me variable IS defined in the overarching context of the function. BUT you are trying to access a variable outside of its scope.
If you followed all of this, you now understand a major part of how the JavaScript engine works.

Questions on JavaScript hoisting


Windows Server - Dynamic update of DNS entries for hosts with static IP

Question: I am using Windows Server SBS 2003 as a DNS server. I also have some other servers configured with a static IP (ESXi hosts, Linux hosts, Windows Server hosts, ...) and I want them to be added automatically into the DNS.
These hosts has their hostname configured, but they dont register to the DNS, so I cannot access them with their hostname, I must use their IP address.
Please note that these hosts has static IPs.
How can I make these hosts to automatically add an entry for themselves on the DNS server so I can access them using their hostname?
Answer: One possible way would be to use DHCP, and configure reservations for those addresses from within your DHCP server.
Comment: http://serverfault.com/questions/332492/dns-records-not-being-discarded-or-updated-ms-server-2008-dns-w-dhcp
Comment: (and make sure your DHCP server is set to create entries in DNS for its clients)
Comment: And if the host is deleted from the DHCP reservations and removed from my network, how does the DNS entry is removed?


Problema no loop com switch case

Question: Eu refiz o codigo seguindo as orientações passadas aqui. Porem, voltou a ter o problema inicial... eu escolho a opção desejada, ele executa a ação desejada mas logo depois vai pro default do switch case e imprime "informação invalida"
Meu código está assim:
#include <string.h>
#include <stdio.h>
#define TAM 20
#include <ctype.h>

int menu(){
    char opc;

    printf("| A | Ler string\n");
    printf("| B | Tamanho da string1\n");
    printf("| C | Comparar strings\n");
    printf("| D | Concatenar strings\n");
    printf("| E | Imprimir string1 invertida\n");
    printf("| F | Quantidade de ocorrencias de um caractere na string1\n");
    printf("| G | Subsituir o primeiro caractere1 pelo caractere2\n");
    printf("| H | Retornar substring da string1\n");
    printf("| I | Sair\n");
    scanf("%c", &opc);

    return tolower(opc);
}

void pedirstr1(char *str1){

        printf("Entre com a string1: ");
        fflush(stdin);
        fgets(str1, TAM, stdin);
        str1[strlen(str1)-1] = '\0';
}

void pedirstr2(char *str2){

        printf("Entre com a string1: ");
        fflush(stdin);
        fgets(str2, TAM, stdin);
        str2[strlen(str2)-1] = '\0';
}

int main(){
    char str1[TAM] = " NULL ", str2[TAM] = " NULL ", char1, char2, c, opc = 'f', sair=0, c2, junto[TAM];
    int inicio, fim, contchar = 0;

    do {
        opc = menu();
        printf("\n\n");

        switch(opc){

        case 'a':
                //system("CLS");

                pedirstr1(str1);

                break;

        case 'b':
                //system("CLS");

                if (strcmp(str1, " NULL ") == 0){
                    printf("Nao existe nenhum valor na string1.\n");
                    printf("\n\n");
                } else {
                    printf("O tamanho da string1 e: %d\n", strlen(str1));
                    printf("\n\n");
                }

                break;

        case 'c':
                //system("CLS");

                pedirstr1(str1);
                pedirstr2(str2);

                if (strcmpi(str1, str2) == 0){
                    printf("As strings 1 e 2 sao iguais.\n");
                    printf("\n\n");
                } else {
                    printf("As strings 1 e 2 sao diferentes. \n");
                    printf("\n\n");
                }

                break;

        case 'd':
                //system("CLS");

                pedirstr1(str1);

                pedirstr2(str2);

                printf("string1 + string2 = %s%s\n", str1, str2); //posso usar strcat mas da ruim pq fica armazenado na variavel
                printf("\n\n");

                break;

        case 'e':
                //system("CLS");

                pedirstr1(str1);

                printf("String1 invertida: ");
                for (c=strlen(str1); c>=0; c--){
                    printf("%c", str1[c]);
                }

                printf("\n\n");

                break;

        case 'f':
                //system("CLS");

                pedirstr1(str1);

                printf("Letra que deseja contar: ");
                scanf("%c", &char1);

                for (c=0; c<strlen(str1); c++){
                    if (str1[c] == char1){
                        contchar ++;
                    }
                }

                printf("A letra %c aparece %d vezes na string1.\n", char1, contchar);
                printf("\n\n");

                break;

        case 'g':
                //system("CLS");

                pedirstr1(str1);

                printf("Entre com o caractere que deseja substituir: [diferencie maiusculas de minusculas]");
                scanf("%c", &char1);

                printf("Qual caractere deseja colocar no lugar? ");
                scanf("%c", &char2);

                for (c=0; c<strlen(str1); c++){
                    if (str1[c] == char1){
                        str1[c] = char2;
                    }
                }

                printf("Nova string: %s", str1);
                printf("\n\n");

                break;

        case 'h':
                //system("CLS");

                pedirstr1(str1);

                printf("A partir de qual posicao? ");
                scanf("%d", &inicio);

                printf("Até onde? ");
                scanf("%d", &fim);

                while (inicio > fim){
                    printf("A posicao de inicio deve ser menor do que a do fim. \n");

                    printf("A partir de qual posicao? ");
                    scanf("%d", &inicio);

                    printf("Ate onde? ");
                    scanf("%d", &fim);
                }

                printf("Substring: ");
                for (c=inicio; c<fim; c++){
                    printf("%c", str1[c]);
                }

                printf("\n\n");

                break;
        case 'i':
                sair = 1;

                break;

        default:
                //system("CLS");

                printf("Informacao invalida, tente novamente. \n");
                printf("\n\n");

                break;
        }
    } while (!sair);

    return 0;
}

Comment: Se você colocar um `fflush(stdin);` após o `scanf` da função `menu`, o que acontece? E se você colocar antes?
Comment: AAAAA FUNCIONOU
Answer: Tens o opc = menu(); fora do teu do while. Ou seja a tua variável opc não actualiza após cada ciclo fica sempre a mesma e mantém o 1º valor introduzido.
Exprimenta:
do {
    opc = menu();
    switch(opc){

    //resto do codigo

    }
} while (!sair);

Comment: tudo bem, sem problema. de qualquer forma, muito obrigada
Comment: Tu estás a usar `"NULL"`  ou seja a string null e não o valor `NULL` e como estás a fazer o `strcmp()` e tens diferente nº de espaços na tua string `"NULL"` vai dar errado exemplo: `"NULL    "` !=  `"     NULL"`.
Usa o valor NULL e não uma string com uma palavra, `str1[TAM] = NULL`.
Comment: Eu tentei colocar str1[TAM] = NULL, porem deu o erro "invalid initializer".Então resolvi tirar o teste pra ver se ja tinha algo na string, deixei ele apenas pedindo. porem continua com o mesmo problema citado acima. entao, eu testei ja colocando um valor na opc. por ex opc = 'f'. Dessa maneira, ele funcionou! pq quando eu peço pro usuario entrar com a opc ele não funciona corretamente?
Comment: `char str1[TAM]  str2[TAM],` e assim? Supostamente devem ser iniciadas por default a `NULL`
Comment: Mas em que case é que não funciona especificamente?
Comment: Eu editei a pergunta, pois fica mais facil de explicar por la
Comment: `scanf("%c", &opc);` porque é que tens `&opc` e não só `opc`?
Comment: mas se não colocar o & ele não guarda na memoria
Comment: Eu estive a ver e não encontro mais erro nenhum, espera que outra pessoa venha dar uma vista de olhos, desculpa eu não poder ajudar mais :(
Comment: Experimenta dar um print a `opc, str1, str2` antes do case para ver o que é que eles tem como valores guardados isso talvez ajude a fazer debug mais facilmente.
Comment: E já agora pergunta estúpida deste compile depois de teres feito as alterações, não estás só a correr o exec?
Comment: kkkk queria que o problema fosse esse. ate conferi aqui pra ter 100% de certeza... não e isso ;-;
Comment: Nunca se sabe, não seria a 1ª vez xD, mas faz um print do opc depois de seleccionares o opc.
Answer: Adicione
getchar();

Depois de
scanf("%c", &opc);

Quando você escolhe uma opção que não é de leitura e tecla ENTER. Ele realizar a operação que você escolheu e entende o ENTER que você deu como uma opção que você digitou também, com isso ele entra no default.

Problema no loop com switch case


Simple discount and effective interest

Question: Sylvia invests her money in an account earning interest based on simple discount at a $2$$\%$ annual rate. What is her effective interest rate in the fifth year?
The formula for effective interest rate is $r = (1+\frac in)^n -1$
The way I would do this is find $i$ which is $0.0204$
Then I would plug everything in $r = (1+ \frac {0.0204}{5})^5-1 $ and my answer is $2.056 \%$
However, when looking up solutions, this is what they did
They took $i$ and multiplied it by $5$ which equals to $0.1020$
Then their effective interest rate formula would look like this $r = (1 + 0.1020)^{1/5}-1$ and they get $.0196 \%$
What am I doing wrong?
Comment: how did you find i ?
Comment: $d = \frac {i}{i+1}$  $0.2 = \frac {i}{i+1}$
Comment: my thought was maybe you were thinking APR versus APY.
Comment: In case of simple interest the future value ($n=5$) is $C_0\cdot (1+i\cdot n)=C_0\cdot (1+i\cdot 5)$. $C_0$ denotes the present value. Do you agree ? Then the effective interest rate is $i_{eff}=\left(\frac{C_0\cdot (1+i\cdot 5)}{C_0} \right)^{1/5}-1=\left( 1+i\cdot 5 \right)^{1/5}-1$. Doesn´t it sounds logic.
Comment: $d$ is the rate of discount. See  here for an example and explanation. https://math.stackexchange.com/a/1346195/144421
Comment: @callculus The problem states simple discount!  You cannot use compound interest formula...
Answer: The annual effective rate of interest for year $t$, which we denote by $i(t)$, is the ratio of the amount of interest earned in a year, from time $t−1$ to time $t$, to the accumulated amount at the beginning of the year (i.e., at time $t−1$):
$$
i(t)=\frac{a(t)-a(t-1)}{a(t-1)}
$$
For the simple-discount method, we have $a(t)=\frac{1}{1-dt}$ where $d=2\%$ is the simple discount rate.
Observing that $a(5)=\frac{1}{1-0.02\times 5}=\frac{1}{0.9}$ and $a(4)=\frac{1}{1-0.02\times 4}=\frac{1}{0.92}$
$$
i(5)=\frac{a(5)-a(4)}{a(4)}\approx 2.22222\%
$$
NOTE: this exercise comes from the book Mathematical Interest Theory, 2nd ed. (Leslie Vaaler,James Daniel): ex. Sec 1.8 n. (2) at pag 65, sol. at pag. 441

Simple discount and effective interest


Forecasting A Noisy Time Series

Question: I have daily time series data of the number of views that a YouTube channel has, alongside daily data on the views that the videos in that channel receive.
I would like to predict three months of views given this data and am not sure how to go about this.
I was thinking of the following:
(1) Time series regression after removing trend, and test for the optimum amount of lags. We do not need our forecasts to be incredibly precise, but a realistic view of where a channels views might be in 6 months.
(2) as above, but with the views of a channel and daily views of certain videos. The problem with this approach is that maybe some videos are two weeks old, and are contributing a lot to views, and some are really old and do not contribute much, or have spent their potential views in early years. Our problem with this approach is that we now are working with time series of uneven length, so I am stuck here.
Has any thoughts or ideas?
Also please assume that I know only regression models, but am open to learning anything that will help with the problem above
Answer: One possibility would be to forecast each video's views using exponential smoothing. Potentially include seasonality if there is evidence of intra-weekly seasonality. Also include a trend.
Consider modeling and forecasting cumulative views. This will probably increase very quickly at the beginning, and then the increase will taper off. So it would make sense to include a dampened trend.
Alternatively, you could look at regression with ARIMA errors, where you could include "bump functions" to model a video's "lifecycle". Or Bass diffusion models, which explicitly model market growth and saturation.
In addition, you can probably improve your forecasts by leveraging the hierarchical structure. Forecast each video separately, as above. Also forecast the entire channel's views. Then combine the forecasts using the optimal combination approach (see here). This even allows you to use different forecasting methods for the different videos. I have repeatedly found that this approach improves forecasts on all levels of a hierarchy.

Forecasting A Noisy Time Series


specific machines on subnet randomly lose connectivity, but the rest of the network is fine

Question: Every physical machine is connected to a cisco switch and is on the same network 192.168.1.0/24
Every server I have is running Centos 6.5.  A couple run KVM with a bunch of virtual machines.  Most of the machines have bonded nic's.
Machines:
virtual server (vs0) has a bunch of vm's (vm00, vm01)
virtual server (vs1) has a bunch of vm's (vm10, vm11)
then I have a some other random physical machines (web0, web1)
Normally, everything works fine, but occasionally, certain machines will lose connectivity.
web0 cannot ping vm11
web0 can ping web1, vs0, vm00, vm01, vs1, vm10
vm11 cannot ping web0
vm11 can ping web1, vs0, vm00, vm01, vs1, vm10
All other machines can ping every other machine
And then 30 minutes later, everything is fine again.
Occasionally, web0 can't see web1, so I don't think its a KVM thing.  And when web0 can't see vm11, web0 CAN see vs1, so I don't think its a nic issue.
I tried tcpdump on the machines and no packets are hitting the machines except ARP packets.  I don't know what else to look for.  I'm out of ideas for debugging this.  Any ideas?
Comment: Have you checked for error stats on the switch itself?
Comment: I don't know exactly what I'm looking for, but the switch has 0 drop events, CRC & ALign Errors, Undersize/Oversize Packets, Fragments, Jaggers, Collisions (from Status and Statistics->RMON->Statistics).  I'll continue to look for additional information in the switch though.
Comment: Under View Log->RAM Memory, there is nothing from May except my login.  I see some link up and link down entries from a while ago, but I assume those are from me plugging stuff in.  There are no entries during the time period today when the machines lost connectivity.
Comment: From one server that web0 can ping, and one it can't, use arp to check what it thinks the MAC address for web0 is.  I suspect its an arp issue caused by the bonding.
Answer: I wonder if the problem relates to the way the bonding is being done, and the switch getting confused with MAC addresses on ports etc.
I'm guessing you are using "Mode 0" for bonding. Try changing things to Mode 1 (Active-backup), or (temporarily) dropping one of the underlying bonding interfaces on each device and see if that makes things more stable.
Comment: annoyingly, I couldn't get it to break again so I could look at arp values.  i went ahead and just updated the bonding mode to 5.  https://bugzilla.redhat.com/show_bug.cgi?id=584872#c16
Comment: I'm actually using mode 6, BONDING_OPTS="mode=6 miimon=100", but I will try dropping a connection when I get back to work on monday and see what happens.


Second Species Counterpoint

Question: I am working on a second species counterpoint and I am a bit stuck. This is what I have so far:

Any tips for where to go from here? The exercise I found online gave me all the notes of the CF and only the first 3 notes of the counterpoint below.
Comment: Just to clarify: the initial "E F# G" of the counterpoint were given, and the following "E D E" were added by you?
Comment: I've done a possible version of the 8 bars, but I am not able to upload the image.  It keeps saying it is too big.  :(  Sorry - I've not tried to add an image here before.  If it's of any use, I could explain to you what I did, and you could write the notes down Also, I could explain what I did and why.
Comment: @Aaron yes, correct!
Comment: @Jomiddnz if you want you could explain it here or email it to me: email@example.com
Comment: @Jomiddnz it might be easier to email it to me. thanks
Answer: I think the biggest sticking point may be the final sixteenth note you have in the opening measure. That last E, if it's intended to be a passing tone within the second-species guideline, is actually impossible to use correctly, because it would necessitate an F♯ on the downbeat of the next measure, which would be a dissonant tritone with the soprano C (and thus not allowed).
Try changing that E to another consonance with the B and see if that helps get you going in the second measure.
Comment: thanks! I changed it to a G which is a third. But then I am repeating a G in the same measure.

Second Species Counterpoint


hook_views_pre_render and hook_node_view

Question: In my custom module I'm creating a logic with two fields.
The first field is an image and the second is date field.
When I choose past date from the date field, the image field should be hidden. If the date value is present or made in future, the image will be visible.
It's working great on hook_node_view, but I can't figure out how to do this on views.
Here's my code:
<?php
function custom_alter_node_view($node, $view_mode, $langcode) {
 if ($node->type == 'hot_offers') {
    $c = strtotime($node->field_hot_offers_new_date['und'][0]['value']);
    $current_time = date("m/d/Y H:i:s");
    $d = strtotime($current_time);
    if ($c < $d) {
    $node->content['field_hot_offers_new_image']['#access'] = FALSE;
    }
  }
}

I know there's a hook_views_pre_render, but how do I create the same logic, so the image will be visible only if the date field value will be present or in future?
Comment: I would give hook_field_access a go. I think both views and node_view will take your access rule into account. https://api.drupal.org/api/drupal/modules!field!field.api.php/function/hook_field_access/7
Comment: In broad strokes, in `hook_views_pre_render(&$view)` you would look first at `$view->name` and then on the correct view, look inside its `$view->result` and unset or otherwise modify your image field therein based upon similar logic as above.
Answer: I've solved the puzzle and I'm sharing the solution.
function custom_alter_views_pre_render(&$view) {
    if ($view->name == 'hot_offers') {
        //dpm($view);
foreach ($view->result as $key=>$value) {
    $c = @$value->field_field_hot_offers_new_date[0]['raw']['value'];
    $d = date("Y-m-d"); //2014-06-26
    if ($c < $d) {
    $value->field_field_hot_offers_new_image[0]['rendered']['#access'] = FALSE;
    }
  }
 }
}

The tricky part was to set the $d same format as the new_date field, otherwise the if statement logic will not work.
Answer: You can do it using any of the following ways.

Install View PHP module and you will get a gobal php field in the views where you can write your logic as a php code.
Or as Jimajamma said, in hook_views_pre_render(&$view) you can check $view->name and unset the values from $view->result.
Or you can write your own views custom field handler for the image field and write your logic to display the way you want.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackoverflow.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


How can I commit/push my Android Studio project to another GitHub repository?

Question: I'm currently building an app with one of my coworkers and we came across a problem.
We already have one GitHub repository where everything is committed. But we wanted to create another repository so we can change the code etc. without damaging the original.
We added the new remote to the project and have removed the old one but now, when we try to commit, it still wants to commit to the original.
How do we change that?
Comment: The whole point of git is to be able to change the code etc. without damaging the original. Committing and then pushing to the existing repo does not damage anything.
Answer: You can use the set-upstream command to connect your local branch to a new branch in the origin:
git push --set-upstream <remote> <branch>

I am not shure if this will also work with a branch that is part of another repository though.
Anyway you dont need a new repository I think. What you are describing can be done by creating a new branch on your repo. Often you will find projects organized like this:

master-branch: this is there the official/ release version of your code lives
development-branches: here you and your colleges can add new features and test them without affecting the master branch or other development branches.

When you are done with a new feature, you can create merge-requests to add it to the master branch. You should have a look at git workflows to understand how to work with git:
https://git-scm.com/docs/gitworkflows
Hope this helps
Answer: The commit itself happens on your local machine, it continues to do so after adding a 2nd remote or replacing the 1st remote. It's the push command that you are looking for, I believe.
You can push to your specific remote with a command like:
git push <remote> <refspec>
Where remote is typically (but not always) origin. If in doubt you can find the name with the git remote command.
The refspec can be left empty to push all new commits on branches that are already on your remote, or set to a specific branch or several other values of what you'd like to push.
Note that in your case, assuming the new remote does not have your branch yet, it is crucial to set refspec for your first push. Check the documentation of the git push command for a more complete explanation of how to use these options.