Tallest height matching next element

Question: I usually use this to match elements heights:
function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
    }

    $(function() {
        equalHeight($('.column'));
    });

However, in my case I need to match elements to their nearest sibling not by class, with the following example

This is a post headline

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volut

There will be multiple (over 15) instances per page of this structure. I don't want to match the height of ".leftCol" to the height of ".rightCol" across the board - that is I don't want every ".leftCol" to match every ".rightCol" on the page, just within each ".post" group - match ".leftCol" height to its immediate sibling of the ".rightCol" class... any ideas?
Answer: If what you're trying to do is to set each leftCol/rightCol pair to the taller of either one, but only within the pair and you want to do the same for all pairs, you can do it like this:
$(".post .leftCol").each(function() {
    var $left = $(this);
    var $right = $left.next();
    var maxHeight = Math.max($left.height(), $right.height());
    $left.height(maxHeight);
    $right.height(maxHeight);
});

This code works as follows:

For each .post .leftCol object
Get the .leftCol jQuery object
Get the matching .rightCol jQuery object using .next()
Find out the max height between the two of them
Set this .leftCol and .rightCol pair each to that max height

Note: you may be able to solve this problem with CSS alone.  See CSS - Equal Height Columns?.
Comment: perfect. you're a friend indeed, thanks man. I am now at least getting the concept mostly right but still suck on execution.

Tallest height matching next element


Power Apps runs on Android Device Without Microsoft Power Apps

Question: I created an app in Microsoft Power Apps. how do execute an app without Microsoft Power Apps?
Comment: "How to" questions are too broad off-topic questions in SO..
Comment: Do you want to run the power app using web URL or you want something like you could download it from playstore or app store and use it?
Answer: Apps made with PowerApps can be only used with either the browser using https://home.dynamics.com or with the PowerApps apps from the respective Apple, Google or Microsoft stores. They cannot be used outside of the PowerApps ecosystem.
Answer: No, it only run in Microsoft power platform or used with either the browser (like https://home.dynamics.com, here 'home' is your app name when you create)
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).
Answer: You can't do that you will need the Powerapps client in platform that you want to use.
Answer: Microsoft power apps do not give the freedom of allowing their apps to run outside their ecosystem like a standalone app. Every app developed and deployed using powerapps must still run in Microsoft ecosystem.
You can also use the play.powerapps.com to preview them on any browser after authenticating with your power apps login.
Answer: The problem is that you can't install the application as a stand-alone programme. If you don't have a power apps account, you can't utilise the programme since Microsoft only allows you to create and share programmes in the power apps environment. Outside of the power apps' environment, it cannot be accessed.
Use Chrome or another browser to access it.
just follow the steps:

login to your power apps account.
open your app and then go to file menu.
then go to share tab.
There, you must enter the mail ID of the person you wish to share the application with.
When you do this, an email created by Outlook will be sent to the recipient you specify, notifying them that you have shared the application with them. then they can use the URL they received in the mail to access the application. (The user must possess a power apps account.)
or you could share the link by going to the details option in your power apps and from there you can copy the web link to access the applicaion. but first you need to follow the steps mentioned in step 4.

If you find this answer helpful please mark it as solved.
or you could tell me whether it is helpful or not using comments.
Happy development :)
Answer: This is now possible using the App Wrap feature.
Once you enable this feature in your environment you can wrap an app which generates an android and/or iOS app which you can sign and deploy.
You can find the latest documentation for how to it here:
https://learn.microsoft.com/en-us/power-apps/maker/common/wrap/overview
Answer: It is recommended to use power platform application in your device and access the app you built.
Answer: You can run them in the web without installing PowerApps for Android. Go to https://web.powerapps.com/ on your phone's browser to see your list of apps and run them.
Comment: Thanks for your help. I need another help. Can I use web apps without Microsoft  Organisation  account Authentication?  We need to use dynamics 365 portal authentication in Power Apps. Give a video demo or tutorial


Differential linear equation first order?

Question: I have the equation $(1+y^2)\,dx+(xy+1)\,dy=0$.
It is a linear differential equation of the first order.
Now the problem is that this doesnt have the regular form of this type of equations which is $$\frac{dy}{dx}+p(x)y=q(x) \ .$$
I know I can divide both sides by $dx$ and then I'll have $(1+y^2) +
(xy+1)y'=0.$ Still, it should be $(xy+1)+y'$ not $(xy+1)y'$.
Comment: It is linear for $x$ as a function of $y$, not the other way 'round.
Answer: If you set $M(x,y)=(1+y^2),~~N(x,y)=xy+1$, you see that $$M_y=2y,~~N_x=y$$ and $$\frac{M_y-N_x}{-M}=\frac{-y}{1+y^2}$$ is a function respect to $y$. Now think of an integrating factor $\mu(y)$ and then make your OE exact.
Comment: ..•¤*Excellent*¤•..@Babak S. シ
Comment: @flashdesign2550: $\ddot\smile$
Comment: Babak you are awesome :)
Comment: Indeed, awesome!! $\ddot\smile$
Comment: @amWhy: Thanks for saying so. I saw you are full, and cannot make additional plus :-)


how to get the '0' entry in object

Question: I have the following object:
<code>stdClass Object ( [0] => stdClass Object ( [img_id] => 56 [img_name] => 5c9eeb51930ebe222ab26895dab7c348.png ) )
</code>
It is being dumped into a variable called $image_names. I am trying to get the entry for [0].
I have tried:
$image_names->0 but I get the error: syntax error, unexpected T_LNUMBER
I even tried $image_names[0]. I realize this should not work, but I thought I would give it a try. This does not return an error. But, it also does not return the data.
In this object structure, how do I get the object associated with the key [0]?
Answer: Same as always.
<code>$image_names->{'0'}
</code>
Comment: Thanks. That was it. I've never had to access an object like this, so I don't have a 'Same as always'. Do you happen to know why the '0' has to be in curly brackets like that?
Comment: Because you're using a string for the attribute.
Comment: 0 is a string? I realize it can be, but here it appears to be a number. BTW, I am not questioning you, obviously you know, since your solution worked, but I am just wondering why you cannot use $var->0.
Comment: `0` is a number. `'0'` is a string. You cannot use literals to access attributes directly.
Comment: I think I understand. Are you saying in the object I posted, the '0' is not actually a number but rather some other data type?
Comment: Correct. It is a string.
Comment: I see. Thanks for the lesson Ignacio.

how to get the '0' entry in object


looping to find sum of array java

Question: I am making program that adds up the values from an array of a class. I keep getting an error about binary operators. My code is:
public static int sum(Array[] x){
   int sum = 0;
   for (int i = 0; i < x.length; i++){
       sum += x[i];
   }
   return sum;
}

Thanks in advance!
Comment: please include the full stacktrace. and shouldn't `Array[] x` be `int[] x`?
Comment: What does your `Array` class look like?
Answer: It seems you are using an Array[], and there is no operator+ for the type Array (which is the type of x[i])
You probably wanted int[] as the type of x.
public static int sum(int[] x){
//                     ^^
//               note the fixed type of the array
   int sum = 0;
   for (int i = 0; i < x.length; i++){
       sum += x[i];
   }
   return sum;
}

Bonus: For simplicity and readability - you might want to consider using a for-each loop
public static int sum(int[] x){
       int sum = 0;
       for (int e : x){
           sum += e;
       }
       return sum;
}

Answer: your parameter is an array with type Array.
What are you expecting to see an int "+" an Array object?
Answer: You need to use int[] and not Array[] which is a generic type.

looping to find sum of array java


Is it meaningful to calculate standard deviation of two numbers?

Question: I am doing a biological experiment to measure a biologically relevant quantity, say concentration of a chemical in my cells. Ideally, I would do 3 or 5 or some number of replicates of my experiment to get an estimate of mean and standard deviation. But due to time limitation, complexity of my experiment and costs involved, I can only do two replicates. Now, I end up with two estimates of concentration. No one questioned me when I took the mean of these two quantities. But people were uncomfortable when I calculated the standard deviation. I could understand their concern but I want to get more insights into why it is ok or not ok to take standard deviation in this case? If it is not ok, what are my options?
Comment: Yes, 12.71, not 1.96.  Of course, the error bars will be wide. But that is the penalty you incur for having such a small sample.
Comment: If you can get up to 3 data points, the multiplicative factor on the sample standard deviation to get a two-sided confidence interval goes down from 12.71 to 4.30.  That's a 66% savings. And if you act in the next 15 minutes, I'll give you some additional "savings" in the form of n-1 vs. n not dinging you as badly in the denominator of the formula for sample standard deviation when n = 3 vs. 2.
Comment: If your data is Normally distributed, then don't forget to apply the necessary multiplicative factor to the sample standard deviation to get, say, a 95% two-sided confidence interval.  That is based on a Student t distribution with 1 degree of freedom, and is a whopping 12.71, in contrast to the value of 1.96 to which fans of the Normal distribution are so accustomed.
Comment: I think my comment above, from before your update, is getting to the nub of the matter. Try running that by the uncomfortable people.
Comment: So you mean that the estimate of std dev should be multiplied by 12.71 to get the error bars?
Comment: That is disheartening but I see your point. Thanks! Please let me know if you think there is any better way of quantifying the agreement between replicates for my data. It seems error bars will make my data look bad. Not that I want to deceive my audience but I believe my data is good.
Comment: Hmm, life is tough. No gains without pains. I'll work on the 3rd data point. :-/
Comment: Do you you have two observations, or two samples containing multiple observations?  It's not clear.
Comment: @david25272 I have both.
Comment: Dear @MarkL.Stone , I regret that I have only one "upvote" to give to your "up to 3 data points" comment above. However, as a special bonus offer, I will also upvote your compilation and expansion below! Extra credit for your patient dialog with Jon.
Comment: @MarkL.Stone: a dinging in the denominator sure sounds painful…!
Answer: Compilation and expansion of comments:
Let's presume your data is Normally distributed.
If you want to form two-sided error bars (or confidence intervals), say at the 95% level, you will need to base that on the Student t distribution with n-1 degrees of freedom, where n is the number of data points. You propose to have 2 data points, therefore requiring use of Student t with 1 degree of freedom.
95% 2-sided error bars for n = 2 data points require a multiplicative factor of 12.71 on the sample standard deviation, not the familiar factor of 1.96 based on the Normal (Student t with $\infty$ degrees of freedom).  The corresponding multiplicative factor for n = 3 data points is 4.30.
The situation gets even more extreme for two-sided 99% error bars (confidence intervals).
As you can see, at either confidence level, there's a big "savings" in the multiplicative factor if you have 3 data points instead of 2.  And you don't get dinged as badly by the use of n-1 vs. n in the denominator of sample standard deviation.
<code>  n  Confidence Level  Multiplicative Factor
  2       0.95              12.71
  3       0.95               4.30
  4       0.95               3.18
  5       0.95               2.78
 infinity 0.95               1.96

  2       0.99              63.66
  3       0.99               9.92
  4       0.99               5.84
  5       0.99               4.60
 infinity 0.99               2.58
