What is the flow of using BDD as test-first development approach for front-end and back-end as one project?

Question: Currently I am working on a project using BDD with Cucumber as a test-first development methodology. I am struggling to understand the integration of UI with my back-end code.
As per my understanding BDD->Write failing Scenario (Feature File)->Write Step Definition (Step Def File) ->Application Code (Java Class)
I have implemented my back-end using test-first approach (Java cLass). Next, I need to integrate my UI part.
Do I need to create my front-end e.g dynamic web project as a separate project and how would that follow test-first way then. Everything on internet is just telling Cucumber and Selenium as automation framework. I couldn't find a good resource on developing a complete end-to-end (even if very small application) but using both front and back as test-first approach.
 I don't want to know about testing, I am trying to apply BDD as test-first development approach.
Answer: First of all when cuking web applications your initial focus should be on WHAT the application does and WHY its important. So how its implemented is completely irrelevant.
Using Cucumber as a tool to drive development using BDD you just start by writing scenarios guided by WHAT the business wants and WHY the thing they want is so important that they want you to work on it ASAP.
With a UI a user will be doing something (WHAT) and that thing will be important (WHY). The thing they are doing will require an interaction with the UI (at this point HOW they interact is completely irrelevant. This interaction is captured in the scenarios WHEN.
For them to make this interaction some things will have need to have taken place already. These things a captured by the scenarios GIVENS. After the user has interacted with the system something needs to change in the UI. You examine this in the scenarios THENS.
Once you have your scenario you can define and start implementing your step definitions. In general I make each step definition a single call to a helper method, so the steps do only one thing which is to translate a line in a scenario into a call in your programming language.
Now you can define a method in your programming language and only then should you start thinking about HOW you are going to make this all work.
To start this work with a very simple example that you understand. I'll choose registration.
Scenario: Register
  Given I am a new user
  When I register
  Then I should be registered

now we can do the step definitions, (I'll use ruby, you will have to translate)
Given 'I am a new user' do
  @i = create_new_user
end

When 'I register' do
  register(user: @i)
end

Then 'I should be registered' do
  check_registration(user: @i)
end

Now we make our helper methods
def create_new_user
  # here you will create a new user. The user will know their email and password
end

def register(user: )
  # here you can use a tool, perhaps selenium, to goto the registration page
  # and fill in the registration from. You can use the user to get the email,
  # password and any other registration details
end

def check_registration(user: )
  # here you will look at where you are in the UI and look at the page to
  # confirm the user is registered
end

And thats pretty much it. You just repeat that pattern for every new piece of behaviour you uncover.
Some further tips
most Givens DO NOT need to go through the UI
all WHENS interact with the UI
all THENS should interact with the UI
what you have done with your backend is totally irrelevant to how you can proceed developing new behaviour with BDD. BDD is all about finding out the WHAT and the WHY. Your backend only becomes relevant when you start thinking about HOW you are going to make the behaviour you have specified work.
If you work in small incremental steps you can use your previous behaviour to build you new behaviour. So once we can register we can start thinking about signing in
Scenario: Sign in
  Given I am registered
  When I sign in
  Then I should be signed in

and we follow exactly the same pattern as above.
Note that because a Given does not have to go through the UI we can do something like
Given 'I am registered' do
  @i = create_registered_user
end

def create_registered_user
  user = create_new_user
  save_user_to_db(user)
  return user
end


Unable to play Soundcloud song on my webpage

Question: I am trying to play a Soundcloud song on my webpage.  I am just trying to test out using the API but I don't seem to be getting anywhere.  Any idea what I am doing wrong?  Soundcloud will authorize me and will show an object for the song, but will not play it.  Not sure how to look up more information, the information for beginners is tough to find or doesn't working.  Trying to do this from developers.soundcloud.com
SC.initialize({
  client_id: 'entered my id from the registered app here'
});

var track_url = 'https://soundcloud.com/aviciiofficial/hope-theres-someone-1';
SC.oEmbed(track_url, { auto_play: true }).then(function(oEmbed) {
  console.log('oEmbed response: ', oEmbed);
});

Answer: This is because the API does not allow you to get the track contents. Unfortunately this is not very clear from the documentation. Nor is it very clear when a track is allowed to be accessed through the API and when it's not.
Find the track id:
curl "https://api.soundcloud.com/resolve?url=https://soundcloud.com/aviciiofficial/hope-theres-someone-1&client_id=..."
{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/255863316?client_id=..."}

wget "https://api.soundcloud.com/tracks/255863316?client_id=..."
--2016-04-25 11:05:01--  https://api.soundcloud.com/tracks/255863316?client_id=...
Resolving api.soundcloud.com... 184.108.40.206
Connecting to api.soundcloud.com|126.96.36.199|:443... connected.
HTTP request sent, awaiting response... 403 Forbidden
2016-04-25 11:05:01 ERROR 403: Forbidden.

This one is allowed to be accessed without a 403 error, and I liked the title of it: https://soundcloud.com/paradoxeodstl/error-403-prod-boxinwoxin


Prove some properties of ring homomorphism

Question:
Let $R,S$ be rings and $\varphi : R\to S$ be a ring homomorphism. Verify that

$\varphi(na) = n\varphi(a)$ for all $n\in\mathbb Z$ and $a\in R$.
$\varphi(a^n) = (\varphi(a))^n$ for all $n\in\mathbb Z^+$ and all $a\in R$.
If $A$ is a subring of $R$, then $\varphi(A) = \{\varphi(a):a\in A\}$ is a subring of $S$.

For (1) I have the following:
$$
\begin{split}
\varphi(na) &= \varphi((n-1)a+a) \\
&= \varphi((n-1)a)+\varphi(a) \\
&= (n-1)\varphi(a)+\varphi(a)\\
&= n\varphi(a).
\end{split}
$$
For (2): For $n=1$, we have $\varphi(a) = \varphi(a)$. Suppose for some $n\in\mathbb Z^+$ that $\varphi(a^n)=(\varphi(a))^n$. Observe:
$$
\begin{split}
\varphi(a^n) & =(\varphi(a))^n \\
\varphi(a)\cdot \varphi(a^n) & =\varphi(a)\cdot (\varphi(a))^n \\
\varphi(a \cdot a^n) & =(\varphi(a))^{n+1} \\
\varphi( a^{n+1}) & =(\varphi(a))^{n+1} \\
\end{split}
$$
For (3): I verify for $a,b\in\varphi(A)$ then $a-b\in\varphi(A)$ and $a\cdot b\in \varphi(A)$ (for brevity).

Well, $0\in A \implies 0 \in \varphi(A) $
For $a,b \in \varphi(A)$ we have $\varphi(a) - \varphi(b) = \varphi(a-b)$, thus, verified, because $a-b\in A$.
For $a,b \in \varphi(A)$, we have $\varphi(a) \cdot \varphi(b) = \varphi (a\cdot b)$, thus, verified, because $a\cdot b \in A$.

Did I do these right? Feedback appreciated!
Comment: Instead of writting "For $n=1$, we have $\varphi(a)=\varphi(a)$" I would write "For $n=1$, we have $\varphi(a^n) = \varphi(a) = (\varphi(a))^n$".
Answer: For the first property,
use induction to show that $\phi(na) = n\phi(a)$ for all $a$ and $n\geq 0$.
This is actually what you have done.
For negative $n$ one must be careful.
For $n>0$ put
$(-n)a = -(na)$, which is the additive inverse of $na$.
This part is then true simply by definition.
Answer: I agree with Wuestenfux's answer, and have some feedback to give. There is some error in your answer to part $(1)$, which is similar to one in part $(2)$ as well. How do you know that $\phi((n-1)a)=(n-1)\phi(a)$? For $(2)$ you suppose that there exists some $n\in\mathbb{Z}^+$ satisfies $\phi(a^n) = (\phi(a))^n$, but it could be the case that
$\{n\in\mathbb{Z}^+|\phi(a^n) = (\phi(a))^n\}$ is empty. For both $(1)$ and $(2)$, one can use induction after showing the properties hold with base case $n=2$.
For problem $(3)$, remember that if $b = \phi(a)$ for some $a\in A$ then $b\in \phi(A)$. It is only once we write an element $b$ in the form $\phi(a)$ that the containment $b\in \phi(A)$ becomes clear. For example, given $0\in A$, we know by properties of ring homomorphisms that
$$\phi(0) =0.$$
Hence $0 = \phi(0) \in \phi(A)$.
"For $a,b\in \phi(A)$, we have $\phi(a) - \phi(b) = \phi(a-b)$." This does not show that $a-b \in \phi(A)$, because $a \neq \phi(a)$ and $b\neq \phi(a)$. Again, to say that $a\in \phi(A)$ means there exists some $x\in A$ for which $\phi(x) = a$.
Comment: Follow up question, apologies for tardiness. Is the question then supposed to have been for $n\in\mathbb Z^+$ for (1) as well?
Comment: In (1), you can show that the result holds for all $n\in\mathbb{Z}$. A method for doing so is showing that (1) holds for $n\in \mathbb{Z}^+$, then using this to prove that it holds for all $\mathbb{Z}$. See Wuestenfux's answer for more detail.


Is the complex conjugate of the complex conjugate of f(x) = f(x)?

Question: Complex conjugate of $\overline f(x)$ ?= f(x)
I'm assuming it is:
f(x) = 1 + i
$\overline f(x)$ = 1 - i
second conjugate = 1 + i
Answer: Don't assume it is.  Use the definition to see that it is.  What does $f$ have to do with it?  If $z$ is a complex number, then $\overline{\overline{z}}=z$, and this is straightforward to show from the definition.
Comment: So my logic is wrong and the answer is no?
Comment: @macdonjo: How did you conclude this?  Suppose $z$ is a complex number.  The complex conjugate of that is denoted $\overline z$. So the complex conjugate of the complex conjugate is denoted $\overline{\overline z}$.  As I mentioned, and as you should show using the definition, for every complex number $z$, $z = \overline{\overline z}$.  That is true regardless of whether or not your $z$ is written as $f(x)$ for some mystery function $f$.
Comment: Me telling you "don't assume" is very different from telling you it isn't true. I mean, show it, don't assume it without reason.  I may have misunderstood your meaning of "assume," but either way I want to encourage you to show that it is true using the definition.


Distinguishing cryptographic properties: hiding and collision resistance

Question: I saw from Another question the following definitions, which clarifies somewhat:
Collision-resistance:
Given: $x$ and $h(x)$
Hard to find: $y$ that is distinct from $x$ and such that $h(y)=h(x)$.
Hiding:
Given: $h(r|x)$, where $r|x$ is the concatenation of $r$ and $x$
Secret: $x$ and a highly-unlikely-and-randomly-chosen $r$
Hard to find: $y$ such that $h(y)=h(r|x)$.
This is different from collision-resistance in that it doesn't matter whether or not $y=r|x$.
My question:
Does this mean that any hash function $h(x)$ is non-hiding if there is no secret $r$, that is, the hash is $h(x)$, not $h(r|x)$?
Example:
Say I make a simple hash function $h(x) = g^x \pmod n$, where $g$ is the generator for the group. The hash should be Collision resistant with $$p(x_1 \ne x_2, h(x_1) = h(x_2)) = \frac{1}{2^{\frac{n}{2}}}$$ but I would think it is hiding as well?
Comment: You "collision resistance" is usually called "second preimage resistant". Collision resistance means for it to be hard to find $x \neq y$ with $h(x) = h(y)$.
Comment: $r$ is given in the hiding property, right? What's the difference between "highly unlikely" and randomly chosen?
Comment: "generator for the group". What group? The invertible integers modulo $n$? If so, that's not "collision resistant" in your weird sense of the word.
Answer:
Pre-image resistant: given a hash value $h$ find $m$ such that $h=Hash(m)$. Consider storing the hashed of password on the server. An attacker will try to find your password.
Second Pre-image resistant: As Henno Brandsma said this is also called collusion resistant means. In this case, the attacker wilt try to find and $h'$ such that $h' = Hash(m)$. Note that; $h'$ can be equal to $h$.
Hiding: This technique due to Time-Memory attack on Block cipher by Hellman and Hash Functions. Modern from, Rainbow Tables, is due to  Oechslin. To mitigate the attacks, one solution is concatenating a random value to passwords, called salt. So the $h=Hash(r|m)$ is stored in the database with the salt. Now, the attacker must have to build a new table for any of the password in the database. Finding an $m'$ s.t $Hash(m') = Hash(r|m)$, in this case, will not solve the problem. Because the server will calculate $Hash(r|m') \neq Hash(r,m)$.
Adding salt (or in general random value), in Cryptography, has many applications.

The answer to your question; yes, it is not hiding, because there is no random. For some applications, non-hiding will be enough, as comparing the hash of the download with hash from the server to see that the download is complete.
I assume that the $g$ generates a cyclic group;
If the two elements are unique, yes the hash will be different. In general, however, one must support larger values than the group size. such two values $x_1 = x_2 + k \bmod m$ will have collision. To hide it, you must add random value.


Exhaustive list of techniques used to estimate population mean and variance?

Question: In beginning stats, we were told that:

$\bar{x}$ is an unbiased estimate of $\mu$
$\frac{1}{n - 1}\sum(x - \bar{x})^2$ is an unbiased estimate of $\sigma^2$

As I am reading more, I have learned that you could estimate population variance and mean using other ways such as:

Method of Moments
Maximum Likelihood Estimation

To round out my knowledge, I have a few questions.

Is there an exhaustive list of estimation techniques used to estimate population mean and variance?  Or are those 2 the only ones?
Is "$\bar{x}$ is an unbiased estimate of $\mu$" considered an example of method of moments estimation?
What about "$\frac{1}{n - 1}\sum(x - \bar{x})^2$ is an unbiased estimate of $\sigma^2$"?  What estimation technique does that involve?  My understanding is both MLE and MOM produce biased estimates of population variance.
Comment: For 2 and 3, you can say $\mathbb E\left[\bar{x} \right]=\mu$ and $\mathbb E\left[\frac{1}{n-1}\sum (x_i-\bar{x})^2 \right]=\sigma^2$ and for normally distributed random variables with unknown mean and variance they are the "minimum variance unbiased estimators" (MVUE) related to the Rao–Blackwell theorem and Lehmann–Scheffé theorem.
Comment: On 1, all these and others, such as [minimum mean square error](https://en.wikipedia.org/wiki/Minimum_mean_square_error), are frequentist point estimators.  There are more.  More broadly there are other techniques such as interval estimation and Bayesian methods with posterior distributions for the parameters (you can even have various Bayesian point estimators).  There may not be an exhaustive list
Comment: The [method of moments produces unbiased estimators](https://stats.stackexchange.com/a/459659/7224) of all non-central moments.
Answer: 1) Exhaustive? Nope.
2) $\bar{x}$ is the MOM estimator and happens to be unbiased. Being unbiased and MOM do not go together, however.
3) The $n-1$ adjustment comes from taking the expected value of the MLE and finding that there's an easy correction to get an unbiased estimator. When you take the square root to get what you might think is an unbiased estimator of standard deviation, you in fact get a biased estimator of standard deviation! There is not a straightforward adjustment for all distributions to give an unbiased estimator, though it has been worked out in special cases (such as normal).


Permutation Analysis using unequal samples

Question: I need to conduct a permutation analysis on unequal samples, one (X) with 579 data points, and another (Y) with 1289 data points.  There is an obvious difference in the data.  However, this difference may be due to the imbalance between sample sizes.  I need to run a permutation analysis using all possible pairs (combinations) of these data points to see what the likelihood that these differences are real and not artifact due to the imbalance. The results need to give me p-values to interpret for significance testing.  I am very new to R.  Also, most everything I have found gives me paired-samples.  Does anyone have code or suggestions to do this?
Thanks.
Comment: What exactly are you comparing between the two groups?  What is this "obvious difference" and how are you measuring it?  Also, please be careful with your terminology, because a "pair" and a "combination" and a "permutation" are all very different things. A pair literally is just two things; a combination is a subset of things; and a permutation is a re-ordering of all of them. Because you seem to have used these three terms as if they were equivalent, please consider editing this question to clear up that ambiguity.
Answer: Your data are apparently not paired. You should not be attempting to pair unpaired data.
With (presumably) independent samples, the usual form of permutation test simply permutes the group labels.
With your sample sizes, a full permutation test would usually be impractical (unless the sample difference is fairly extreme, in which case a complete enumeration of the tail may be feasible).
As such we'd usually be looking at a randomization test.
In the independent samples case, when testing for a difference in means that consists of any statistic yielding equivalent p-values (i.e. providing the same ordering of samples as a difference in means).
The sum of the values in the smaller sample would be sufficient (the difference in means is a simple linear transformation of this).
So the randomization test would consist of selecting random sets of 579 values from the combined sample of (579+1289) points and computing their sum, and then locating the sample value in that distribution and identifying the proportion of statistics at least as extreme as the observed one - counting the observed one.
With a two-tailed test, you can compute a sum of values in the smaller sample for the difference in means having the opposite sign to the observed and make teh same count of the proportion more extreme in the other tail.

The independent-samples randomization test is a pretty standard test. In R you should be able to do it using the coin package, but writing code for it is pretty simple (though possibly a good deal slower than using a function in a well-built package).
Consider the following data (this is small enough to do complete enumeration of the permutation distribution, but we'll do it as a randomization test):
Sample A: 23.194 28.027 37.487 31.180 30.430 38.424
Sample B: 34.623 32.936 36.885
 a <- scan()
 23.194 28.027 37.487 31.180 30.430 38.424

 b <- scan()
 34.623 32.936 36.885

 (mean.diff <- mean(b)-mean(a))
 [1] 3.357667

 sumb <- sum(b)
 alldata <- c(a,b)

 res <- replicate(10000,sum(sample(alldata,3)))

 res <- c(res,sumb)
 extreme1 <- sum(res >= sumb)
 extreme2 <- sum(res >= sumb)+sum(res <= 3*(2*mean(alldata)-mean(b)))
 p.value.1 <- extreme1/10000
 p.value.2 <- extreme2/10000

In my example it gives an (upper) one tailed p-value of $0.19$. and a two-tailed p-value of $0.37$.
You'd have to make a few adjustments for your sample data but that's the gist of how it works.
The exact permutation test p-value in this case is computed thusly:
permsum = combn(alldata,3,sum)
pp.value.1 = sum(sumb<=permsum)/length(permsum)
pp.value.2 = pp.value.1+sum(3*(2*mean(alldata)-mean(b))>=permsum)/length(permsum)
hist(permsum,n=50)
abline(v=sumb,lty=2,col=6)
abline(v=3*(2*mean(alldata)-mean(b)),lty=2,col=8)

The corresponding exact 1- and 2- tailed p-values here are $0.19$ and $0.37$.


Is it dangerous if I expose my database schema in an open source project?

Question: I am writing myself a blog in python, and am to put it up to GitHub.
One of the file in this project will be a script that create the required tables in DB at the very beginning. Since I've gonna put this file on a public repository, I expose all DB structure.
Is it dangerous if I do so?
If yes, I am thinking of an alternative to put column names in a separate config file and not upload column names of my blog. What are others ways of avoiding exposing schemas?
Comment: Security by obscurity is not going to keep you safe. Publish the schema.
Comment: "Dangerous"?  How so, especially in a self-professed open source project?  What harm are you imagining?
Comment: Most people are not malicious, you'll find that more people want to help than to exploit any weaknesses in your code.
Comment: Martijn said everything :)
Answer: It's not dangerous if you secure access to database. You are exposing only your know-how. Once somebody gains access to database, it's easy to list database structure.
Comment: @FrostNovaZzz: If someone can use a SQL injection attack, they can query your database structure. Not knowing the structure won't prevent a SQL injection attack.
Comment: Yes I understand that. I concern is that there seem always to be security hole to leak access to my database, so I am thinking hiding column names will be a save a lot of efforts in securing access?
Answer: I think it is dangerous, as if  a SQL injection vulnerability exists in your website, the scheme will help the attacker to retrieve all important data easier.
Answer: There is a difference between sharing database and database schema.
You can comment the values of database machine/username/password in your code and publish the code on github.
As a proof of concept, you can host your application on cloud(without disclosing its database credentials) and add its link to your github readme file.


How to prove this assertion below?

Question: A matrix $A$ is a scalar matrix if it commutes with every matrix $B$.
I exactly know that if a matrix is a scalar matrix, then it commutes with every matrix. But I do not know how to show the reverse proposition.
I negated the "then" part and tried to show a contradiction, but I felt it may be wrong. There must be a nice proof.
Thanks.
Comment: What contradiction did you find?
Answer: Hint: Let $B$ be a matrix whose entries are all $0$ except for one non-diagonal entry, which has value $1$. What can you learn about $A$ from the fact that $AB=BA$? Try an example of such a $B$ before you attempt the general case.

How to prove this assertion below?


Place two text fields within a single  class

Question: I have assigned class names to both user name & password text fields in user login block separately like this and it's working.
function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
   }
}