</code>
Comment: @Johnnyboycurtis The confidence intervals are wide, as seen from the very large multiplicative factors arising from a t distribution with 1 degree of freedom. Whether they are 'satisfying" is another matter. The typical uncomfortable people were probably thinking in terms of Normal Z for multiplicative factor, not t with 1 degree of freedom.
Comment: Normal assumption is just as valid whether 2 data points or a million. There's no averaging going on here as in Central Limit Theorem. But yes, Normal assumption is crucial, that's why at the beginning of  my answer I stated "Let's presume your data is Normally distributed." I would discuss the Normality assumption if presenting this to anyone, whether 2 data points or a gazillion.
Comment: "But people were uncomfortable when I calculated the standard deviation. I could understand their concern but I want to get more insights into why it is ok or not ok to take standard deviation in this case? If it is not ok, what are my options?" -- this question still remains. I am in disagreement of using CIs for only two samples. With n = 2, you basically get a meaningless SD and CIs.
Comment: whether t or Z you're still assuming the data is approx. Normal after some large sample size; this assumption does not hold well with n = 2.
Comment: I think you need to ask yourself, would you be comfortable presenting this to a room of statisticians?
Comment: Alright, well, you've discussed what would happen if the data were to be approx. Normal. Now, what would happen if it were not?
Comment: Then all the error bars, confidence intervals, or whatever you want to call them would be bogus, regardless of the number of data points. The bogusness is likely to be moist severe at high confidence levels, i.e., in the tails, where deviations from Normality are likely to be most severe.
Comment: Great, answer. Now how would you test if the data were approx. Normal for n=2?
Comment: I wouldn't. It would have to be based on a priori knowledge. And with that, I shall now move on to other endeavors. Thanks for the chat.
Answer: Setting aside your initial explanation of the time-series context, it might be useful to look at this as a simple case of observing two data points.  For any two observed values $x_1 , x_2$ the sample standard deviation is $s =  |x_2 - x_1| / \sqrt2$.  This statistic is exactly as informative as giving the sample range of the two values (since it is just a scalar multiple of that statistic).  There is nothing inherently wrong with using this statistic as information on the standard deviation of the underlying distribution, but obviously there is a great deal of variability to this statistic.
The sampling distribution of the sample standard deviation depends on the underlying distribution for the observable values.  In the special case where $X_1, X_2 \sim \text{IID N}(\mu, \sigma^2)$ are normal values you have $S \sim \sigma \cdot \chi_1$ which is a scaled half-normal distribution.  Obviously this means that your sample standard deviation is quite a poor estimator of the standard deviation parameter (biased and with high variance), but that is to be expected with so little data.
Comment: Isn't the standard deviation formula you write the population standard deviation, and sample standard deviation would be more appropriate? Using the sample standard deviation, for n=2 the standard deviation is identical to the range/difference of the two data points, and the relative standard deviation is identical to the percent difference. Thus, the standard deviation is certainly meaningful.
Comment: I ran through the derivation, you are correct that the sample standard deviation simplifies to $s=|x_2-x_1|/\sqrt{2}$.
Answer: If you only have 2 values, just present those 2 values.  It doesn't make sense to convert 2 measurements into 2 other quantities (mean and stdev) if your audience is going to argue about the significance of one or the other.
If you want to estimate uncertainty, these other responses are right on, but don't forget to add other potential sources of error (measurement instrument bias errors, resolution, etc.).
Answer: " I know that you could compare the two time series by taking Pearson correlation and such" -- this is incorrect. Pearson Correlation assumes observations are independent, but time series data is by nature not independent. You would actually need to use a cross-correlation. Reference: https://web.archive.org/web/20160302024823/https://onlinecourses.science.psu.edu/stat510/node/74
Also, you shouldn't use the typical variance (if you really must calculate a variance); I suggest using something like Mean Absolute Deviance (MAD). You can then create a histogram to summarise the distribution of similarity/dissimilarity.
Comment: thanks for the answer. please look at my updated question.


Área de cadastro de clientes em WordPress

Question: Existe algum plugin que faça cadastro de clientes para o wordpress?
Preciso de uma área separada da área de login onde clientes possam se cadastrar para receber arquivos e afins.
Obs.: preciso que esses clientes tenham seu cadastro a parte dos usuários com acesso ao painel administrativo.
Answer: Você pode usar o https://wordpress.org/plugins/customer-area/
Sempre foi muito útil em alguns projetos que precisei.


C# ImageButton Click event not fired

Question: Code first:
public class ExtendedGridView : GridView
{
    private ImageButton m_btnPrint;
    public ImageButton PrintButton
    {
        get { return m_btnPrint; }
        set { m_btnPrint = value; }
    }

    protected override void OnPreRender(EventArgs e)
    {
        base.OnPreRender(e);

        PrintButton = new ImageButton();
        PrintButton.Click += new ImageClickEventHandler(OnPrintButtonClick);
        PrintButton.AlternateText = "Print";
        PrintButton.ImageUrl = "../../Images/Print.png";

        TableCell cell = new TableCell();
        cell.Controls.Add(PrintButton);
        cell.ColumnSpan = this.FooterRow.Cells.Count;

        this.FooterRow.Cells.Clear();
        this.FooterRow.Cells.Add(cell);
    }

    public void OnPrintButtonClick(object sender, ImageClickEventArgs e)
    {
        // Do Stuff
    }
}

This bit of code is intended to replace the footer content with an image button, and it does this fine. The plan is to handle the click event in the same class but I can't get the method 'OnPrintButtonClick' to go, it just won't break there. The page does, however, seem to be doing a post back. There have been questions on this before on this site but I haven't seen an answer yet.
Thanks in advance
Comment: Where is OnPrintButtonClick being wired up?
Answer: This is a page lifecycle problem.
You're adding the ImageButton to the page (and registering your handler) during the PreRender phase, which occurs after control events have been dispatched. Therefore, your handler will never be called.
Try adding the button during the Load phase, if at all possible.
Comment: I overrode OnLoad instead of OnRender

C# ImageButton Click event not fired


How can I change the onClick action of a ImageView dynamically?

Question: I have a ImageView that does an action called setAsFavorite(). This action sets a product as favorite, so I change the image of the ImageView. But when the product is favorite, I want to change the onclick event, so when the user presses the imageView, the action called should be unsetAsFavorite() instead of setAsFavorite.
How can I change the onclick event dynamically?
Comment: Handle a boolean value on click event of imageview. Based on that, you can change the image of imageview.
Answer: The answer given by av_lee is sufficient. But there is a better option.
Use if instead,
 boolean isFavourite = false;

    public void switchFavorite(){//Replace function setAsFavorite() with this
          if(isFavourite)
              isFavourite = false;
          else
              isFavourite = true;
    }

This way you decrease the number of function needed for the job.
Answer: You could use A flag to know if it has been set as favorite then act on that
yourImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
               if(isSetAsFavorite){
                   unsetAsFavorite();
                 } else {setAsFavorite();}
            }
        });

where is isSetAsFavorite is of boolean type.
Answer: I think there are two operation in your onclick method setAsFavorite() & unsetAsFavorite()
int myFlag =0;

onclick(){

   if(myFlag == 0)
        setAsFavorite();
   else
        unsetAsFavorite();

}

void setAsFavorite(){

   myFlag = 1;

   //do your work...

}

void unsetAsFavorite(){

   myFlag = 0;

   //do your work...

}

Answer: Get a reference to your ImageView:
getView().findViewById(R.id.your_img_view_id)

and then assign a new listener to it like this:
yourImageView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // your code here
                }
            });

This way you change an old listener with the new one.


TypeError: Cannot read property 'minify' of undefined

Question: So, since yesterday I've started getting the following build errors when attempting to deploy my project to either Heroku or Now. Locally, the project works completely fine. What's the issue here and how do I resolve it?
On Now the logs read as follows:

02/04 10:38 AM (7m)
Error: static/chunks/commons.2ab19e066e0721785714.js from Terser
TypeError: Cannot read property 'minify' of undefined
    at minify (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/minify.js:162:59)
    at TaskRunner.boundWorkers (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:62:41)
    at enqueue (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:82:14)
    at tryCatcher (/tmp/3d5396dc/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:690:18)
    at _drainQueueStep (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:138:12)
    at _drainQueue (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:131:9)
    at Async._drainQueues (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:147:5)
    at Immediate.Async.drainQueues (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:17:14)
    at runCallback (timers.js:794:20)
    at tryOnImmediate (timers.js:752:5)
    at processImmediate [as _immediateCallback] (timers.js:729:5)
    at Function.buildError (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/index.js:111:14)
    at results.forEach (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/index.js:255:50)
    at Array.forEach (<anonymous>)
    at taskRunner.run (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/index.js:242:17)
    at step (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:76:9)
    at done (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:84:30)
    at boundWorkers (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:89:13)
    at TaskRunner.boundWorkers (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:64:11)
    at enqueue (/tmp/3d5396dc/node_modules/terser-webpack-plugin/dist/TaskRunner.js:82:14)
    at tryCatcher (/tmp/3d5396dc/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/tmp/3d5396dc/node_modules/bluebird/js/release/promise.js:690:18)
    at _drainQueueStep (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:138:12)
    at _drainQueue (/tmp/3d5396dc/node_modules/bluebird/js/release/async.js:131:9) Error: static/runtime/webpack-42652fa8b82c329c0559.js from Terser

And on Heroku they read as:

2019-02-04T10:58:23.286953+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:23:31)
2019-02-04T10:58:23.286955+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:1337:18)
2019-02-04T10:58:23.286956+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:23:31) code: 'MODULE_NOT_FOUND' }
2019-02-04T10:58:23.287670+00:00 app[web.1]: (node:30) UnhandledPromiseRejectionWarning: Error: Cannot find module 'graphql-tools'
2019-02-04T10:58:23.287672+00:00 app[web.1]:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
2019-02-04T10:58:23.287674+00:00 app[web.1]:     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
2019-02-04T10:58:23.287675+00:00 app[web.1]:     at Module.require (internal/modules/cjs/loader.js:637:17)
2019-02-04T10:58:23.287676+00:00 app[web.1]:     at require (internal/modules/cjs/helpers.js:22:18)
2019-02-04T10:58:23.287678+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:2110:18)
2019-02-04T10:58:23.287679+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:23:31)
2019-02-04T10:58:23.287680+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:341:31)
2019-02-04T10:58:23.287681+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:23:31)
2019-02-04T10:58:23.287682+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:1337:18)
2019-02-04T10:58:23.287683+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/index.js:23:31)
2019-02-04T10:58:23.287772+00:00 app[web.1]: (node:30) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 133)
2019-02-04T10:59:23.314730+00:00 app[web.1]: { Error: Cannot find module 'graphql-tools'
2019-02-04T10:59:23.314741+00:00 app[web.1]:     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
2019-02-04T10:59:23.314743+00:00 app[web.1]:     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
2019-02-04T10:59:23.314745+00:00 app[web.1]:     at Module.require (internal/modules/cjs/loader.js:637:17)
2019-02-04T10:59:23.314746+00:00 app[web.1]:     at require (internal/modules/cjs/helpers.js:22:18)
2019-02-04T10:59:23.314748+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:2110:18)
2019-02-04T10:59:23.314750+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:23:31)
2019-02-04T10:59:23.314752+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:341:31)
2019-02-04T10:59:23.314753+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:23:31)
2019-02-04T10:59:23.314755+00:00 app[web.1]:     at Object.<anonymous> (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:1337:18)
2019-02-04T10:59:23.314756+00:00 app[web.1]:     at __webpack_require__ (/app/.next/server/static/KANAUI~IRZ6dj1SV~XfmF/pages/_app.js:23:31) code: 'MODULE_NOT_FOUND' }
Answer: This issue has been fixed a short time ago:
https://github.com/webpack-contrib/terser-webpack-plugin/issues/66
The reason why it worked locally is because you might have had the old version still cached.


NFL players with at least 5 Super Bowl rings

Question: The New England Patriots beat the Atlanta Falcons in overtime of Super Bowl 51 (2017) to win the Lombardi Trophy. This makes Tom Brady (the quarterback of the New England Patriots) the first Quarterback to win 5 Super Bowls. How many players in any position have won at least 5 rings, strictly as a player?
Comment: Related: [Which world leader holds the record for the most Super Bowl rings held?](http://www.cbssports.com/nfl/news/heres-how-vladimir-putin-stole-a-super-bowl-ring-from-the-patriots-robert-kraft/)
Comment: @CodeNewbie You're confused that wasn't stealing that was [civil forfeiture](https://en.wikipedia.org/wiki/Civil_forfeiture_in_the_United_States) Putin was just reading up on US law and decided it was a cool tool.
Answer: According to Wikipedia on Super Bowl Rings, at least 24 people have 5+ rings.  However, only 2 have 5+ rings as players:

Charles Haley (two with San Francisco and three with Dallas, all as a player)
Tom Brady (five as quarterback of New England)

In addition, three of the people who have 5 or more rings have some of them as a player.


Conectar colunas de diferentes tabelas

Question: SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
    ,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS WHERE HR.EMPLOYEES.DEPARTMENT_ID = DEPARTMENT_ID) AS 'Department Name'
    ,e.SALARY AS 'Base Salary'
FROM [HR].[EMPLOYEES] e
WHERE e.COMMISSION_PCT IS NOT NULL AND e.SALARY IS NOT NULL
UNION
SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
    ,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS WHERE HR.EMPLOYEES.DEPARTMENT_ID = DEPARTMENT_ID) AS 'Department Name'
    ,e.SALARY AS 'Base Salary'
FROM [HR].[EMPLOYEES] e
WHERE e.COMMISSION_PCT IS NULL AND e.SALARY IS NOT NULL
ORDER BY e.SALARY DESC;

UPDATE
SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS d WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID) AS 'Department Name'
,(SELECT JOB_ID FROM HR.JOBS k WHERE e.JOB_ID = k.JOB_ID) AS 'Job ID'
,MAX(e.SALARY)AS 'Base Salary'
FROM HR.EMPLOYEES e
WHERE e.SALARY IS NOT NULL
GROUP BY e.SALARY
ORDER BY e.SALARY DESC

Quando tento ir buscar o nome do departamento que se encontra em HR.DEPARTMENTS, e tento fazer corresponder o DEPARTMENT_ID das duas tabelas, dá-me o seguinte erro:

The multi-part identifier "HR.EMPLOYEES.DEPARTMENT_ID" could not be bound.

Como posso resolver?
Answer: Tente isso:
SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
    ,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS d WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID) AS 'Department Name'
    ,e.SALARY AS 'Base Salary'
FROM HR.EMPLOYEES e
WHERE e.COMMISSION_PCT IS NOT NULL AND e.SALARY IS NOT NULL
UNION
SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
    ,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS d WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID) AS 'Department Name'
    ,e.SALARY AS 'Base Salary'
FROM HR.EMPLOYEES e
WHERE e.COMMISSION_PCT IS NULL AND e.SALARY IS NOT NULL
ORDER BY e.SALARY DESC;

Assim você chama a mesma referência para o HR.EMPLOYEES, que chamou de "e" no "FROM", colocando também um identificador para DEPARTMENTS.
Além disso, retira os colchetes de identificadores das chamadas:
https://docs.microsoft.com/pt-br/sql/relational-databases/databases/database-identifiers?view=sql-server-2017
Agora uma dúvida, tem certeza que precisa fazer um union pra essa query?
Você não está fazendo a mesma busca duas vezes?
UPDATE
Para melhorar a query, tente assim:
SELECT e.EMPLOYEE_ID AS 'ID'
    ,e.FIRST_NAME + ',' + e.LAST_NAME AS 'Name'
    ,(SELECT DEPARTMENT_NAME FROM HR.DEPARTMENTS d WHERE e.DEPARTMENT_ID = d.DEPARTMENT_ID) AS 'Department Name'
    ,e.SALARY AS 'Base Salary'
FROM HR.EMPLOYEES e
WHERE e.SALARY IS NOT NULL

Assim ele vai trazer como você disse que quer no seu comentário, nulos ou não nulos. Tanto faz. Depois você faz o ORDER BY como quiser.
Comment: Funcionou! Sim preciso do union, para correr o query quando a comissão é não nula e quando é nula.Pode só explicar para que serve o  'd' e o 'e'? Sou novo no Sql e ainda não estão bem sólidos esses conceitos
Comment: @BrunoBacelar entendi. Tente então, ao invés do UNION, retirar a cláusula e.COMMISSION_PCT IS NOT NULL na primeira e rodar ela sem o UNION da query debaixo, vou colocar na resposta como deve fazer.
Comment: Ela funciona sem o UNION só que assim vou ter duas tabelas de resultados diferentes e eu quero tudo só numa
Comment: Coloquei na resposta como você deve fazer pra funcionar do jeito que você disse ai. Vê se te ajuda ;) @BrunoBacelar
Comment: Não queria abusar da sua paciência mas preciso de ajuda em mais umas coisas, quero só ver quem tem o maior salário, dei update no código, só que me dá um erro
Comment: @BrunoBacelar Adiciona no final: ORDER BY e.SALARY DESC; que vai funcionar. =)
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/84751/discussion-between-bruno-bacelar-and-nathalia-delavi).

Conectar colunas de diferentes tabelas


Set class property of an instance within class method in MATLAB

Question: My Objective is:
Using MATLAB, set the property value within one class method, and the property values are different between instances.
My Problem is:

When using SET in the class method, I will change the property value of all instances of this class, which is not what I want. I only want to change the property value of this instance.
About the dynamic property: I think it's used to create a unique property of the instance instead of setting the unique value of a general class property, is that right?