I want to include these fields inside a single '' and assign class name for design purpose, like this.

  username field
  password field

I am using the following code but I didn't get the expected output.
function mymodule_form_alter(&$form, &$form_state, $form_id, $element) {
   if ( TRUE === in_array( $form_id, array( 'user_login', 'user_login_block') ) ) {
       $form['user_login']['#attributes']['class'] = array('#prefix' => 'myclass');
       $form['name']['#attributes']['class'] = array('mgnB10', 'fntXL', 'drkFg1');
       $form['pass']['#attributes']['class'] = array('fntXL', 'drkFg1');
       $form['user_login'] = array('#suffix' => '
');
   }
}

Answer: Hope this will help you,
In Drupal 7 you can achieve it by using the #prefix and #suffix properties in hook_form_alter().
   /**
    * Implements hook_form_alter().
    */
    function hook_form_alter(&$form, &$form_state, $form_id) {
      switch ($form_id) {
        case 'user_login':
        case 'user_login_block':
          $form['name']['#prefix'] = '<div class="username-password-wrapper">';
          $form['pass']['#suffix'] = '</div>';
          break;
      }
    }

Comment: Welcome enjoy :)
Answer: Instead of doing this programmatically, you can use the Field Group module, which allows you to group fields using the Manage Fields tab in the UI.

 can be selected as the group type.