Code example:
classdef Storage

    properties
      tree =  containers.Map('KeyType','int32', 'ValueType','any')
    end

    methods

    function obj = set_tree(obj,period, value)
        obj.tree(period) = value;
    end

    end

end

When setting the value using this method:
   st1 = Storage();
   st2 = Storage();

   st1 = st1.set_tree(10,1);
   st2 = st2.set_tree(10,2);

Right now, the value set to st2.tree(10) will override the value set to st1.tree(10), which I am trying to avoid.
Comment: Can you show us a code example?
Comment: Hi, I just edited it. Thank you!
Comment: @gnovice Sorry to bother again...can you help me run the sample code in my question now? it seems that container.map property will behave differently.
Answer: The problem you're having is caused by setting a handle class object as a default value for a class property. The relevant documentation says this:

MATLAB® evaluates property default values only once when loading the class. MATLAB does not reevaluate the assignment each time you create an object of that class. If you assign an object as a default property value in the class definition, MATLAB calls the constructor for that object only once when loading the class.

So, for your Storage class above, all of your instances will be using the same default containers.Map object stored in the tree property. And since the containers.Map class is a subclass of the handle class it has reference behavior, which means the copies of the object will all point to the same underlying key/value map. If you want independent objects for each instance, you can initialize  the tree property in the constructor:
classdef Storage

  properties
    tree
  end

  methods
    function obj = Storage()
      obj.tree = containers.Map('KeyType','int32', 'ValueType','any');
    end
    function obj = set_tree(obj, value, period)
      obj.tree(period) = value;
    end
  end

end

Comment: Note that the reason this is an issue here is that `containers.Map` is a handle class, so it's the same instance that's referenced in all instances of the class. If you were using a struct, this wouldn't happen.
Comment: @WenbinLiu: Happy to help! Next time you have a question, remember to add as much detail about the code as possible right from the start. It'll get you quicker answers. Also, don't forget that you can [mark answers as accepted](https://stackoverflow.com/help/accepted-answer) when they've solved your problem.
Comment: Will do next time! Thanks!


dotnet-run command not working as expected

Question: I want to run my simple demo of .NET Core project in VS code. When I run dotnet build in my VS Code terminal, it works as expected. But the problem is, in the same project, when I run dotnet run then I get the following error:

Couldn't find a project to run. Ensure a project exists in C:\Users\hp\Desktop\HW-3\FirstTestApp, or pass the path to the project using --project.

This error is totally unexpected for me because this project should be working correctly, but it does not. I am actually not much familiar with VS Code.

Simplyfied dotnet build and dotnet run create this output
PS C:\FirstTestApp>dotnet build
Microsoft (R) Build Engine version 15.9.20+g88f5fadfbe for .NET Core
Copyright (C) Microsoft Corporation. All rights reserved.

   Restore completed in ... for \FirstTestApp\FirstTestApp\FirstTestApp.csproj
   FirstTestApp -> C:\ ...\FirstTestApp.dll
   FirstTestApp -> C:\ ...\FirstTestApp.Views.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

PS C:\FirstTestApp>dotnet build
Couldn't find a project to run. Ensure a project exists in C:\FirstTestApp, or pass the
path to the project using --project.

And this is my demo project structure:
Comment: Post any code and errors as text, not images. Images can't be copied, googled or compiled.
Answer: dotnet build will build using a solution file if one is present (the *.sln file).
dotnet run however requires a project file (*.csproj).
The easy fix is to just change into the project directory, and then run dotnet run again.
cd C:\Users\hp\Desktop\HW-3\FirstTestApp\FirstTestApp
dotnet run

The documentation for dotnet build and dotnet run sort of makes this clear - the dotnet build [<PROJECT>|<SOLUTION>] command clearly can accept a project or solution file, whereas dotnet run [--project <PATH>] can only accept a project file.
If you are completely new to C# then I will just briefly explain that a .csproj project file is the file that tells the build toolchain how to build the project - it does the same job as a makefile, ant file, pom.xml file, or the main file from any other build system.
The solution file basically just links together several projects into a single solution such that opening the solution file in your editor (VS or VS Code) causes the projects to be loaded as well.


Incluir ou somar elementos do tipo chave/valor em um array javascript

Question: Preciso incluir em um array objetos do tipo chave/valor com informações que vem do banco, mas se a chave já existir no array, o valor deve ser somado ao que já existe. Desenvolvimento em Angular

<code>/*A informação do banco vem assim:
  variavel[
  item1:10,
  item2:5]
*/
minhaVariavel: any[] = []

metodo(){
 this.dao.readRegisters().subscribe(data => {
    data.docs.forEach(d => {
      const info = d.data()

  //Antes de fazer o push preciso saber se a chave da nova info já existe na minhaVariavel, se existir o valor deve ser somado ao que já existe, senão ele deve ser inserido. (não sei se consegui ser claro)

  this.minhaVariavel.push(info.informacao)
  })
 })
}</code>
Answer: Existe mais de uma maneira de fazer isso, vou te mostrar uma delas usando um pouco de paradigma funcional.
<code>// simulei essa variável como o resultado que vem do banco
const retornoBanco: any[] = [{ item: 10 }, { item2: 20 }, { item: 5 }, { item6: 25 }];
// aqui como exemplo considerei que já existia um valor no array
const minhaVariavel: any[] = [{ item: 3 }];

// aqui fiz uma redução e transformei um array em um objeto com chaves e valores
const retornoReduzido = retornoBanco.reduce((objeto, atual) => {
    // será utilizado caso a chave não exista
    const valorInicial = 0;
    // percorre todas as chaves do objeto atual e adiciona ao objeto de retorno,
    // se as informações do banco não estiverem agrupadas, as instruções abaixo
    // irão agrupá-las
    Object.keys(atual).forEach(
        (key) => (objeto[key] = (objeto[key] || valorInicial) + atual[key])
    );

    // retorna o objeto com as chaves adicionadas para a próxima etapa
    // da redução
    return objeto;
}, {} /* inicialização do objeto que será retornado */);

// percorre os itens existentes em minhaVariavel e incrementa
// de acordo com as informações de mesma chave que vieram do banco
minhaVariavel.forEach((elemento) => {
    Object.keys(elemento).forEach((key) => {
        if (retornoReduzido[key]) {
            elemento[key] += retornoReduzido[key];
            // remove chave-valor do retorno do banco para adicionar
            // somente os novos itens nas instruções finais
            delete retornoReduzido[key];
        }
    });
});

// percorre os retornos do banco que não existiam na minhaVariavel
// adicionando-os em minhaVariavel
Object.keys(retornoReduzido).forEach((key) =>
    minhaVariavel.push({ [key]: retornoReduzido[key] })
);
</code>
Deixei o código comentado falando o que cada parte faz, recomendo que você veja Como criar um exemplo Mínimo, Completo e Verificável, para que nas suas próximas perguntas você tenha uma resposta mais assertiva.
Referências:
reduce
forEach
Object.keys()
Comment: Retorna esse erro na linha minhaVariavel.push({ [key]: retornoReduzido[key] }): O argumento do tipo '{ [x: string]: any; }' não é atribuível ao parâmetro do tipo '{ item: number; }'. A propriedade 'item' está ausente no tipo '{ [x: string]: any; }', mas é obrigatória no tipo '{ item: number; }'.ts(2345)
Comment: O que dá para entender com o erro é que a `minhaVariavel` é um array de `{ item: number }`, ou seja, tem que ter a propriedade `item`, mas pelo que entendi no seu exemplo, esse `item` seria dinâmico, vindo com chaves diferentes.
Comment: Exatamente, dinâmico. Eu copiei seu código com o intuito de entender, antes de implementar, mas de cara deu esse erro aí
Comment: Achei que já tinha portado para seu código, não me atentei ao `typescript`, coloquei o tipo da variável para `any[]`, agora deve dar certo
Comment: Muito obrigado, show!!


Discontinuous partials but differentiable

Question: I am trying to provide a counterexample to the statement that differentiability implies continuous partial derivatives. So far, I have found this function:
$$
f (x,y) = (x^2 + y^2) \sin\left(\frac{1}{\sqrt{x^2 + y^2}}\right)
$$
for $(x,y) \neq (0,0)$ and $0$ otherwise.
If I take the partial derivative with respect to $x$, I get:
\begin{align*}
f_x = \lim\limits_{h \to 0} \frac{f(h,0) - f(0,0)}{h} = \lim\limits_{h \to 0} \frac{h^2 \sin\left(\frac{1}{\sqrt{h^2}} \right)}{h} = \lim\limits_{h \to 0} h \sin\left(\frac{1}{|\sqrt{h}|}\right) = 0.
\end{align*}
I get the same result for $f_y$.
My question involves how I demonstrate that this function is actually a counterexample. In other words, how do I show that $f(x,y)$ is differentiable at $(0,0)$ and at least one of the partials is discontinuous?
An explanation of the strategy for doing this would be more than enough.
Thanks.
Answer: Compute $\frac{\partial f}{\partial x}(x, 0)$ when $x\neq 0$. It doesn't converge to $0$ when $x\to 0$.
$f$ is differentiable at $(0,0)$ because $|f(x, y)|\le \|(x, y)\|^2$


Problem using exec within class' function in Python

Question: The following code works as expected
name = "Test"
myname = ""
exec('myname ="' + name + '"')
print(myname)

Which shows as result:
Test

Problem
However, if I define the same within a function in a class and execute it I get as result an empty string.
class new(object):
    def __init__(self, name):
        self.print(name)

    def print(self, name):
        myname = ""
        exec('myname ="' + name + '"')
        print(myname)

a = new("My name")

The above is a toy example code of a bigger code.
Question
How to define the function so as to get the same result? The exec function is actually needed in the bigger code.
Comment: Have you read the documentation for [`exec`](https://docs.python.org/3/library/functions.html#exec)? What does it say about the behavior in local scopes? Hint, look at the last note.
Comment: Why are you using `exec` at all? I half suspect you *don't* need it as much as you think you do.
Comment: In this example case it's not needed of course. But in the real case I'm working in it's needed to shorten the code.
Answer: You can pass a dictionary as the globals (or locals) for exec.
def print(self, name):
    d = {"myname": ""}
    exec('myname ="' + name + '"', d)
    print(d["myname"])

Comment: Is there no way to assign a value to a variable `myname` within the print function using the `exec` function? I tried what you proposed and it works. But I still can't create a variable named `myname` which gets what I want to be assigned. In particular in my bigger code I need a `DataFrame`  get created using `exec` and then access one of it's columns. I may ask another question maybe...


What to return when the requested index is out of bounds

Question: If I have a method like this:
public Object getObject(int i) {
    if (i >= 0 && i < objectList.size()) {
        return objectList.get(i);
    } else {
        return
    }
}

Is this the best way to deal with array index out of bounds errors, and what should I return in the else statement, null?
Comment: Actually if there's no Array an `ArrayIndexOutOfBoundsException` wouldn't be a good choice. There however is a more general `IndexOutOfBoundsException` which would be perfect for this situation. Check here: http://docs.oracle.com/javase/7/docs/api/java/lang/IndexOutOfBoundsException.html
Answer: There is no absolute answer for this question, it depends on many things. However, if null is not a legal value, I would return null, if it's legal value I would throw an exception.
/**
 * ...
 * @return The element at index i, null if out of bounds.
 */
public Object getObject(int i) {
    if (i >= 0 && i < objectList.size()) {
        return objectList.get(i);
    }
    return null;
}

Or if null is a legal value:
public Object getObject(int i) throw IndexOutOfBoundsException {
    if (i >= 0 && i < objectList.size()) {
        return objectList.get(i);
    }
    throw new IndexOutOfBoundsException();
}

Answer: There is no such thing as "the best way", everything depends on your particular application. If "null" is somewhat recognizable (there are no nulls in your container) it can be an option. In some cases returning 0 may be the good option (when dealing with strictly positive number containers) and in others you could return element at i % size (so your container is cyclic). In general - it is always risky to return anything when asked for non existing element.
The most "frequent" approach is to raise an exception instead of returning anything.
Answer: I would throw an exception when the method is called with an illegal index. It does not make much sense to return anything for illegal calls.
Code would look like this:
public Object getObject(int i) {
    return objectList.get(i);
}

Furthermore returning null pollutes other code with boilerplate null-checks.
Finally you're in good neighborhood with Java's List specification of List.get(int) when raising IndexOutOfBoundsException in such cases.
Answer: You could implement the Null Object pattern.
Or you could implement a clamp, i.e. if the index is negative then return element at index 0 or if it is greater than or equal to size then return element at index size-1
But in your particular case the best thing to do is to raise an exception. This is what List#get does per default, so just leave it like that.
The reason is that you are explicitly asking for the value of an element at a certain index, i.e you expect that it is available. If not then there must be something wrong with the logic you use to determine that index.
Answer: Its true there is no such thing like "best way" but you can handle exceptions by thinking what can cause them not to go to that point atleast.
public Object getObject(int i)
{
   if(objectList == null || ojbectList.size()<=i)
        return null;

    if (i >= 0 && i < objectList.size())
    {
        return objectList.get(i);
    }
}


Javascript Google map api V3 fitbounds with center location

Question: I want to fitbound pushpins to visible all around user's location pushpin. i wrote the following code it center the user location but few pushpin goes out of map ??
FYI: userPinLoc is pushpin object which is already populated
 function setInitialZoom() {
            mapZoom = googleMap.getZoom();
            var bounds = new google.maps.LatLngBounds();
            bounds.extend(userPinLoc);
            for (i in nearestEntitiesToZoom) {
                entity = nearestEntitiesToZoom[i];
                var googleLatLng = new google.maps.LatLng(entity.latitude,entity.longitude);
                bounds.extend(googleLatLng);
            }

            google.maps.event.addDomListener(googleMap, 'bounds_changed', function() {
                googleMap.setCenter(userPinLoc);
            });
                 googleMap.fitBounds(bounds);
        }

Answer: I'm not sure where you're getting userPinLoc from. Give this a go:
...
var bounds = new google.maps.LatLngBounds();

// Go through each...
for (i in nearestEntitiesToZoom) {
    entity = nearestEntitiesToZoom[i];
    var googleLatLng = new google.maps.LatLng(entity.latitude, entity.longitude);
    bounds.extend(googleLatLng);
};

// Fit these bounds to the map
googleMap.fitBounds(bounds);
...

Remember, fitCenter or fitBounds needs a LatLng object as a parameter.
This code is adapted from: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/
Comment: Sorry to forget, I am already having "googleMap.fitBounds(bounds);" this line in my implementation, i don't see any change other then that in your code.
Comment: My bad. I started this message before you made your last revision to your question (it didn't have the last `googleMap.fitBounds(bounds);` line)
Answer: I did it using java and javascript
public static void calculateMapFitBounds(GeoLocation userLocation, List<GeoLocation> contents, Map<String, GeoLocation> latlngBounds){

    if (Util.isEmtpyGeoLocation(userLocation) || contents == null || contents.isEmpty()) {
        return;
    }

    //SW
    double minLat = userLocation.getLatitude();
    double minLng = userLocation.getLongitude();

    //NE
    double maxLat = userLocation.getLatitude();
    double maxLng = userLocation.getLongitude();

    for(GeoLocation content: contents){

        /*
         * Populating Top left cordinate (SW)
         */
        minLat = Math.min(minLat, content.getLatitude());
        minLng = Math.min(minLng, content.getLongitude());

        /*
         * Populating Bottom right cordinate (NE)
         */
        maxLng = Math.max(maxLng, content.getLongitude()) ;
        maxLat = Math.max(maxLat, content.getLatitude());
    }

    /*
     * Calculating Delta fit bounds
     */

    double latDelta = Math.max(Math.abs(userLocation.getLatitude() - minLat), Math.abs(maxLat-userLocation.getLatitude()));

    double lngDelta = Math.max(Math.abs(userLocation.getLongitude() - maxLng), Math.abs(minLng - userLocation.getLongitude()));

    //Calculating SW
    minLat = userLocation.getLatitude() - latDelta;
    minLng = userLocation.getLongitude()- lngDelta;

    latlngBounds.put("swLatLng", new GeoLocation(minLat, minLng));

    //Calculating NE
    maxLat = userLocation.getLatitude() + latDelta;
    maxLng = userLocation.getLongitude()+ lngDelta;

    latlngBounds.put("neLatLng", new GeoLocation(maxLat, maxLng));

}

I am using velocity views so here is velocity and js code
#if($swLatLng && $neLatLng)
        var swLatLn = new google.maps.LatLng($!swLatLng.latitude, $!swLatLng.longitude, false);
        var neLatLn = new google.maps.LatLng($neLatLng.latitude, $neLatLng.longitude, false);

        var bounds = new google.maps.LatLngBounds(swLatLn, neLatLn);
        googleMap.fitBounds(bounds);

        #end

Answer: When I've done this before, I've done the bounds.extend() for the map center as the very last one, not the first one.  Which seemed to work better for some reason.
function initialize() {
    var points = [
        {
            lat: 51.498725,
            lng: -0.17312
        },
        {
            lat: 51.4754091676,
            lng: -0.186810493469
        },
        {
            lat: 51.4996066187,
            lng: -0.113682746887
        },
        {
            lat: 51.51531272,
            lng: -0.176296234131
        }
    ];

    var centerLatLng = {lat: 51.532315, lng: -0.1544};

    var map = new google.maps.Map(document.getElementById("map"), {
        zoom:               15,
        center:             centerLatLng,
        mapTypeId:          google.maps.MapTypeId.ROADMAP
    });

    var bounds = new google.maps.LatLngBounds();

    var homeMarker = new google.maps.Marker({
        position: centerLatLng,
        map: map,
        icon: "http://maps.google.com/mapfiles/ms/micons/green-dot.png"
    });

    for (var i = 0; i < points.length; i++) {
        var marker = new google.maps.Marker({
            position: points[i],
            map: map
        });

        bounds.extend(points[i]);
    }

    bounds.extend(centerLatLng);

    map.fitBounds(bounds);
}

Comment: doing same thing extending bounds then add center location as bound then call fit bounds. r u sure it will 100% resultant to center pin surrounded by other pins with perfect fitbound ?


symfony 2 Updating color schemes dynamically

Question: I'm working in a project using Symfony 2,
I'm using Assetic with rewrite and less filter, and it work fine,
Now I'm planing to let administrator (connected user) to controle some features in css like font and main color.
The problem that I'm facing is :
- how can I proceed to integrate these css changes from entity to the css management

I can't let assetic use routing rule to include custom css
Eaven if I success to get this work, every time I have a changes to the custom css I have to install assets to web folder and make the assetic:dump and clearing cache from a controller.
Answer: If you (or someone else) still need this:
I solved this by putting all generic CSS in a asset handled by Assetic like usual and putting the dynamic CSS generation in a Controller action and rendering the CSS with Twig.
Answer: As suggested by Steffen you should put the dynamic CSS in a Twig template.
But now you might suffer from that part of the css being a full request to a symfony application instead of a css (HTTP 302 and such) which increases server load.
Thats why I would advise you to do 3 things (you can skip step 2 if your css doesn't change without interaction, e.g. date based):

Implement a service which caches the current output to e.g. web/additional.css.
Write and register a RequestListener to update the css regularly
Extend all controller actions that could introduce changes to the css with the service call

Example (assumes you use Doctrine and have an entity with some color information):
Service
<?php
//Acme\DemoBundle\Service\CSSDeployer.php
namespace Acme\DemoBundle\Service;

use Doctrine\ORM\EntityManager;

class CSSDeployer
{
    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * Twig Templating Service
     */
    protected $templating;

    public function __construct(EntityManager $em, $templating)
    {
        $this->em = $em;
        $this->templating = $templating;
    }

    public function deployStyle($filepath)
    {
        $entity = $this->em->getRepository('AcmeDemoBundle:Color')->findBy(/* your own logic here */);
        if(!$entity) {
            // your error handling
        }

        if(!file_exists($filepath)) {
            // your error handling, be aware of the case where this service is run the first time though
        }

        $content = $this->templating->render('AcmeDemoBundle:CSS:additional.css.twig', array(
            'data' => $entity
        ));

        //Maybe you need to wrap below in a try-catch block
        file_put_contents($filepath, $content);
    }
}

Service Registration
#Acme\DemoBundle\Resources\config\services.yml
services:
    #...
    css_deployer:
        class: Acme\DemoBundle\Service\CSSDeployer
        arguments: [ @doctrine.orm.entity_manager, @templating ]

RequestListener
<?php
//Acme\DemoBundle\EventListener\RequestListener.php
namespace Acme\DemoBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Debug\Exception\ContextErrorException;
use \DateTime;
use Doctrine\ORM\EntityManager;

class RequestListener
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var EntityManager
     */
    protected $em;

    public function __construct(ContainerInterface $container, $em)
    {
        $this->container = $container;
        $this->em        = $em;
    }

    /**
     * Checks filemtime (File modification time) of web/additional.css
     * If it is not from today it will be redeployed.
     */
    public function onKernelRequest(GetResponseEvent $event)
    {
        $kernel     = $event->getKernel();
        $container  = $this->container;

        $path = $container->get('kernel')->getRootDir().'/../web'.'/additional.css';

        $time = 1300000000;

        try {
            $time = @filemtime($path);
        } catch(ContextErrorException $ex) {
            //Ignore
        } catch(\Exception $ex) {
            //will never get here
            if(in_array($container->getParameter("kernel.environment"), array("dev","test"))) {
                throw $ex;
            }
        }

        if($time === FALSE || $time == 1300000000) {
            file_put_contents($path, "/*Leer*/");
            $time = 1300000000;
        }

        $modified   = new \DateTime();
        $modified->setTimestamp($time);
        $today      = new \DateTime();

        if($modified->format("Y-m-d")!= $today->format("Y-m-d")) {
            //UPDATE CSS
            try {
                $container->get('css_deployer')->deployStyle($path);
            } catch(\Exception $ex) {
                if(in_array($container->getParameter("kernel.environment"), array("dev","test"))){
                    throw $ex;
                }
            }
        } else {
            //DO NOTHING
        }
    }
}

RequestListener registration
#Acme\DemoBundle\Resources\config\services.yml
acme_style_update_listener.request:
    class: Acme\DemoBundle\EventListener\RequestListener
    arguments: [ @service_container, @doctrine.orm.entity_manager ]
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }

Controller actions
public function updateAction()
{
    // Stuff
    $path = '....';
    $this->get('css_deployer')->deployStyle($path);
}

Hope this helps someone in the future.
Comment: at this line `public function __construct(EntityManager $em, $templating)` doesnt compile, `argument "$templating" of method "__construct()" has no type-hint, you should configure its value explicitly`, I couldn't find the type


Array of characters in python 3?

Question: In Python 2.7 I can create an array of characters like so:
#Python 2.7 - works as expected
from array import array
x = array('c', 'test')

But in Python 3 'c' is no longer an available typecode. If I want an array of characters, what should I do? The 'u' type is being removed as well.
#Python 3 - raises an error
from array import array
x = array('c', 'test')

TypeError: cannot use a str to initialize an array with typecode 'c'
Comment: Warning: this basically asks how to store characters and then accepts an answer which stores encoded characters as a byte array. In case you didn't notice, that's not really an array of characters.  Basically it means that the person didn't get it: use a *string*.
Answer: Use an array of bytes 'b', with encoding to and from a unicode string.
Convert to and from a string using array.tobytes().decode() and array.frombytes(str.encode()).
>>> x = array('b')
>>> x.frombytes('test'.encode())
>>> x
array('b', [116, 101, 115, 116])
>>> x.tobytes()
b'test'
>>> x.tobytes().decode()
'test'

Answer: It seems that the python devs are not longer supporting storing strings in arrays since most of the use cases would use the new bytes interface or bytearray. @MarkPerryman's solution seems to be your best bet although you could make the .encode() and .decode() transparent with a subclass:
from array import array

class StringArray(array):
    def __new__(cls,code,start=''):
        if code != "b":
            raise TypeError("StringArray must use 'b' typecode")
        if isinstance(start,str):
            start = start.encode()
        return array.__new__(cls,code, start)

    def fromstring(self,s):
        return self.frombytes(s.encode())
    def tostring(self):
        return self.tobytes().decode()

x = StringArray('b','test')
print(x.tostring())
x.fromstring("again")
print(x.tostring())

Answer: Addition to the answer of Mark Perryman:
>> x.frombytes('hellow world'.encode())
>>> x
array('b', [116, 101, 115, 116, 104, 101, 108, 108, 111, 119, 32, 119, 111, 114, 108, 100])
>>> x.tostring()
b'testhellow world'
>>> x[1]
101
>>> x[1]^=0x1
>>> x[1]
100

>> x.tobytes().decode()
'wdsthellow world'
>>> x.tobytes
<built-in method tobytes of array.array object at 0x11330b7b0>
>>> x.tobytes()
b'wdsthellow world'

Exactly, I need to convert a special byte from my array list recently,
have tried various methods, then get the new simple method:x[1]^=0x1, and
could get a array easily via array.array['b', <my bytes list>]

Array of characters in python 3?


Why don't we use OLS estimator to test hypothesis in linear regression?

Question: In a linear regression model $Y = X_1 \beta_1  + X_2 \beta_2 +  \epsilon$, we use ANOVA to test null hypothesis $H_0 : \beta_2 = 0$. Denote $RSS_1$ as the sum of square of residuals under the submodel $Y = X_1 \beta_1 + \epsilon$, denote $RSS$ as the sum of square of residuals under the full model $Y = X_1 \beta_1 + X_2 \beta_2 + \epsilon$, we choose $\frac{(RSS_1- RSS)/\text{df}}{RSS/\text{df}}$ as the test statistic and calculate p-value.
Here is my question: since the OLS estimator $\hat{\beta}$ has a $N(\beta,\sigma^2(X^TX)^{-1})$ distribution, why don't we simply test the null hypothesis $H_0 : \beta_2 = 0$ through $\hat{\beta}$? For example, we can take $\| \hat{\beta_2} \|^2 / \{ \hat{\sigma^2} \sum_i [(X_TX)^{-1}]_{i,i}\} $ as a test statistic, which takes a t-distribution under null hypothesis.
In fact, this is the method of getting a confidence interval of $\beta$. Why don't we test the hypothesis through the same method of getting confidence interval?
Answer: The test you are proposing is exactly what is done in the T-test for an individual coefficient, which is presented in the coefficient estimates table.  One of the major theorems of regression analysis is that the F-test reduces to equivalence to the T-test when you apply it to a single coefficient.  Thus, for an individual coefficient $\beta_2$, you should find that the p-value for the two tests you mention are always the same (since they are effectively the same test).
Comment: Thanks for your answer! What will happen in testing multiple coefficients?
Comment: When testing multiple coefficients you would generally use the F-test, and there is no T-test analogy in this case.
Comment: I see. Thank you!


Can an ESX server under heavy load cause cpu spikes on guest VM's?

Question: So we have a number of vm's running on an ESX 4.1 server for product testing. The ESX Server is at times under heavy load. We've been experiencing high CPU levels during some use cases, but we can't always duplicate this. If the ESX server as a whole is under heavy load could this cause guest machines to show high CPU usage?
To ask it a different way, if the guest machines require more cpu resources than the server has, how does this affect CPU usage as indicated by the OS and process?
Answer: One of the canonical sources for ESX performance tips is the Performance Troubleshooting Guide! (PDF)
In short:  If your host is busy, and your VMs are reporting a high "ready-time," (which is a counter of when the VM is ready to perform work but no physical CPU can be found for the machine to be scheduled by the hypervisor) then the symptoms you are experiencing are not that in-guest CPU usage is high, but that the individual VMs are not getting enough physical CPU time to service their workload.  This can manifest in-guest as appearing like high CPU use, but this is just an accounting mistake the guest is making because it is not aware of virtualization itself.
So check for ready time and if it is indeed high, find a way to either add more physical cpu to your machine/cluster or reduce use.
In-guest CPU monitoring has the potential to skew when the machine is idle, and also when it is busy.  In one scenario, the idle process is not scheduled by the hypervisor.  In the other, high use by many machines will result in some machines being starved of cpu, and hence guest-level monitoring should not be used without additional hypervisor-level monitoring.
Answer: In-guest CPU monitoring is a bad idea, it's almost impossible inherently for any guest to ever really know how much CPU time it's taking, on any hypervisor - the only real way to know is to look outside via the hypervisor. So yeah, a very busy hypervisor could easily make an in-guest CPU usage stat way off base yes - just don't trust those figures anyway.


What happens when we use document.getElementsByTagName("body")[0]?

Question: What is the process happening in Browser when we use document.getElementsByTagName("body")[0]. I have the below code to be executed. What is the difference in the flow when we use  somewhere in the  or  with the below one.
function addJavascript(jsname,pos) {
var th = document.getElementsByTagName(pos)[0];
var s = document.createElement('script');
s.setAttribute('type','text/javascript');
s.setAttribute('src',jsname);
th.appendChild(s);
}
addJavascript("myJs.js","body");

I also want to know what happens when we use document.getElementsByTagName("head")[0].
Comment: Your question isn't clear. What in the descriptions (for example in the MDN) of the functions do you want explained ?
Comment: My intention is to know what document.getElementsByTagName("body")[0] does.
Answer: document.getElementsByTagName("tag here")[0]

This will find the first element in the html with the tag specified
In case of body and head tag, it is not doing anything special as they are defined only once.
Comment: I have a piece of JavaScript code which will be invoked asynchronously while the  is being rendered. It is unpredictable that when this code will be inserted to page. Also, I have a JavaScript file which will be loaded in the page and which will process the JavaScript piece of code. I am unable to change the code in the JS file. Also, I am unable to directly place the JavaScript code somewhere in the page. The code will be inserted from an external tool to the page.
Comment: Now, the JavaScript file contains document.write method to create an image. But, this method is not recommended since it is impossible to predict when the write action will take place. For example, if the code snippet runs after the body rendering finishes and after the DOM is loaded, the page content will be entirely rewritten.

I want to make sure that the above worst situation should not take place.
Answer: I'm uncertain whats actually asked here, so I guess you're confused about the [0] part.
Well, document.getElementsByTagName queries for an unknown number of elements within your markup. It will return a HTMLCollection, which is an Array-like structure. Thats why we need to address specific elements within that list via brackets.
 and  elements are only allowed onced within a valid HTML document, so this might look a little confusing. A better way to get those nodes is directly, via reference:
var head = document.head,
    body = document.body;

To be on the save side, combine that with a fallback and you're fine
head = document.head || document.getElementsByTagName("head")[0];

Comment: Please find my comment in the above answer
Answer: From your comment on the question:

My intention is to know what document.getElementsByTagName("body")[0] does.

document.getElementsByTagName finds the elements that exist in the document as of when you call it that have that tag (body, head, p, a, div, etc.) So since you're calling it with the tag name "body", it finds all body elements in the document, if there are any when you call it.
[0] then tries to get the first entry from the resulting list. If the list is empty, you get back undefined.
So document.getElementsByTagName("body")[0] either gives you the first (and presumably only) body element in the document, or undefined if there is none (yet).

What is the difference in the flow when we use  somewhere in the  or  with the below one.

Well, if you have it in the  and you run it looking for the body tag, document.getElementsByTagName('body') will return an empty node list (since the head must precede the body), and so [0] on that will give you undefined, and attempts to use appendChild on it will fail.

If you just want to reliably add a script element on the page, from a script, the usual thing is to use:
var parent = document.getElementsByTagName('script')[0].parentNode;
// ...create your new script element
parent.appendChild(yourScript);

...since if your script is running (and you didn't defer it and remove the script element that included it), you know there's at least one script element somewhere on the page.
Comment: Please find my comment in the first answer
Comment: @RaheebM: That has nothing to do with the question you actually asked, and then reconfirmed when Dystroy asked you what you were actually asking. If you want to know how to reliably append content to a page without using `document.write`, ask that question instead. *This* question has been answered (by multiple people).


$\sqrt{3x+5}-\sqrt{x-1}=0$

Question: I've been trying to complete this question for a while now, but my answers never make sense. I always end up with $3x = x -1$, or something similar, but that can't possible to right.
The instructions are 'solve each of the following radical equations algebraically. State any restrictions on the variable.'
Any pointers in the right direction would be greatly appreciated.
Thank you in advance!
Comment: How do you end up with $3x=x-1$?
Answer: if it is $$\sqrt{3x+5}-\sqrt{x-1}=0$$ we can write
$$\sqrt{3x+5}=\sqrt{x-1}$$
after squaring we have$$3x+5=x-1$$ thus $$x=-3$$ since we have $$x\geq 1$$ we have no solutions.
Answer: Hint
$$\sqrt{3x+5}-\sqrt{x-1}=0\rightarrow \sqrt{3x+5}=\sqrt{x-1}$$
Square both sides and remember that
$$3x+5 \ge 0\\
x-1\ge 0
$$

$\sqrt{3x+5}-\sqrt{x-1}=0$


Desired output at design time, Visual Studio 2008 (vb)

Question: Is it possible to choose to run specific code at design time? What i would like to be able to do is to display a list of enums that are used ina specific form and menu. Is this possible to do? Any response would be appreciated.
Thanks in advance!
Answer: Not sure exactly what you want, but in the Immediate Window (CTRL + ALT + I) you can type this type of command:
? System.Enum.GetNames(GetType(System.AttributeTargets))

...which will produce this output:
{Length=16}
    (0): "Assembly"
    (1): "Module"
    (2): "Class"
    (3): "Struct"
    (4): "Enum"
    (5): "Constructor"
    (6): "Method"
    (7): "Property"
    (8): "Field"
    (9): "Event"
    (10): "Interface"
    (11): "Parameter"
    (12): "Delegate"
    (13): "ReturnValue"
    (14): "GenericParameter"
    (15): "All"

Just replace System.AttributeTargets with your favourite enum.
With a bit of creativity you can get all sorts of values from your code and also invoke methods in the same way (just quick examples here):
' print the value of a property '
? (New VBWindowsApplication1.Form1()).Text

' call some method '
? (New VBWindowsApplication1.Form1()).SomeMethod()

Of course there is a limit on how complex operations you can do here, but for simpler debugging purposes it works well.
Comment: @Macros; no, that's the point with the Immediate Window. Updated the answer with a link to the MSDN documentation.


PHP magic methods e Seguranca

Question: Estou a meio de um desafio de programacao e precisava apenas de uma caminho a seguir o codigo que tenho de rever :
<code><?php
  require_once( "settings.php" );
  class Database{
    function __construct(){
      $this->setDefaults();
    }
    function setDefaults(){
      if( !isset($this->host) ) $this->host = DB_HOST;
      if( !isset($this->user) ) $this->user = DB_USER;
      if( !isset($this->pass) ) $this->pass = DB_PASS;
      if( !isset($this->name) ) $this->name = DB_NAME;
      $this->description = $this->user."@".$this->host."/".$this->name;
    }
    function connect(){
      $this->connection =  new mysqli( $this->host, $this->user, $this->pass, $this->name );
      if( !$this->connection ) die( "Connection to ".$this->host." failed!" );
    }
    function query( $sql ){
      if( !isset( $this->connection ) ) $this->connect();
      $this->result = $this->connection->query( $sql );
      return $this->result;
    }
    function fetchRow(){
      return $this->result->fetch_assoc();
    }
  }

  class Flag{
    function getFlag(){
      return file_get_contents( FLAG_PATH );
    }
  }

  class Page{
    function __construct(){
      $this->elements = array();
      $this->html = "";
    }
    function __wakeup(){
      $this->compile();
    }
    function addElement($el){
      return $this->elements[] = $el;
    }
    function render(){
      if( empty( $this->html ) ) $this->compile();
      return $this->html;
    }
    function compile(){
      foreach( $this->elements as $el ){
        $this->html .= $el->render();
      }
    }
  }

  Interface Element{
    function render();
  }

  class SelectElement implements Element{
    function render(){
      if( empty( $this->aItems ) ) return "";
      $html = "<select>\n";
      foreach( $this->aItems as $k => $item ){
        $html .= "<option>".$item."</option>\n";
      }
      $html .= "</select>\n";
      return $html;
    }
  }

  class ObjectDescriber{
    function __construct( $obj, $prop, $type ){
      $this->obj = $obj;
      $this->prop = $prop;
      $this->t = $type;
    }
    function __toString(){
      if( $this->t == "m" ){
        return $this->obj->{$this->prop}();
      }else{
        return $this->obj->{$this->prop};
      }
    }
  }

  class DatabaseDescriber extends ObjectDescriber{
    function __construct( $db ){
      $this->obj = $db;
      $this->prop = "description";
      $this->t = "p";
    }
  }

?>
</code>
Desafio :
Receber o valor de Flag->getFlag()
Comment: o que isso tem a ver com métodos mágicos do php e segurança?
Comment: Tas a falar a serio ... ou ... tens o modo troll  on ?
Answer: Primeiro você tem que ter uma constante definida chamada de FLAG_PATH com o provavel path de algo que vc deseja ler. Depois instanciar a flag ou fazer direto:
1 -
<code>$flag = new Flag();
$flat->getFlag();
</code>
2 -
<code>(new Flag())->getFlag(); #Dependendo da versão do PHP não funciona assim
</code>
Sinceramente foi apenas isso que entendi da sua pergunta e não consegui mesmo entender o que tem haver com segurança e magic methods. Se puder explicar melhor o que realmente deseja, pq não vi nada além que um monte de classes empilhadas em um lugar só que não interage em nada uma com a outra.

PHP magic methods e Seguranca


Red Herring Error : Class name must be valid object or string

Question: After just having spent two days trying to get to the bottom of a particularly weird bug I thought I'd post up what my question would have been — if I had taken the time to write it — and then post my answer also, just in the hope of helping other people avoid the headache.

PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522

This was the starting point. I got this error — along with a typically pleasant WSOD — after creating a new install of my site on a localhost. The strange thing about it was that I had almost exactly the same setup working on another machine. The code was served by GitHub and so was identical, the database was a direct dump from the original site, php was configured as expected and versions were only a 0.0.5 out (5.3.15 and 5.3.10), both Drupals were version 7.9 ... everything should be working.
What made this weirder still was the fact the site would work directly after a drush rr, however, it would break immediately after a drush cc all, or on refresh.
This led my collegue and I traipsing in circles, debugging common.inc and modules.inc trying to find a clue as to what was going on. What we discovered was that after the reset registry the correct entity_info array was built, but after the clear cache, we only got part of the full entity_info array.
Investigating further we found rather ridiculously that the following code — taken from module.inc — could not find particular functions in particular module files that we knew to exist.
foreach ($list as $module) {
  $include_file = isset($hook_info[$hook]['group']) &&
    module_load_include(
      'inc', $module, $module . '.' . $hook_info[$hook]['group']
    );
  // Since module_hook() may needlessly try to load the include file again,
  // function_exists() is used directly here.
  if (function_exists($module . '_' . $hook)) {
    $implementations[$hook][$module] = $include_file ? $hook_info[$hook]['group'] : FALSE;
  }
}

This could only mean that at the point this code was being executed certain files that should have been included by now, weren't. What made this even more baffling was that if we called the following outside of any of the caching code, it returned the correct entity_info array.
$entity_info = module_invoke_all('entity_info');

This meant that there wasn't anything wrong with the files, it just seemed to be the caching system. To cut a rather long story short, because we didn't have anything modifying the core drupal caching system, we decided to resort to the good old trial and error disable all modules and enable one by one. Great.
This took some time but we managed to whittle everything down to one bespoke module, which we then trial and errored function by function call. Until we got the culprit:
/**
 * Helper function to redirect an actual submit to the ajax handler
 */
function microsites__admin_settings_submit(&$form, &$form_state) {
  return microsites__admin_settings__ajax_button(&$form, &$form_state);
}

So I guess my question — apart from being, what can cause PHP Fatal error: Class name must be a valid object or a string error — would be what out of the above function could cause such a disastrous error, and in such a weird manner?
Answer: For those who have been using PHP a while, it should be obvious what is causing the issue, although what wont be obvious is why Drupal didn't make a song and dance about it.
Basically the cause of the WSOD were the two ampersands denoting call time pass by reference. Something that has been deprecated in PHP for a while. The reason why they were there at all was just a copy and paste typo.
return microsites__admin_settings__ajax_button(&$form, &$form_state);

The above should have been:
return microsites__admin_settings__ajax_button($form, $form_state);

With the above change made, everything magically started working again.
Now I might get some people assuming that we just hadn't been keeping track of our errors, but we had as much logging enabled as possible... at no point did either PHP or Drupal complain about the call time pass by reference. Instead what Drupal seemed to do — and only after clearing cache I might add — was fail to include other files once it had hit this illegal / deprecated syntax, which then went on to create malformed entity_info arrays.
I have since tested this on other files, and all it takes is to add a call time pass by reference and it breaks Drupal, at least for all my localhost setups anyway... that is, unless the following has been specified in the php.ini:
allow_call_time_pass_reference = On

If anyone can ascertain as to why the silence (considering all other PHP errors and warnings are shown), why it broke other files loading, and why the problem only affected when running after a cleared cache, I'd be interested to hear.
Maybe upgrading to 7.22 would fix a few of the above... but in future I'll make sure I double check coherence between my entire php.ini(s) I think; rather than spend a few days trying to bash through a brick wall using only a toothpick.
update
Just to answer Clive's question, this was the output in the apache error log after I've just tested the same problem again:
[Thu Apr 11 11:15:29 2013] [notice] Digest: generating secret for digest authentication ...
[Thu Apr 11 11:15:29 2013] [notice] Digest: done
[Thu Apr 11 11:15:29 2013] [notice] Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8r DAV/2 PHP/5.3.6 configured -- resuming normal operations

Comment: Regarding the silence - are there any errors reported in the Apache log when the exception occurs?
Comment: @Clive - no unfortunately nothing reported there either :S I guess it'll be something either hidden away in Drupal or in my php/apache setup.
Answer: This is the tip of the iceberg on this problem. (the PHP Fatal error: Class name must be a valid object or a string in /includes/common.inc on line 7522).
in 7.28, at line 7855, 6 =
    $class = $type_info['controller class'];
    $controllers[$entity_type] = new $class($entity_type);

The issue stems from, for whatever reason, not being able to obtain a $class value from the $type_info array by executing module_invoke_all('entity_info').  Certainly a call time pass by reference could do it, but that would normally be caught.  The actual problem is in /includes/common.inc at 7644.
  if (empty($entity_info)) {
    if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
    }
    else {
      $entity_info = module_invoke_all('entity_info');
      // Merge in default values.
      foreach ($entity_info as $name => $data) {
        $entity_info[$name] += array(
          'fieldable' => FALSE,
          'controller class' => 'DrupalDefaultEntityController',
          'static cache' => TRUE,
          'field cache' => TRUE,
          'load hook' => $name . '_load',
          'bundles' => array(),
          'view modes' => array(),
          'entity keys' => array(),
          'translation' => array(),
        );
        $entity_info[$name]['entity keys'] += array(
          'revision' => '',
          'bundle' => '',
        );
        foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
          $entity_info[$name]['view modes'][$view_mode] += array(
            'custom settings' => FALSE,
          );
        }
        // If no bundle key is provided, assume a single bundle, named after
        // the entity type.
        if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
          $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
        }
        // Prepare entity schema fields SQL info for
        // DrupalEntityControllerInterface::buildQuery().
        if (isset($entity_info[$name]['base table'])) {
          $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
          if (isset($entity_info[$name]['revision table'])) {
            $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
          }
        }
      }
      // Let other modules alter the entity info.
      drupal_alter('entity_info', $entity_info);
      cache_set("entity_info:$langcode", $entity_info);
    }
  }