Comment: I installed Field Group module. In manage field page of Article I added group and two fields inside it. In Widget column I saw div open
required_fields yes
classes group-test-group field-group-div
show_label Yes
label_element Header 3
effect None
speed Fast Now it doesn't work and I how can I add  div close. How do I add close div?


Convert. Int64 or int.Parse Is Not Recognized LINQ To Entities

Question: I am trying to get range data between two strings.
i have list of string which have data like this
Example:
K123456,
H123456,
J123456,
T122123,

So the first charter of string object contains an alphabet.
var StartLabwareid = int.Parse(obj.LWbStartId.Replace(labIni,""));
var EndtLabwareid = int.Parse(obj.LWbEndId.Replace(labIni, ""));

var LabWId = (from ai in _entities.Ai
              join result in _entities.Re on ai.Id equals re.Id
              where (Convert.ToInt32(ai.Id.Replace(Ini,"")) <= Startid ||
                     Convert.ToInt32(ai.Id.Replace(Ini, "")) >= Endtid)
              select new MViewModel
              {
                  ID = re.Id,
              }).ToList();

Or I can use something else to compare to string and get data between that as we do in date range St rating and Ending Date
Comment: Not entirely sure what you're doing here, what is `Ini` and `labIni`? Can you give us an example of your start and end parameters and which rows you would like to return? The comparison parts also looks odd because it seems your SQL is retrieving rows *not* in that range, contrary to your description. Please be more specific in your question and example.
Comment: Since this is LINQ to Entities, what ever you are doing in you LINQ statement has to be translatable to SQL, so you are fairly limited in what you can use in your statement.
Comment: labIni is the starting charter of id example "K1234" so Labini is K
Answer: You cannot use C# functions such as Convert in Linq to Entities. Instead, you could do your comparison after the result is materialized, or use SqlFunctions. With SqlFunctions, you should get your result with combining Stuff and CharIndex functions. Modify the line below to suit your needs, since you are not providing all of the code.
SqlFunctions.Stuff(ai.Id, SqlFunctions.CharIndex(ai.Id, "replaceable"), 3, "")


HandleErrorAttribute is not working in MVC 5

Question: I am trying to make HandleErrorAttribut working in ASP.NET MVC 5 but it's not working
I created FilterConfig.cs file under App_Start
namespace WebApplication12.App_Start
{
    public class FilterConfig
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    }
}

and in Global.asax
namespace WebApplication12
{
    public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        }

    }
}

and in web.config
  <system.web>
     <customErrors mode="On" defaultRedirect="~/Views/Errorrr.cshtml">
       </customErrors>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

And still get errors and can't handle exceptions
  [HandleError]
        public ActionResult Index()
        {

            throw new Exception("New Error");
 }

Thank you,
Lucia
Answer: By default, the HandleError Attribute will display the Error view located in the ~/Views/Shared folder but if you wanted to display a specific view you can set the View property of the attribute.
[HandleError(View = "Error")]
public ActionResult Index()
{
    ViewBag.Message = "Welcome to ASP.NET MVC!";
    int u = Convert.ToInt32("");// Error line
    return View();
}

See if this helps.
Answer: If its Mvc5 make sure you use "using System.Web.Mvc" and not "using System.Web.Http.Filters"  as the latter is  for WebApi. Also can you post the code for HandleErrorAttribute class.


Memory allocation troubles SSAS Azure

Question: Hello guys,
I have a cube on Azure and when I want to process the partitions (using SSMS) I have that error message Memory error: You have reached the maximum allowable memory allocation for your tier. Consider upgrading to a tier with more available memory.
The thing is that I still have 20gb free on my instance and one partition is something like 300mb. I think the problem could come from the calculated columns because the process is perfectly working when I don't have those calculated columns.
Any idea on how to solve it ?
Thanks a lot.
Comment: Can you post the DAX for your calculated columns? Can you confirm if you just do ProcessData not ProcessRecalc (to skip calculated columns) it doesn't fail?
Answer: Actually my problem has been solved. I used that calculated column [column1]&[column2] to concatenate and it was not working. By changing it into CONCATENATE([column1];[column2]) it worked perfectly. I guess the & was part of the problem for some reason.
Thanks.

Memory allocation troubles SSAS Azure


How to distinguish data types in a string with C on Linux?

Question: I'm writing a simple program that verifies an a 8 character password with a minimum of two numbers. This seems to be commonly assigned to beginners, but I could not find any answers to my question anywhere online and failed the assignment, but I would still like to learn how to do this and think this would be of help to other beginners like me
I need to verify that a string containing both letters and numbers contains at least two numbers.
isalpha() or isdigit() only read one character at a time, and strspn( , ) or strcspn() stop calculating length when it gets to a byte not found in the other segment, so if I input a password like "a1b2c3" using either one of those functions, the output will be 1 or 0.
I have also tried switching up the data types from char to int and vice versa.
This is what I have so far:
<code>#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <ncurses.h>

int main() {

   char password[8];
   char numVerify[] = "1, 2, 4, 5, 6, 7, 8, 9";
   int valid = 10

  do {
       printf("Enter Password: \n");
       scanf("%s",password);
       int a = strspn(password,numVerify);

     if (strlen(password) <= 8 && a >= 2 ) {

         printf("You have entered a valid password");

         break;
       }
         else {
         printf("\e[2J\e[H");
         printf("Invalid Password!\nEnter password with a maximum of 8 characters and at least 2 numbers\n");
            }
   }while(valid > 5 );

    return 0;
}
</code>
Comment: The "password" variable should be "char password[9];"  additionally, strspn() does not do what I think YOU think it does.  Perhaps you should simply count the number of characters in "password" that "isdigit()" returns a non-zero value.  After testing all characters in "password", if your digit_count is greater than or equal to 2, then it passes edit.
Answer: You need to count the num of Numbers in the string. Use a for loop to go through each letter in the string
<code>int numcount=0;
for (i = 0; i < strlen(string); i++) {
if(isdigit()) numcount+=;}
if(numcount>=2) //password is good {}
else {} //bad
</code>
Probably not good syntax. Havent used C in awhile but this is the idea.
Comment: This worked for me, with slightly different syntax, but this is exactly what I needed. Thank you so much!


does F(x) = -F(1/x) for all x in domain of F for this specific F(x)?

Question: I apologize in advance for my ignorance on how to type mathematical symbols in this editor.
Let F be the function defined for $x > 0$ by
$F(x)= \int_1^x e^{((t^2)+1)/t}\frac{dt}{t}$
Show that $F(x) = -F(1/x)$ for all $x$ in domain of $F$.
What I have done is used the mean value theorem for integrals to say that there exists a number $z$ such that:
$e^{((z^2)+1)/z} \cdot \int_1^x\frac{dt}{t} = e^{((z^2)+1)/z} \cdot (-1)\cdot\int_1^{1/x}\frac{dt}{t}$ and that they both equal $e^{((z^2)+1)/z}\ln|x|$.
What i can't figure out is how to show that the $z$ used for the first function ($F(x)$) is the same as the $z$ used in the second function ($-F(1/x)$).
Does anyone know how I could go about it?
thank you.
Comment: How is $F$ defined on $x>0$, when the integral starts from $1$? Isn't $F$ defined on $x\geq 1$?
Comment: @frabala You can have $00$ so that we don't divide by zero.
Answer: First, write the integral this way:
$$
F(x) = \int_1^x e^{t + 1/t}\frac{dt}{t}.
$$
Now we'll try the $u$-substitution $u=1/t$. Then $dt=-du/u^2$ and the new integral is
$$
F(x)=\int_1^{1/x} e^{1/u+u}\cdot\frac{-du/u^2}{1/u}
= -\int_1^{1/x}e^{u+1/u}\frac{du}{u} = -F(1/x).
$$
Comment: Thank you for looking at this. I tried using u=1/t but i didn't get anywhere with it. I can't use it in the original integral because i'll keep a t dependence on the exponent. Maybe i missed something? what I was planning on doing was to somehow make the limits of integration from 1 to x and from 1 to 1/x the same, but even this doesn't make sense as it would make the function = 0 where it's not defined.
Comment: Sorry i keep coming back to you, but could you loor at this question: http://math.stackexchange.com/questions/785458/error-replacing-integral-of-f-with-its-midpoint-rule-approximation


Is this absolute value notation or something else?

Question: In this document, in Figure 1 (second to last page) there are several uses of $\| \;\;\|$:

Is this another notation for absolute value, or is this a notation for something to do with vectors/matrices?
Comment: that is a "norm" a generalization of absolute value. In simplest term norm of a vector is its length. [ref](http://en.wikipedia.org/wiki/Norm_(mathematics))
Answer: As the document says immediately following the introduction:

This Wikipedia page has the definition of the $2$-norm and the $\infty$-norm of a vector. The definition is as follows: for a vector $x=(x_1,\ldots,x_m)\in\mathbb{R}^m$, the $p$-norm of $x$ is
$$\|x\|_p:=(x_1^p+\cdots+x_m^p)^{1/p}$$
if $p$ is finite, and if $p=\infty$, we define
$$\|x\|_\infty:=\max\{x_1,\ldots,x_m\}.$$


Non-linear Model vs Linear Model for a dataset

Question: I have a time series dataset for a city. The dataset contains rainfall amount and the number of repairman requests to a company. The company has 20 shops in different blocks of city and the rainfall data is also individually available for all 20 block. One point to consider is that rainfall is seasonal , hence when there is a rainfall in one block there is a high probability that there will be rainfall in some other block. Also it is assumed that a person in a given block will always place a request in the shop present nearest to him
I am trying to establish a relationship between the amount of rainfall and the number of repairman requests in that city at a block level.
I am getting good results when I model the aggregated data for the whole city using a linear model. In contrast when I model the data on individual block level using linear model, the results are not that good. Hence I have to use non linear models when establishing a relationship on block level.
What I want to do is to try to justify the use of non linear model instead of linear model for modelling relationship at a block level. One method which I feel could provide the justification is that 'law of large number' is not applicable at a block level of city but is applicable when the whole city is considered as a single unit.
Is this justification correct? Or do I need a different justification?
What sort of analysis do I need to perform  to support the justification?
Comment: How are you dealing with the dependence in the data? What sort of model are you using?
Comment: Yes, I am trying to make a hypothesis that the amount of rainfall can be used to predict the number of repairman requests.

When treating the whole city as a single unit I am using a linear model Y ~ mX + c.

When predicting on a block level, I am using random forest model (non-linear) predicting Y with predictor X
Comment: What exactly are you referring to as dependence? Dependence of one block on another, or dependence of requests on rainfall?
Comment: Dependence over time. You have repeated measures. This violates the assumptions of linear regression and other regression methods. Two common ways of dealing with it are multilevel models and time series methods (ARIMA and so on). Your model Y ~ mX + c is inappropriate, unless I am missing something. Random forests are likely to also be inappropriate, but I am not certain and it may depend on exactly how you are implementing them.
Comment: The hypothesis I am trying to make is that for any week w in any location l, the amount of rainfall R(w,l) is a good predictor of the number of requests in that week in that location Q(w,l).

Hence I am not exactly treating it as a timeseries. I mean Q(w,l) is independent of both Q(w-1,l) and Q(w,l2)
Comment: The last statement seems rather suspect.
Answer: I am too "young" to join the discussion in the comments, so I will post my ideas and guesses as an answer.
I think there are better ways to estimate model fit (and hence justify it) than appealing to asymptotic laws. For example, you can fit a model an inspect the prediction errors. Or you can do cross validation and figure out which of the models has a better predictive capabilities.
In your case, it seems that you have already (somehow) determined that pooled linear model is inadequate and want to go to block level. I don't know why it didn't work, but I can guess - you have too little data on a block level and individual-block-regressions model overfits. If that is the case, the decision to go to individual-block-nonlinear-model is slightly suspicious, as you could overfit even more. Maybe you could consider an approach like hierarchical regression, which regularizes individual regressions.
When you are happy about the block level fit, then it is only appropriate to plot errors over time, and look if time is significant predictor. If it is, you can include it into the model as well.
Comment: What I mean by aggregated data is that I have aggregated data over all locations i.e sum of all requests from all blocks and sum of rainfall in all blocks. The linear model describing a relationship between this summed up data is a good fit.
But if instead I use a hierarchical model or a simple linear model treating each block separately but training just a single model for all, then the results are bad.

My non-linear model also treats all blocks separately, but I have a single model trained and tested on combined data of all blocks and it works well.
Comment: So it seems that you have already figured out the goodness of fit part. In such case I don't think there is a need for a further justification of the model, unless you want to understand yourself why regularized linear models were inadequate compared to random forests. I don't think I can say anything clever with regards to that, especially without seeing the data.


UI testing Blazor Dekstop apps

Question: I'm really interested in making the next project in MAUI with WebView hosting Blazor app.
I know that I can use bUnit to unit test components, but is there a solution to run full UI tests like in Cypress?
I mean literally running the app, and have something click around. Or is bUnit enough? Is it able to run MAUI app with all native services (like opening a file from disk with a native popup) or do I need to mock the edge services?
I came with an alternative which would be to setup a server side Blazor poject running the same app and just use Cypress, but I don't really like this idea.
Answer: for anyone wondering, Playwrite has a dotnet API and works pretty nice: https://playwright.dev/dotnet/

UI testing Blazor Dekstop apps


.bashrc in the cloud?

Question: I do alot of development from the terminal at both work and home.  What's a good solution for keeping all of my .bashrc, .vimrc, .screenrc, Irssi configs and scripts, etc. in sync across multiple machines?
I was thinking of setting up a hook in my .bash_login to go into a ssh into a central repository and rsync everything, but is there a better way?
Answer: One solution I have seen used by a number of my friends is to put all of their configuration files in a source control repository like Github which can use your home direcoory as their working directory.
Then all you need to do is pull from the repository and all of your rc files will be up to date. Committing changes from any of your machines and pushing them allows you to make those changes available everywhere.
In order to deal with variation among versions or paths between machines you can either use multiple branches(or tags depending on your choice of revision control) or just use the building in condition abilities of your config files (at those which support such things).
Comment: As an added benefit, your files are versioned. If you want to know what's different between this version and the last one, it's easy to find out.
Comment: I do something similar.  I use CVS for my `$HOME/.*` and `$HOME/bin/*` files.  For various reasons, I don't check them out directly into my home directory; instead, I have `update-home` and `update-bin` scripts that copy files from my checked-out CVS repository.  (I like git, but CVS makes it easier to track versions of individual, and possibly unrelated, files.)
Comment: Yeah, I switched to having my dotfiles in github, and it's super great.  Thanks!
Answer: Put your config files in your Dropbox folder, and symlink to them in your homedir.
Comment: I don't think this will work if I'm remoting into a server and all I have is terminal access

.bashrc in the cloud?


Edit theme login page

Question: I'm using a theme called Nexus.
Now in the login page, /?q=user, it looks somewhat like this:

All I want to do is change the order of the tabs, where "Log in" is in front, number one, then Request new password, then lastly Create new account.
Aka:
[Log in][Request new password][Create new account]
I've tried looking in the theme's folder, including page.tpl.php, and in the user module files to see if I could find where it was defined/rendered but I couldn't find anything.
This also did not seem to be what I wanted.
Sorry for being such a noob.
Answer: You may use hook_menu_alter function to do it
<code>/**
 * Implements hook_menu_alter.
 */
 function MYMODULE_menu_alter(&$items) {
   $items['user/login']['weight'] = 0;
   $items['user/password']['weight'] = 1;
   $items['user/register']['weight'] = 2;
 }
</code>
Comment: In sites/all/themes/Nexus/nexus/template.php, nexus_menu_alter(&$items) this is already defined ... in the same order. How come it does not render the same way?
Comment: have you cleared caches?
Comment: Tried clearing caches, tried changing weights and clearing cache again.
Comment: Sorry I've made mistake in code, now it should work
Comment: That's weird though, it was defined with '#weight' in the existing theme code, removing the '#' did nothing.. Cleared my caches too.

Edit theme login page


Enable mod_rewrite Apache

Question: When I try to turn the RewriteEngine on, it tells me that mod_rewrite is not installed.
I've looked in my apache2.conf file and there is not line to uncomment that resembles
LoadModule rewrite_module modules/mod_rewrite.so

I am not savvy at system admin and I want to make sure I don't screw up my server.  Can I just copy (or symlink) mod_rewrite.so into my mods_enabled directory?  Should I load the module as I tried above?
Comment: The problem is that the module is not installed and for us to being able to help you, you need to tell us what distro you are using. And then this question is better suited for Server fault.
Comment: i've seen similar questions posed here. I'm using ubuntu 10.4.
Answer: First you need to check if the module is installed do this by:
cd /etc/apache2/mods-available
ls -la

If the module is not installed you do:
apt-get install libapache2-mod-rewrite

Then you need to active the module:
a2enmod rewrite

If you want to disable it:
a2dismod rewrite

Note that you shouldn't add modules in apaches config manually, you should use the a2enmod/a2dismod command.
Comment: done and done, thanks Ancide.  I was going to install manually!
Comment: I'm glad I could be of help :) Also you have the mods-enabled folder where you find all mods that are installed if you ever would want to.

Enable mod_rewrite Apache


NFS performace degradation

Question: I work for a small software house.
We share our developers' home directories over NFS.  The primary use for this is to host the users' git repository.
Since last week, there has been a signficant degradation in performance.  For example, cmake invocation (used by our build system) has slowed down markedly.  I don't have numbers for a build on nfs share from before the slowdown, but the comparison between local disk and nfs for this task is:

Local: 29.3s
  NFS: 9m 46.9s (586s)

So we have this job running (rather neatly) 20x slower on the NFS share.  Load average on the NFS server is not high.  If anything, we have fewer staff working due to people taking annual leave in August.  I think it must be either network or server specific because the problem is seen from multiple clients.
What might cause this kind of slowdown?
Edit:
Server is Centos 6.3 running on a DL180G6. Kernel is 2.6.32-279.el6.x86_64. Clients are generally Centos 6.2 and 6.3. Network is 1G ethernet with utp cabling. Network mount points are shared via NIS maps. The server is running autofs-5.0.5-54.el6.x86_64.
The export line in /etc/exports on the NFS server is:
/export/home 10.0.1.0/24(rw,nohide,no_root_squash,sync) 10.1.0.0/24(rw,nohide,no_root_squash,sync)

The timestamp on this file does not suggest that this has been edited recently.
Comment: When you typed out this question did no part of your conscious mind not consider adding some of the pertinent details here? say make/model of whatever your NFS servers is, OS version, config, filesystem, network design - you know, some form of actual detail that might give us a 1% chance of helping you here. This is the technical version of "My car had broken down, it's a blue one".
Comment: What are your NFS mount options?
Comment: Harsh...but fair!

Server is Centos 6.3 running on a DL180G6.  Kernel is 2.6.32-279.el6.x86_64.
Clients are generally Centos 6.2 and 6.3.
Network is 1G ethernet with utp cabling.

Network mount points are shared via NIS maps.  The server is running autofs: autofs-5.0.5-54.el6.x86_64

I'll put the share options into a separate comment, because I'm running out of characters.
Comment: The export line in /etc/exports on the NFS server is:
/export/home    10.0.1.0/24(rw,nohide,no_root_squash,sync) 10.1.0.0/24(rw,nohide,no_root_squash,sync)
The timestamp on this file does not suggest that this has been edited recently.
Answer: The answer turned out to be an error on the RAID card.
Sorry for the inconvenience.  I write because of the slim possibilty that someone else might hit something similar.
To recap:
build duration slowed down by a factor of ~3, and the duration was consistent +/-10%, hence suggesting that load wasn't the primary factor.

NFS performace degradation


Cloud functions with firebase: firebase.functions is not a function

Question: After creating a cloud function addMessage on Firebase using Firebase SDK 4.12.0, the following code does not work when attempting to call the addMessage function from within my client app:
var firebase = require("../node_modules/firebase")
var functions = firebase.functions();

functions.httpsCallable("addMessage").call(
    //...
)

TypeError: firebase.functions is not a function
Answer: The solution was to add
require("firebase/functions")
Comment: For those who are loading from CDN, include corresponding Firebase JS SDKs. For example, if firebase.functions() is undefined, then include  `firebase-functions.js` from CDN as documented here
https://firebase.google.com/docs/web/setup#libraries_CDN
Comment: If using ES6 use this: import 'firebase/functions'
Comment: a "-" not / is seems const functions = require('firebase-functions');


Tratar Exceção no Post do Jquery

Question: Tenho esta função Javascript (Post Ajax) que quando dá exceção no post ela está passando noif (r != "") {.
Eu precisava capturar que foi uma exceção e tratá-la fora do if.
JavaScript
function AsyncAlert() {
    $.post("MinhaUrl/AsyncMessage", {}, function (r) {
        if (r != "") {
            mensagemAlert(r);
        }
    });
}

C#
public JsonResult AsyncMessage()
{
    if(TemMensagemNovaAsync())
        return Json(_msgAsync);
    else
        return Json("");
}

Considere que eu preciso capturar a exceção caso não tenha conseguido conectar no backend. Em outras palavras, o servidor da url caiu, a url não estava disponível

Qual a melhor maneira para eu rever isso?
Observação: minha linguagem é C#.
Comment: Se manda requisição para qual tipo de linguagem? se quer tratar o que por exemplo, cites problemas?
Comment: Estou utilizando C#
Comment: Bruno pode ser feito um retorno com a excessão que deu no servidor, um paramento indicado `true` ou `false`, é assim nada complicado, mas, ao mesmo tempo fiquei na duvida porque Erros podem ser diversos
Comment: Mas true or false vem no parâmetro "r" no caso? Eu imaginei algo tipo o success do ajax post...
Comment: Bruno eu consigo retornar qualquer coisa pela linguagem de programação, mas, existe uma duvida por exemplo eu consigo retornar assim `r.success = true` sem problemas tranquilamente, mas, está indefinido como você quer que isso seja retornado. Eu posso retornar a execção completa, não sei se é válido para o seu contexto... entendeu?
Comment: Ah sim... entendi o q vc quis dizer.
Minha preocupação não é no backend, pois lá já está tratado. A exceção que me refiro é por exemplo não conseguiu fazer o post na URL.
Comment: Poste o seu código completo javascript e o backend completo por favor.
Comment: Mesmo quando dá alguma exceção ele entra naquela função?
Comment: Virgilio, postado.
Comment: jbueno, exatamente isso que eu quero. Saber q ele não conseguiu entrar na função do backend.
Comment: Então, você que tratar as *exceptions*, não é? O que eu quero saber é se mesmo quando estoura alguma exception no server side a função do client-side está sendo executada. Porque se for isso, tem mais algo errado.
Comment: @jbueno, o server já está com o tratamento para não estourar exceptions.
A única exception que poderia estourar neste caso aí é se o post não conseguisse acessar a URL. ou seja, alguma exceção na tentativa de post.
Answer: Na documentação do $.post(), existe o .fail(). Utilize ele para fazer algo caso acontece algum erro no server.
Um exemplo simples seria este:

$.post("MinhaUrl/AsyncMessage", function() {
  console.log("sucesso");
}).done(function() {
  console.log("segundo sucesso");
}).fail(function() {
  console.log("error");
}).always(function() {
  console.log("terminou");
});

Tratar Exceção no Post do Jquery


Eclipse complains about getActionBar overridden method

Question: android.app.Activity has getActionBar() method which returns android.app.ActionBar. Then a library project contains a custom activity which extends from Activity. This custom activity class has a getActionBar() method(without @OVERRIDE) which returns a custom ActionBar, not android.app.ActionBar. Then Eclipse complains about incompatible return type for the getActionBar(). Because this is an external library project I don't want to change the name getActionBar() and custom ActionBar class. Solution?
Answer: Is not possible. Change the name getActionBar().
Defining Methods in java
Comment: This library was developed for before 3.0 when ActionBar was introduced, so there is conflict. Changing API level to 8 solved the problem.


Classifying whether a collection of objects is a set

Question: I'm wondering whether or not there is a definite criterion for determining whether a collection of objects is a set. In the literature, I've recently encountered some obscure examples (in Riemann Surface Theory, to be precise) of naturally-arising collections of objects which are not sets.
Here is some pseudo-rigor to make the question more precise:
Let $S$ be a collection of objects. Is there some property $P$ so that $S$ is a set iff $S$ has property $P$?
Comment: I don't really think there is, unless you consider "constructible from the axioms" such a property. Otherwise, why not have property $P$ as the sole axiom of set theory?
Comment: This isn't worth a separate answer, but let me elaborate on Andres' point: "The class of all countable groups, for instance, is a proper class. It is true that all such groups are bounded in size, but their elements don't need to be: Given any group $G$, you can pick a monstruously large set $M$ and obtain a group isomorphic to $G$ simply by replacing the identity of $G$ with $M$." In general, a class of objects which is "isomorphism-invariant" is a proper class for exactly this reason: we can tweak the "actual elements" of an object of the class while keeping the structure the same.
Comment: @Jam Please do not add the elementary-set-theory tag. As the answers illustrate, it does not really belong here.
Comment: For the opposite question, see https://math.stackexchange.com/questions/3406931/can-we-characterize-properties-that-dont-make-a-set
Answer: In ZF-style foundations, the name of the game is rank (which annoyingly doesn't have its own wikipedia page). If you have defined a class $C$ of sets representing mathematical objects in ZF (or ZFC, or NBG or what-have-you) then it is a set if and only if there is an ordinal $\alpha$ such that every element of $C$ has rank less than $\alpha.$
In practice, this is usually decidable, but it doesn't need to be since we can easily cook up a stupid example to the contrary: let $C$ be defined as the class where for any set $x,$ $x\in C$ if and only if the continuum hypothesis holds. So $C$ is a proper class if and only if CH holds, and so assuming we aren't using axioms strong enough to decide CH, it is undecidable whether $C$ is a set.
(That was the "useful" answer. A less useful answer is that a class is a set iff it is co-extensive with a set. We could write this in the first order language of set theory as: $\exists y \forall x(x\in C\leftrightarrow x\in y)$ where here $x\in C$ is shorthand for the first-order formula $\varphi_C(x)$ that defines membership in the class. It just so happens that in ZF, this is provably equivalent to the more satisfying property above.)
Comment: Well... https://en.wikipedia.org/wiki/Rank_(set_theory) (redirects to the _Von Neumann universe_ page you linked to)
Answer: In ZF and related theories, as indicated in another answer, the key to whether a class is a set is whether it has a rank, meaning that it appears at some point in the process of forming sets by starting with the empty set and iterating (throughout the ordinals) the operations of taking power sets and collecting what you have so far.
The drawback of the above is that some working knowledge of ordinals is needed even to understand the statement. However, as a corollary, there is a different criterion that is also useful in practice. To state it, we need the notion of transitive closure. The thing to keep in mind is that in ZF every actual object is a set. Given a class $x_0=x$, its elements are sets and so we can collect them together by taking the union of $x$, $x_1=\bigcup x_0$. The elements of the elements of $x$ are also sets, so we can collect them together by considering $x_2=\bigcup x_1$, etc. Let $x_\infty=\bigcup_{n\in\mathbb N}x_n$. This is the transitive closure of $x_0$.
Ok, the criterion:

A class $X$ is a set if and only if there is a bound on the size of the members of $X_\infty$.

This is useful in practice: The class of all countable groups, for instance, is a proper class. It is true that all such groups are bounded in size, but their elements don't need to be: Given any group $G$, you can pick a monstruously large set $M$ and obtain a group isomorphic to $G$ simply by replacing the identity of $G$ with $M$.
Many natural classes appearing in practice are closed under isomorphism, and a similar silly construction as in the example above shows that they are proper classes.

(The universe of all sets can be stratified according to rank, for any ordinal $\alpha$, the set of all sets of rank smaller than $\alpha$ is denoted $V_\alpha$, and any set belongs to some $V_\alpha$.
Sets can also be stratified according to the size of their transitive closure. For any cardinal $\kappa$, the sets $x$ whose transitive closure has size strictly smaller than $\kappa$ is denoted $H(\kappa)$ or $H_\kappa$, and any set belongs to some $H_\kappa$. There is a small technicality that doesn't come into play in the above; see here.)
Comment: Thank you for the comment. Talk of classes in ZF is perfectly standard, this is not an issue in the situations in practice where the question arises. Bringing MK into the matter seems to confuse things, on the other hand. The point of the answer is to provide a practical test that can be used without needing to know the underlying foundations. (If one is conversant in said foundations, there is no need for the question.)
Answer: Traditionally speaking, along the standard line of set theory, i.e. ZFC, "set" is not definable, the axioms of ZFC function to lay down characteristics about sets, so every object in the domain of discourse of ZFC is a set. If we allow classes on top of ZFC, like the case of NBG or MK, then here you can speak of sets as special case of classes, and in these theories sets can be defined as classes that are elements of classes. However, this  capability of being an element of a class is connected to a concept related to size comparisons between classes, i.e. their cardinality. One version of NBG\MK depicts sets as classes that are strictly smaller than the class of all elements, i.e. the universe, in which case we'll have global choice. You can also use the Hierarchy notion to define sets in a class theory as sets being classes that are sub-classes of a stage in the cumulative Hierarchy [defined by Von Neumann]. Of course this emphasizes the well founded structure of sets as an additional feature next to them being collectible as elements of a classes, as well as transferring to them the size notions of the relevant class theory related to enabling collections of being elements.


Why a decidable logic is considered trivial?

Question: I was reading some notes on propositional logic and I stumbled upon these related remarks:
"One way of measuring the strength of a logic is to ask whether it is decidable"
"One of the things we might mean when we say that a logic is trivial is that it is decidable"
"A logic L is decidable iff we could in principle
program a computer to tell us of any given sentence of L in a
finite period of time whether or not that sentence is a logical
truth according to L"
"If logic is decidable then we could
just grind out the consequences of any claim in an unthinking
manner; in that sense, the logic took us nowhere new"
This is not the first time I read something like that, I often find propositional logic denoted as just a "toy".
Seems that this is all related, but I still don't have a grasp on the reasons.
Comment: I sure hope he doesn't think that finding a polytime (or any tractable) algorithm is trivial.
Comment: I'm not really sure how a more typical semidecidable proof theory takes us "somewhere new". We can "grind out the consequences of any claim in an unthinking manner" regardless of whether the logic is decidable or not.
Comment: In fact, the decision problem for classical propositional logic is NP-complete; and according to an answer to a question I posted over on CS stack exchange, the decision problem for intuitionistic propositional logic is PSPACE-complete.
Comment: Note well that the term "trivial" is not well defined but heavily context dependent.
Answer: Well, I certainly wouldn't say that a decidable logical system is trivial (well okay, it might be trivial, but not for that reason alone). The book The classical decision problem contains a lot of information about decidable logical systems, as does this survey paper, and I think it won't be hard to find a bunch which you find plenty interesting. So I'd consider the claim "decidability$\implies$triviality" to be unjustified colorful language.
However:

In light of Godel's incompleteness theorem, any "sufficiently rich" logical system is undecidable. So conversely, knowing that a logical system is decidable does put a limit on its strength; certainly it can't be used to "implement" all of mathematics, or even arithmetic.
Second, propositional logic in particular is indeed often considered just a toy, but not because it's decidable - rather, because it's (arguably) uninteresting. The semantics for (classical) propositional logic simply isn't very rich (just maps from the set of propositional atoms to $\{\top,\perp\}$) compared with other logics (e.g. first-order structures). This is related to the previous bulletpoint: any logic with a "sufficiently complicated" semantics will have to be undecidable.
Comment: Seeing the title, I wondered if for this was maybe the author was suggesting that, due to GIT you mentioned, a "sufficiently rich" system is decidable only if it is inconsistent, and that is the sense in which he meant trivial.


Is there a formula for $(x+y+z)^n$?

Question: We have that $$(x+y)^n=\sum_{k=0}^n\binom{n}{k}x^ky^{n-k},$$
but is there such a formula for $(x+y+z)^n$ ?
Comment: https://en.wikipedia.org/wiki/Multinomial_theorem
Comment: Try to withdraw yourself, replacing y + z = t
Comment: Also: https://math.stackexchange.com/q/1008703, https://math.stackexchange.com/q/74362, https://math.stackexchange.com/q/837346 – all found quickly with [Apporach0](https://approach0.xyz/search/?q=%24(x%2By%2Bz)%5En%24&p=3#) (but who cares)
Answer: $$(x+y+z)^n=([x+y]+z)^n=\sum_{k=0}^n\binom{n}{k}(x+y)^kz^{n-k}=\sum_{k=0}^n\binom nk\left[\sum_{j=0}^k\binom{k}{j}x^jy^{k-j}\right]z^{n-k}$$
Answer: What you are looking for is the multinomial theorem.
In your case (3 variables), a bit of combinatronics yields:
$$
(x+y+z)^n=\sum_{k+l+m=n} \frac{n!}{k!l!m!}x^ky^lz^m
$$
Answer: There is::
$$(x+y+z)^n= \!\!\sum_{\substack{(i,j,k)\in\mathbf N^3\\i+j+k=n}}\!\frac{n!}{i!\,j!\,k!} x^i y^j z^k.$$
It can be extended to sums of more than $3$ terms (multinomial formula):
$$(x_1+x_2+\dots+x_r)^n= \!\!\sum_{\substack{(i_1,i_2,\dots, i_r)\in\mathbf N^r\\i_1+i_2+\dots+i_r=n}}\!\frac{n!}{i_1!\,i_2!\,\dotsm i_r!}\, x_1^{i_1} x_2^{i_2}\dotsm \,x_r^{i_r}.$$
Comment: Where is the difference to Bill's answer https://math.stackexchange.com/a/2773339/42969 above?
Comment: Sorry, I didn't look at the comments. You're right – none, except the variables exponents names. I'll remove it in a moment.

Is there a formula for $(x+y+z)^n$?


How to set selected option on choiceType sonata admin bundle

Question: setting default/ selected option for choice field in symfony3 sonata admin bundle?
For example :
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * @inheritdoc
 */
public function configureFormFields(FormMapper $formMapper) {
  parent::configureFormFields($formMapper);

  $formMapper->add('type', ChoiceType::class, [
    'label' => 'config.label_type',
    'choices' => [
      'config.label_permanent' => 'permanent',
      'config.label_automatic' => 'automatic',
      'config.label_temporary' => 'temporary'
    ],
    'required' => false
  ]);
}

How to make the _permanent_ as selected value ?
This post doesn't help me out
setting default value in symfony2 sonata admin bundle
Answer: You can try with something like this:
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;

/**
 * @inheritdoc
 */
public function configureFormFields(FormMapper $formMapper) {
  parent::configureFormFields($formMapper);

  $subject = $this->getSubject();
   if (null === $subject->getId()) {
     $subject->setType('permanent');
   }

  $formMapper->add('type', ChoiceType::class, [
    'label' => 'config.label_type',
    'choices' => [
      'config.label_permanent' => 'permanent',
      'config.label_automatic' => 'automatic',
      'config.label_temporary' => 'temporary'
    ],
    'required' => false
  ]);
}

Comment: Yes, thanks mate :) . just one correction I have made that,
_$this->admin->getSubject();_  should be **$this->getSubject();**


AIC Model Fitting - Multiple Models

Question: I have many predictor variables (100+) and many outcome variables (10+). I am attempting to optimise which predictor variables to use when modelling my outcome variables. I am using R for the analysis and the outcome variables must be modeled separately using the glm function.
My issue is that the GLMs should all use the same predictor variables, and so when I am choosing which variables to use, I have to take all models into consideration and not just one. Since there are so many predictor variables, I am using backward selection for simplicity. If I were optimising a single model, I would minimise the AIC. However, since I have more than one model, I can't minimise the AIC for just one of them as the AIC for the others might be really high.
My question is this: When optimising more than one model, what value should I minimise at each iteration?
I believe I read somewhere that you are to take the sum of the AICs, but I can't find where I read that (sources would be incredibly helpful). I have a niggling feeling however that it might be beneficial to minimise the product of the AICs as that would reduce influence of any outlying values (this boils down to minimising the arithmetic vs geometric mean)
P.S. If anyone can suggest a different information criterion (such as BIC, etc.), how to use it in this case and why it is superior I would be more than happy to have the feedback.
Comment: @Cagdas I mentioned that independence requirement already; in the absence of independence the sum would generally not be suitable.
Comment: For independent data sets adding would be the correct way of getting the overall AIC of the collection of models.
Comment: @Glen_b In my opinion the output variables should be independent. I think this requirement is not satisfied by definition.
Comment: @Glen_b You said independent data sets. I am not sure what that even means. If the output variables are independent then the multivariate distribution will factor and then the log likelihood can be written as sum however summing AICs will mean 2k component will be summed several times as well which I think is not correct. We just need to add 2k only once on top of the sum of negative log likelihoods from the marginals.
Comment: Another way to do it, would be to perform some kind reduction technique on the predictors (e.g. factor analysis), or perhaps use an PLS regression.  You'd get to control how much of the original variation you want to keep, and it'd solve your uniformity issue, as you can simply keep the same factors across your models. The modeling choice depends somewhat on your substantive setting, as with inferential analysis factors may pose problems with interpretation. Alternatively, you could use the mean change in adjusted R² across all models for each variable as a criterion.
Comment: @Cagdas yes that was poor word choice; the intent was that adding AICs makes sense if you have separate models for several sets of variables that are independent.
Comment: @CagdasOzgenc, if you restrict the coefficients on variable $i$ to be the same in all equations (all dependent variables), for each $i=1,...,k$ then the penalty of $2k$ for the system makes sense. But if you allow the coefficients to differ across equations, why would you not add $2k$ for each equation?
Comment: What is your goal and do you need a single final model? If your goal is prediction and you do not need a single final model, then model averaging using AIC based weights would be one option. Is there a reason for not using a multivariate (i.e. with an 10+ dimensional outcome vector) model? That would even allow you to have a single AIC, would it not?
Comment: @RichardHardy Yes you are correct. Probably I didn't understand the problem well.
Answer: A  stepwise procedure using AIC is a very bad idea as it is equivalent to variable selection/elimination based on a p-value.
A much better method is using expert knowledge to choose variables that you know should be included or excluded, paying careful attention to possible confounders and mediators, in conjunction with a shrinkage method such as LASSO.
Comment: @Maxim.K it may be daunting, but an effort should still be made.
Comment: If you work in an academic setting, and are making inferences, this might be doable in practice. If you work as a business analyst (and don't have weeks to develop just one aspect of your analysis), then this is a highly impractical suggestion. Also, in predictive modeling you wouldn't be concerned as much with this kind of selection process.
Comment: @Maxim.K I don't like to make assumptions about how much time the OP has.
Comment: That is true, but it can be quite a daunting task to make careful selections among hundreds of variables.
Comment: I never said anything about the OP. I stated that there are different analytical situations, and in some of those variable selection on substantive grounds is not practically feasible. In these situations one is forced to make model-driven selections. And the OP is about model-driven selection, as undesirable as it may be, at least I read it that way.

AIC Model Fitting - Multiple Models


Can lines that are not parallel or perpendicular to each other fill up $\mathbb{R}^3$?

Question: As title says, can a union of lines that are not paralell or perpendicular to each other be $\mathbb{R}^3$? The number of lines does not matter. It may be countable or uncountable.
Comment: What do you mean when you say "fill up"?
Comment: It may **not** be countable.
Comment: @Euclid: Your original -- perhaps unclear -- question appears to have been adequately answered by (another) Arthur below.  To preserve this answer I have _reverted_ the question back to its previous version.  Feel free to ask your indended question as a new question.  (Incidentally, now by "intersecting" to you mean just intersecting, or _orthogonal_ and intersecting?  Be careful when phrasing your next question.  Cheers!)
Comment: union, I am saying. Edited my question.
Comment: OK, so what about possibility of union being $\mathbb{R}^3$?
Comment: Does 'perpendicular' imply that the lines intersect? Or does it mean perpendicular _after translation_?
Comment: I meant intersect. Sorry for causing confusion.
Comment: Can anyone provide vector calculus reasoning?
Answer: There is an injection from the set of points in $\Bbb R^3$ to the set of directions contained in the (open) first octant, for instance, via space-filling curves. (Fill the space with a curve, this gives a bijection from $\Bbb R^3$ to $\Bbb R$. Now inject that real line into the space $\{(\theta, \phi) | 0 < \theta, \phi < \pi/2\}$, consisting of directions for the lines in spherical coordinates.)
No two such directions are orthogonal, and every point gets a line through it with a unique direction, so it turns out you can fill the space with lines neither parallel nor perpendicular.


How do I fix an uncaught TypeError?

Question: I am using Drupal 8.1.8. It is giving me many JavaScript errors.
Uncaught TypeError: Cannot read property 'permissionsHash' of undefined
Uncaught TypeError: Cannot set property 'StateModel' of undefined
Uncaught TypeError: Cannot set property 'AuralView' of undefined
Uncaught TypeError: Cannot set property 'KeyboardView' of undefined
Uncaught TypeError: Cannot set property 'RegionView' of undefined
Uncaught TypeError: Cannot set property 'VisualView' of undefined
Uncaught TypeError: Cannot read property 'uid' of undefined
Uncaught TypeError: Cannot read property 'currentPath' of undefined
Uncaught TypeError: Cannot read property 'currentPathIsAdmin' of undefined
Uncaught TypeError: Cannot read property 'url' of undefined
Uncaught TypeError: Cannot read property 'currentQuery' of undefined

There is no error in my local copy, but it happen when I uploaded in live hosting.
How can I fix this?
Comment: um... lack of information. And should we consider DA a debug service provider?
Comment: What more information I need to provide ?
Comment: Can you try to type `drupalSettings` in browser console to see what's the data contained in the object?
Comment: Just dump one, here is the output:
Object {}
__proto__:Object
__defineGetter__:__defineGetter__()
__defineSetter__:__defineSetter__()
__lookupGetter__:__lookupGetter__()
__lookupSetter__:__lookupSetter__()
constructor:Object()
hasOwnProperty:hasOwnProperty()
isPrototypeOf:isPrototypeOf()
propertyIsEnumerable:propertyIsEnumerable()
toLocaleString:toLocaleString()
toString:toString()
valueOf:valueOf()
get __proto__:__proto__()
set __proto__:__proto__()
Comment: I can't see it, can you post in the question?
Comment: Can't upload as image. But i don't see the drupalSettings.user object there  and there is interesting thing is that, in my local copy there is not error. but when i uploaded in live hosting, its giving the error
You can see dump and error here: http://www.courseindex.com/
Comment: I found the reason, `
Comment: SOLUTION DEC 2017: I was searching for the answer to this issue, and my resolutiong was, in fact, just my `` (at the bottom of the ``) had a `` around it. When i moved it outside the `` wrapper so it was a direct child of the `` tag, the errors were gone!
Answer: All the properties can be searched and found from the code in Drupal core. And they seems to be the properties of drupalSettings object in JS.
This object is initialised in core/misc/drupalSettingsLoader.js.
(function () {

  'use strict';

  // Use direct child elements to harden against XSS exploits when CSP is on.
  var settingsElement = document.querySelector('head > script[type="application/json"][data-drupal-selector="drupal-settings-json"], body > script[type="application/json"][data-drupal-selector="drupal-settings-json"]');

  ....

This code explained that the drupalSettings is contained in

How do I fix an uncaught TypeError?


Fixing keyboard stand

Question: We've got Yamaha PSR-E453 keyboard. It allows mounting to a stand with screws. However, there are very few keyboard stands available that support this. Most keyboard stands are universal and you simply lay the keyboard on it, probably without mounting.
As our keyboard is placed in the children room, I'd prefer to fix it to the stand. Is this unusual? How am I supposed to fix a universal stand to the keyboard in order to prevent it from falling? If I drill holes to a stand, I would loose the possibility to adjust the keyboard height...
Answer: Get a stand with four legs, in two pairs, one left, one right. They're far more stable - I will use only them for gigs, as the X stands aren't that stable. Put the keyboard against the wall, and there's little chance of it being pulled over or off the stand.
Comment: @BrianTHOMAS - Gear4music sells the stands I use, spring-loaded legs, height adjustable, solid. Could even screw the k'bd. from underneath, but not necessary.
Comment: e,g, Ikea sell trestle legs strong enough to support a worktop. These would make a rock-solid keyboard stand.

Fixing keyboard stand


$x$ is equal to at least $51$ of $a_1,\frac{a_1+a_2}{2},\ldots,\frac{a_1+a_2+\ldots+a_{100}}{100}$. Prove that $2$ of $a_1,\ldots,a_{100}$ are equal.

Question:
If $x$ is equal to at least $51$ number of the array $a_1, \frac{a_1+a_2}{2},\ldots,\frac{a_1+a_2+\ldots+a_{100}}{100}$, prove that $2$ numbers of the array $a_1,a_2\ldots,a_{100}$ are equal.

That's the way the problem is originally stated. It doesn't tell me whether at least or exactly $2$ numbers of the array $a_1,a_2\ldots,a_{100}$ are equal.
I've thought of a way to define the problem in a different way:

If $n_1,n_2,\ldots,n_{100}$ is an array of distinct natural numbers that belong to the interval $[1\:;100]$ and $k\in\mathbb N$, $k\le50$ and
  $\begin{cases}n_1x=a_1+a_2\ldots+a_{n_1}\\n_2x=a_1+a_2\ldots+a_{n_2}\\\ldots\\n_{50+k}x=a_1+a_2\ldots+a_{n_{50+k}}\end{cases}$, prove that $2$ numbers of the array $a_1,a_2\ldots,a_{100}$ are equal.

I have no idea at the moment how we could come up with a proof that $2$ numbers of the array $a_1,a_2\ldots,a_{100}$ are equal. Some ideas would be great. Thanks.
Comment: Hint: if 51 of the numbers are equal, then two consecutive ones must be equal. That seems as if it might lead somewhere, and it uses the pigeonhole principle, which seems likely to be where this problem arises.
Comment: In problems where you have to prove that at least some number are equal, pigeonhole principle is a great tool.

BTW, yes, it means "at least 2." If it didn't mean at least 2, then consider that all of the terms are equal (since the problem says at least 51), then $a_1=a_2=a_3=\dots=a_{100}$, so more than $2$ are equal. If it said "exactly 2," we could stop there and say that it is not true.
Answer: Let $I$ be the set of all $0 \le n \le 100$ such that $x_1 + \cdots + x_n = nx$.
Note that $0$ does belong to $I$, and so do the $51$ (or more) other values stated in the hypothesis, so $|I| \ge 52$.
Since $I$ is a subset of $\{0, \ldots, 100\}$ with size at least $52$, it must contain at least two pairs of consecutive elements.  In other words, there are distinct $m,n$ such that $m, m+1\in I$ and $n, n+1 \in I$.  (One way to see this cleanly is to consider the spacings between the first $52$ elements: there are $51$ spaces totaling at most $100$, so at least two of the spacings must be $1$ rather than $\ge 2$.)
Notice that whenever $r,r+1 \in I$ we have that $a_{r+1} = x$ (since you're confused you may want to double-check that this holds for $r=0$, but it really is the same calculation as any $r$).  Thus with $m$ and $n$ chosen as above, we have $a_{m+1} = a_{n+1} = x$.
Comment: @mathh This is extremely standard notation.  The sum from $n=1$ to $0$ is the empty sum, namely $0$.
Comment: Yes, my mistake. (But your answer could do with some clarification.)
Comment: But I haven't defined $a_0$, so why have you defined $n$ as $0\le n\le 100$? If $n=0$, then what is $x_1+x_2+\ldots+x_n$ equal to? The indexes are all greater than $0$. I don't understand this.
Comment: I still don't understand why you've shown that $n$ can be equal to $0$. The set $a_1,\frac{a_1+a_2}{2},\ldots,\frac{a_1+a_2+\ldots+a_{100}}{100}$ clearly shows $n$ is $1,2,\ldots,100$. What use does it make to have that $n$ is $0$ if it clearly can't be in this case. I don't understand this.
Comment: @mathh Clearly, when $n=0$ the equation $x_1+\cdots+x_n = nx$ holds since both sides are equal to $0$.  Therefore, $0$ is always in the set $I$.
Answer: Let
$$A=\{\,k\in\mathbb N_0\mid k\le 100,a_1+\ldots+a_k=kx\,\}.$$
Then $A$ contains not only the 51 given indices, but trivially also $0\in A$, i.e. $|A|\ge 52$.
Let $B= (\mathbb N\setminus A)\cap (A+1)$. Then $A\cap B=\emptyset$ and $A\cup B\subseteq \{0,1,\ldots,101\}$ imply $$\tag1|A|+|B|\le 102.$$ For each  $k\in (A+1)\cap A$ we have $1\le k\le 100$ and $$ a_k=(a_1+\ldots+a_k)-(a_1+\ldots a_{k-1})=kx-(k-1)x=x.$$
Now
$$(A+1)\cap A=(A+1)\setminus(\mathbb N\setminus A)=(A+1)\setminus B $$
and $$ |(A+1)\setminus B|\ge |A+1|-|B|=|A|-|B|\ge 2|A|-102\ge 2$$
Shows that there are at least two indices $k$ with $a_k=x$.
Comment: It's  not like Hagen made it up. That is the proper notation.
Comment: How can you define that $k$ can be equal to $0$? Isn't it apparent that it arranges between $1$ and $100$? Since I haven't defined the number $a_0$. I don't understand this.
Comment: What does $|A|$ define? Cardinality of the set $A$?
Comment: I've added my own solution which I believe works if you don't want to decipher his comment.

$|A|$ does indeed denote the cardinality of the set.
Answer: This should work
Let $b_i$ denote the $i$th term of the sequence.
By pigeonhole principle, at least two consecutive terms $b_n, b_{n+1}$ are equal.
If $n$ is even, then necessarily at least one other pair of consecutive terms are equal. If $b_k, b_{k+1}$ are equal, then it can be shown that $a_{n+1} = a_{k+1}$
If $n$ is odd, then it can be that $b_n, b_{n+1}$ is the only pair. If it wasn't, then we can conclude similarly as above. So consider $b_n, b_{n+1}$ being the only pair. $b_1 = a_1$ must be one of the terms equal to $x$ (the terms equal are $a_1 = a_3 = \dots = a_n = a_{n+1} = a_{n+3} = \dots = a_{100}$). Furthermore, $\frac{a_1 + a_2 + a_3 + \dots + a_n}{n} = \frac{a_1 + a_2 + a_3 + \dots + a_{n+1}}{n+1}$, so $a_{n+1} = \frac{a_1+a_2+a_3+\dots+a_n}{n} = x$. Thus, $a_{n+1} = a_1$. $\blacksquare$
Btw, do you know where this problem is from? Seems like a 1990s USAMO problem.
Comment: Although it is quite obvious that there must be two consecutive and equal values $b_i$, it is not so obvious to make this an instance of the pigeonhole principle. If you think of it, here is a way: partition $\{1,2,\ldots,100\}$ into $50$ disjoint sets $\{2i-1,2i\}$, then one pair must contain two of the indices$~n$ with $b_n=x$ by the pigeonhole principle. But this means you get the reduction to the case $n$ odd for free. (One must still do all of the reasoning above for that case.)
Comment: This looks like the best answer to me.
Comment: I've searched for it on the website https://www.artofproblemsolving.com/Wiki/index.php/USAMO_Problems_and_Solutions
But it doesn't seem to contain this problem (I mean the 1990th year). Oh, you meant the 1990s, not the 1990th.
Comment: Do you really need to treat $n$ even and $n$ odd as two separate cases?
Answer: One can say slightly more, not only two of those $a_i$ are equal, actually two of them equal $x$.
Clearly if two consecutive running averages are equal to $x$, then the term added in the second running average was equal to $x$. One obviously cannot select $51$ out of $100$ running averages without this happening at least once (every selected average except the last would block its successor from selection, which gives $50\times2+1$ selected or blocked averages, one too many). If it actually happens more than once, then we have got our two instances of $a_i=x$. But if one wants it to happen just once, then  by a similar argument, every one of the $100$ running averages is either selected or the successor of a selected average, the two conditions being satisfied simultaneously just once. But that means the very first running average was selected, making $a_1=x$, which together with the instance $a_i=x$ for the index $i$ that was both selected and the successor of a selected index gives our two instances.
One can avoid the case distinction by adding a running average $0$ declared to be equal to $x$ (with which the argument "two consecutive averages equal to $x$ implies the second $a_i=x$" remains valid), and argue for at least two pairs of consecutive chosen averages. This is essentially the answer by Eric Wong. I just wanted to show that one arrives at the conclusion also using only rather fantasy-less reasoning.


dimension of linear transformations from $V_5$ to $V_{11}$

Question: For each integer $j \ge 1$, let $V_j$ denote the real vector space of all polynomials in two variables of degree strictly less than $j$.What can be said about the dimension of the space of all linear maps from $V_5$ to $V_{11}$ whose kernel contains $V_3$
and whose image is contained in $V_7$?
I think, applying the rank nullity theorem, the rank of such a linear transformation should be less than or equal to $9$. But does rank equal the dimension of such linear maps? Does defining any sort of functional help here? Thanks beforehand.
Answer: Since the image is contained in $V_7$, that what you really want is the dimension of the space of all linear transformations from $V_5$ to $V_7$ whose kernel contains $V_3$. Besides, since $(1,x,y,x^2,xy,y^2,x^3,\ldots,y^4)$ is a basis of $V_5$ and since $(1,x,y,x^2,xy,y^2)$ is a basis of $V_3$, this is the same thing as the dimension of the space of all linear transformations from$$\operatorname{span}\bigl(\{x^3,x^2y,xy^2,y^3,x^4,x^3y,x^2y^2,xy^3,y^4\}\bigr)$$(which has dimension $9$) into $V_7$ (which has dimension $21$). Therefore, the answer is $21^9$.
Comment: thanks, but, two questions: how come $V_3$ is the kernel of transformation from $\text{span}(\{x^3,x^4\})$ into $V_7$ and, by the way, you missed that the spaces are polynomials in two variables, not one!
Comment: I've edited my answer. I hope that everything is correct now.
Comment: @JoséCarlosSantos V_7 has dimension 28


How do I find $\lim_{x \to a}\frac{f(x)}{g(x)}$ when $\lim_{x \to a} [3f(x)+g(x)]=1$ and$\lim_{x \to a} [2f(x)-3g(x)]=8$?

Question: I had to solve the next exercise:

If $f,g:\mathbb{R}\to\mathbb{R}$ are functions that satisfy $$\lim_{x \to a} [3f(x)+g(x)]=1 \qquad\text{and}\qquad \lim_{x \to a} [2f(x)-3g(x)]=8,$$ then find the limit $\lim\limits_{x \to a}\frac{f(x)}{g(x)}.$

This is what I did:
Let $\lim_{x \to a}f(x)=\ell$ and $\lim_{x \to a}g(x)=t$. Using laws of limits I wrote $3\ell+t=1$ and $2\ell-3t=8$. Then $t=1-3\ell \implies 2\ell-3(1-3\ell)=8$ After some algebraic manipulations I got that $\ell=1$. Then $3(1)+t=1 \implies t=-2$. Finally, since $\lim_{x \to a}g(x)\neq 0$, then $$\lim_{x \to a}(\frac{f(x)}{g(x)})=  \frac{\lim_{x \to a}{f(x)}}{\lim_{x \to a}{g(x)}}=\frac{1}{-2}=\frac{-1}{2}.$$
Is this correct?
Answer: You are starting with that assumption that $f$ and $g$ have limits at $a$ which is not legitimate.
Multiply the first equation by $2$ , the second on by $3$  and subtract one from the other. You will see that $g$ has  a limit as $x \to a$. Now use the first equation to show that $f$ has  a limit as $x \to a$. Now you can proceed the way you have done.
Answer: Another way is to see that :
$$\frac{f(x)}{g(x)} = \frac{3 \left(3f(x)+g(x)\right) + (2f(x)-3g(x))}{2\left(3f(x)+g(x)\right) - 3\left(2f(x)-3g(x)\right)}$$
Therefore the limit when $x$ tends to $a$ is equal to
$$\frac{3 \times 1 + 8}{2 \times 1 - 3 \times 8} = - \frac{1}{2}$$


Browser caching

Question: I am developing a web site which uses lot of images.I would like to make all images are to be stored in browser's cache till some specified time.Now it is stored in browser's cache.However if we refresh the page in browser it is making request to server for particular resource.Server responds with 304 code(NOT MODIFIED).I want to avoid that request also.I am developing application in jsp/servlet.Images wants to be stored in browser for particular time.If the time expires it can send request to server for resources.
Is there any possiblity to implement this?Can anyone provide me help on this.
Thanks.
Answer: There's just no way in which you, working server-side, can stop the browser from checking about things it's caching when it's explicitly being asked to refresh a page -- it's just totally out of your control. You may (and should) claim the cache's validity expires in 2099 or later, but you just cannot force the browse to trust that (or any other) expiration date, period -- programmers who develop browsers have their ideas about how best to serve their customers, and you just can't force their hand.
Answer: Theoretically, if the browser had something like Gears installed, then you might be able to store them client-side, and load them with JavaScript instead of plain vanilla HTTP - first checking the local data store, and then going back to your server if the image wasn't found.
But I'm not sure if you can store binary data or images with Gears, et. al.
Answer: If using Apache, you could use .htaccess files to tweak cache and expiration headers for different folders or file types.
http://www.askapache.com/2006/htaccess/speed-up-sites-with-htaccess-caching.html
Answer: I'm pretty sure an explicit refresh in the browser will cause it to reload all the resources, ignorning cache-expiration settings.

Browser caching


Using 2FA for password reset

Question: My application uses Asp.Net Identity and sends a Two Factor code to my Auth app on login.  This is pretty standard (as there lots of examples on the net) and uses the SendCode() method.  My understanding is that the 'magic' is done by this line:
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
  View("Error");
}

My requirement is to ensure the user goes through the same process of 2FA when they want to change their password after they have logged in.
My issue is that when the code to send the 2FA code is executed:
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
  View("Error");
}

I receive the error 'UserID not found':

Server Error in '/MSPortal' Application.
UserId not found.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: UserId not found.

Source Error:

Line 555:
Line 556:            // Generate the token and send it
Line 557:            if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
Line 558:            {
Line 559:                return View("Error");

I know SendTwoFactorCodeAsync() calls GetVerifiedUserIdAsync() but my understanding is that the user is verified now that I have already logged in using 2FA.
Does anyone know why I would be getting this error?
Thanks.
Comment: [**Do not post images of code or errors!**](https://meta.stackoverflow.com/q/303812/995714) Images and screenshots can be a nice addition to a post, but please make sure the post is still clear and useful without them. If you post images of code or error messages make sure you also copy and paste or type the actual code/message into the post directly.
Comment: Thanks for the heads up Rob.
Answer: I've worked around this by overriding SendTwoFactorCodeAsync() in IdentityConfig.cs.  In this override, I first call GetVerifiedUserIdAsync() as per usual but then if that is 0 I get the User's ID from the Current HttpContext.
I am not stating this is the best way but it's what I have done thus far and its got me moving ahead in my aim of having 2FA for login, change password and forgot password.
The code (likely to go through some refactoring if I get feedback) is:
public override async Task<bool> SendTwoFactorCodeAsync(string provider)
{
    int userId = 0;
    try
    {
        userId = await GetVerifiedUserIdAsync();
        if (userId == 0)
        {
            userId = Convert.ToInt32(HttpContext.Current.User.Identity.GetUserId());
        }

        if (userId == 0)
            return false;
    }
    catch
    {
        return false;
    }

    var token = await UserManager.GenerateTwoFactorTokenAsync(userId, provider);

    // See IdentityConfig.cs to plug in Email/SMS services to actually send the code
    await UserManager.NotifyTwoFactorTokenAsync(userId, provider, token);
    return true;

    //return base.SendTwoFactorCodeAsync(provider);
}

Using 2FA for password reset


Quotient ring of $\Bbb Z[x]$ by an irreducible polynomial is a PID

Question: I don't know what can I do with this problem.

How can I prove that $\mathbb{Z}[x]/(x^{3}-4x+2)$ is PID?
Comment: The first thing I would do is check whether the polynomial is irreducible. Perhaps with Eisenstien.
Comment: That easily settles that it's a domain, but the trick is the "principal" part. Maybe there is an obvious Dedekind-Hasse norm? What have you learned about PID's recently?
Comment: $x^{3}-4x+2$ is irreducible because it has no root in $\mathbb{Z}$.
Comment: I know that if $R$ is Dedekind domain and UFD, then $R$ is a PID. But I can not prove non of them.
Answer: Let $K=\mathbb{Q}(\alpha)$, where $\alpha$ is a root of $f(x)=x^3-4x+2$. Then $f(x)$ has discriminant $-148$, so that $disc(1,\alpha,\alpha^2)=148=2^2\cdot 37$. Since $disc(\mathcal{O}_K)$ differs from $disc(1,\alpha,\alpha^2)$ only by a square, it follows
$disc(\mathcal{O}_K)=37$, or $disc(\mathcal{O}_K)=148$.
Consider the ideal $P=(2,\alpha)$. Then $P^3=(2)(4,2\alpha,\alpha^2,\alpha-1)=(2)$, since the second ideal contains $1$ and is the whole ring. Hence $2$ ramifies, and this is equivalent with $2\mid disc(\mathcal{O}_K)$, so that $disc(\mathcal{O}_K)=disc(1,\alpha,\alpha^2)$. It follows that  $\mathcal{O}_K=\mathbb{Z}[\alpha]\simeq \mathbb{Z}[x]/(x^3-4x+2)$, and this is a Dedekind ring.
Then Minkowski's bound is given by $3!\sqrt{148}/3^3\simeq 2.703$, which
shows that every class in the class group is represented by an ideal whose norm at most $2$, where it is used that $f(x)$ has three real roots. Thus every ideal class is represented either by id or by $P$. But $P$ is the unique ideal with norm $2$, and it is easy to see that it is principal (use that $N(\alpha)=-2$). It follows that the ring is a PID.


Server slow in some domains

Question: I have a application developed using .NET and running on a IIS server. The application is a blog network, that has many different domains. When we activate one domain that uses a differente domain alias the server stay really slow. We think that the application can not handle this alias. How can I analyze this on IIS? Someone has this problem too? Thanks!
Answer: I think it is caused by disk space. You can try to check your task manager. How is the traffic?

Server slow in some domains


org.jetbrains.skiko.LibraryLoadException: Cannot find libskiko-macos-arm64.dylib.sha256, proper native dependency missing

Question: I try to compile https://github.com/CuriousNikhil/k5-compose in IntelliJ (Apple-Silicon) on an M1 MacbookPro, I got the below error
Caused by: org.jetbrains.skiko.LibraryLoadException: Cannot find libskiko-macos-arm64.dylib.sha256, proper native dependency missing.
    at org.jetbrains.skiko.Library.load(Library.kt:71)
    at org.jetbrains.skiko.HardwareLayer.<clinit>(HardwareLayer.kt:10)

How can I solve this issue?
Answer: In the build.gradle.kts of the project, change     implementation(compose.desktop.currentOs) to implementation(compose.desktop.macos_arm64)
Comment: Thanks - I was building a jar on arch linux and deploying to a raspberry pi and this was my problem. Compose on a pi ftw.
Answer: While I found the accepted answer to work:

Changing
implementation(compose.desktop.currentOs)
to
implementation(compose.desktop.macos_arm64)

The documentation seems to indicate that you should just update the version of the wizard:

The Compose plugin version used in the wizard above might not be the latest. Update to the latest plugin version by editing the build.gradle.kts file and updating the version information as shown below. For the latest versions, see the latest versions site and the Kotlin site.

plugins {
    kotlin("jvm") version "1.7.20"
    id("org.jetbrains.compose") version "1.2.2"
}

Which also works, and I think should be preferred.
Answer: I had a similar error, but for Linux.
Cannot find libskiko-linux-x64.so.sha256, proper native dependency missing.

Updating everything to the latest version and replacing currentOs with linux_x64 made no difference, still the same error.
After explicitly adding a dependency on skiko in build.gradle.kts, it worked fine.
implementation("org.jetbrains.skiko:skiko-awt-runtime-linux-x64:0.7.69")

Answer: I looked into the documentation of Skiko itself and found out that they suggest manually importing it the following way (the version may differ):
val osName = System.getProperty("os.name")
    val targetOs = when {
        osName == "Mac OS X" -> "macos"
        osName.startsWith("Win") -> "windows"
        osName.startsWith("Linux") -> "linux"
        else -> error("Unsupported OS: $osName")
    }

    val targetArch = when (val osArch = System.getProperty("os.arch")) {
        "x86_64", "amd64" -> "x64"
        "aarch64" -> "arm64"
        else -> error("Unsupported arch: $osArch")
    }

    val version = "0.7.70" // or any more recent version
    val target = "${targetOs}-${targetArch}"

    sourceSets {
        val jvmMain by getting {
            dependencies {
                implementation("org.jetbrains.skiko:skiko-awt-runtime-$target:$version")
                implementation(compose.desktop.currentOs)
           }
      }
}

I simply put this into the following (in the build.gradle.kts):
kotlin {}
but I think this also works when you just put it outside of it. But the implementation has to be in the dependencies {} of course . This solution solved the problem perfectly for me. I also tried to change implementation(compose.desktop.currentOs) to implementation(compose.desktop.macos_arm64) but it didn't fix it for me.
Answer: I had a same error today on Intel x64 iMac, and solved by upgrading plugins version.
kotlin("jvm") from 1.5.31 to 1.6.10 and id("org.jetbrains.compose") from 1.0.0 to 1.1.1
FYI, it worked fine a month ago.