Notice that if the condition is true in the if at
if ($cache = cache_get("entity_info:$langcode")) {
      $entity_info = $cache->data;
}

then the module_invoke_all('entity_info') is never executed.
It just happens that the condition is always met after some other processing is done to create the cache.  That means that there is no way to get the entity_info set up --- in my case there was no way to obtain the 'user' entity info, causing the original error above.  I made the 'else' one level higher (took out the 'else {}') for testing, and everything worked as it should to clear the error.
I believe that the real bug is that the checking of cache is less than adequate, and that a check on the existence of the entity_info about the specific entity being searched for is needed. In fact, it may be justifiable to also search for the element ['controller class'] for that entity in the entity_info stored in cache.
D
Comment: Is there a Drupal core issue for this?


Assigning Values in SPSS using a Reference Variable

Question: I am having some difficulty achieving the following functionality in SPSS. I'm trying to come up with a way to track pets admitted to a clinic with a certain disease. Originally the pets are assigned a certain number if they have this disease, but in subsequent visits this number is 0, since their disease will be cured! But, we want to see how the pets are doing so we want to be able to add a variable (past disease) that achieves the following functionality.
NAME    Visit DATE    Disease Code
SPOT     1/1              1
SPOT     1/9              0
SPOT     1/11             0
Bruno    12/1             1
Bruno    12/8             0

In this example, Spot and Bruno came in for Disease 1, but they didn't have disease 1 when they came back, since the treatment worked. But, we want to add a variable that still shows that Spot and Bruno had the disease. So the expected outcome would be this:
NAME    Visit DATE    Disease Code    Past Disease Code
SPOT     1/1              1                  1
SPOT     1/9              0                  1
SPOT     1/11             0                  1
Bruno    12/1             1                  1
Bruno    12/8             0                  1

I attempted to do this by using an IF loop, but I couldn't quite get the syntax right, here since Spot and Bruno are entered as a a case multiple times, instead of as a single case. Does that make sense? Essentially, I want to be able to say that since SPOT and Bruno had a 1 for the variable "Disease code", the "Past disease code" should equal 1 for every entry of Spot and Bruno. Note that we can assume that every dog has a different name.
Answer: Look up the AGGREGATE command.
Depending on your data something like this might work, nonetheless should suffice as a good example of how the command works.
AGGREGATE OUTFILE=* MODE=ADDVARIABLES /BREAK=name /PastDiseaseCode=MAX(DiseaseCode).

Comment: Hey there,  thanks so much.  The aggregate command works perfectly, and I hadn't come across it in my research. I appreciate your response, have a great day!


How to disable the comment for a specific node programmatically?

Question: I'm using Drupal 8. I would like to close the comment for the node, once someone commented on that node. But I don't know how to disable the comment for a specific node programmatically.
my_module_comment_insert ($entity) //implement the comment insert hook
{
    $node = $entity->getCommentedEntity();//get the attached comment node.
    // How to implement code here to disable comment for the $node?
}

Answer: In D8, the comments are stored as field containing various comment properties including comment status.
You can disable node/entity comments using something like below:
use Drupal\comment\Plugin\Field\FieldType\CommentItemInterface;

/**
 * Implements hook_comment_insert().
 */
function [MODULE_NAME]_comment_insert($comment) {
  // Get comment field name, default comment.
  $field_name = 'comment'; // $comment->getFieldName();

  // Get entity.
  $node = $comment->getCommentedEntity();
  $node->get($field_name)->status = CommentItemInterface::CLOSED;
  $node->save();
}

Comment: Glad it helped.