Assumptions for adjusted R-squared

Question: Adjusted R-squared is defined as
r2_adj = 1-[((1-r2)(n-1))/(n-k-1)]
I have read at many places that adjusted R-squared is strictly less than R-squared, because k>0 and R-squared <=1.
But I was just thinking upon this formula and it seems that adjusted R-squared will be greater than R-squared if somehow my number of data points  n is less than number of independent variables k.
Is this an basic assumption too that n should always be greater than k+1?
Comment: When you have fewer data points than variables, what is the value of the *unadjusted* $R^2$??
Comment: Its not dependent on variables or data points right? Lets assume R2 is 0, i.e. model is always predicting mean for all the instances.
Answer: Note first that there are many different R-squared estimators. For an overview, see the references below. Disclaimer: I am the author of the third one.
However, all of them indeed require that $p>N$, as otherwise, it is impossible to fit the regression model, in the sense that no unique regression coefficients exist. If you for example try to fit a model with $11$ predictors and $10$ samples, using the lm function in R, it will not provides estimates for two predictors and also no standard errors for any coefficient.
While you technically can get an R-squared from such a model, it is guaranteed to be $1$ and thus meaningless, as will any adjustment of this value.See also the comment by whuber.
You can of course obtain a prediction function for the $p>N$ setting using a different technique, for example, ridge regression. However, all the adjusted R-squared formulas only work for $R^2$ estimates as obtained by ordinary least squared regression. You could fall back to predictive $R^2$ for this case but this estimate something else than adjusted-$R^2$, see my answer to another question: https://stats.stackexchange.com/a/518400/30495
References
$[1]$: Shieh G (2008): Improved shrinkage estimation of squared multiple correlation coefficient and squared cross-validity coefficient. Organizational Research Methods, 11(2): 387-407 (link)
$[2]$: Yin P, Fan X (2001): Estimating $R^2$ shrinkage in multiple regression: A comparison of different analytical methods. The Journal of Experimental Education, 69(2): 203-224 (link)
$[3]$: Karch J (2020): Improving on adjusted R-squared. Collabra: Psychology (2020) 6 (1): 45. (link)
Comment: This just seems to be a misunderstanding in what I meant with it is impossible to fit the regression model. I edited for clarification.
Comment: The problem is the opposite of your characterization: when the rank of the model matrix equals $n,$ there will be a *perfect* fit (and probably many of them), making $R^2=1,$ whence any formula of the form $1 - (1-R^2)*\text{positive constant}$ will give $1$ for its adjusted version. The attempt to divide by $n-k-1$ in the formula is a strong hint that using $R^2$ and attempting to adjust it in such circumstances makes no sense.

Assumptions for adjusted R-squared


UIWebView get user touch on tapping link

Question: I want to perform some action when the user clicks any link on UIWebView. I am doing this for making this work :
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"request - %@", request.URL.absoluteString);
    [webView.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    if(isFirstTimeLoaded)
    {
        [self shoToolbar];
        [self updateButtons];
    }

    return YES;
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    isFirstTimeLoaded = YES;
}

This usually works fine. But it doesn't when UIWebView's first load involves multiple redirection while loading the page. What I want is to fire this condition only when the user intentionally clicks on the link. Not on the url redirection of UIWebView.
Answer: You have to check navigationType
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
    {

        if (navigationType==UIWebViewNavigationTypeLinkClicked) {
            // It was a link
        } else {
           // It wasn't a link
        }

        return YES;
    }

Comment: Stupid I was forgetting about navigationType. Thanks !!


Would the cue ball on top of a rail still be considered legal and playable?

Question: In reference to the image below, the cue ball rested on top of a rail after my opponent attempted a shot. During a different game, I shot the cue ball on top of a rail (to avoid other solid and striped balls) and nearly converted a shot.
Would the cue ball on top of a rail still be considered legal and playable? Would this be considered a scratch?
Answer: If the cue ball is shot and is resting on the rail, it is considered not in play.
According to the United States Professional Pool Players Association Rule 3.b, this occurrence would result in a break foul.

Break fouls include the following:
b. If the cue ball is pocketed or driven off the table it is a foul and the non-breaking >player has cue ball in hand behind the head string (from the "kitchen.")

According to the World Pool Billiard Association, this occurrence is also a foul under rule 6.1 sub rule 8.5

6.1 Cue Ball Scratch or off the Table
If the cue ball is pocketed or driven off the table, the shot is a
  foul. See 8.3 Ball Pocketed and 8.5 Driven off the Table.

8.5 Driven off the Table
A ball is considered driven off the table if it comes to rest other
  than on the playing surface but is not pocketed. A ball is also
  considered driven off the table if it would have been driven off the
  table except for striking an object such as a light fixture, piece of
  chalk or a player which causes it to return to the table. A ball that
  contacts the top of the rail is not considered to have been driven off
  the table if it returns to the playing surface or enters a pocket.
Comment: So, in the circumstances I present above, a cue ball resting on top of a rail is considered not in play whereas using the top of the rail for my shot is in play as long as the cue ball rests on the playing surface.
Comment: You are correct
Answer: As it is often unpleasant to read the intense legal documents that are sports rules, I will put it like this:
The ball has to finish up on the table, or in a pocket, for a shot to be legal.
I once had a pot hit the corner pocket too hard - sending the ball up onto the cushion rail. It raced along said rail before plunging delightfully into the side (middle) pocket. I knew it was OK in snooker, and the TD said it was fine in USA 9 ball too.
Comment: The entirety of rules needed to answer this question consists of a sixteen-word excerpt, which is fewer words than the single sentence in this answer that actually responds to the question.


Image Button to new Activity: Android Studio

Question: I want to link my image to a new activity, I tried multiple of codes and solution online but I am having an error.
public class MainActivity extends AppCompatActivity {
<code>ImageButton myImageButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

   myImageButton  = (ImageButton) findViewById(R.id.APZ);
    myImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intentLoadActivity = new Intent(MainActivity.this,APZ.class);
            startActivity(intentLoadActivity);
        }
    });
}
</code>
}
My problem is the ID I have set in the image is having an error, see the screenshot below:
https://i.stack.imgur.com/IkMC1.jpg
Activity_main.XML code:
<code>    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:text="Astoria Hotels and Resorts"
    android:textStyle="bold"
    android:textSize="25sp"
    />

    <GridLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:rowCount="3"
        android:columnCount="2"
        >

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_row="0"
            android:layout_column="0"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_margin="8dp"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp"
            android:layout_marginTop="25pt"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="center_vertical|center_horizontal">

                <ImageView
                    android:id="@+id/APZ"
                    android:layout_width="123dp"
                    android:layout_height="140dp"
                    app:srcCompat="@drawable/astoria_plaza___project_logo___primary_lockup__small_" />

                <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Astoria Plaza"
                android:textStyle="bold"
                android:textAlignment="center"/>
        </LinearLayout>
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_row="0"
            android:layout_column="1"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_margin="8dp"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp"
            android:layout_marginTop="25pt"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="center_vertical|center_horizontal">

                <ImageView
                    android:id="@+id/imageView4"
                    android:layout_width="123dp"
                    android:layout_height="140dp"
                    app:srcCompat="@drawable/agb_transparent" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Astoria Greenbelt"
                    android:textStyle="bold"
                    android:textAlignment="center"/>
            </LinearLayout>
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_row="1"
            android:layout_column="0"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_margin="8dp"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="center_vertical|center_horizontal">

                <ImageView
                    android:layout_width="123dp"
                    android:layout_height="140dp"
                    app:srcCompat="@drawable/astoria_current_transparent" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Astoria Current"
                    android:textStyle="bold"
                    android:textAlignment="center"/>
            </LinearLayout>
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_row="1"
            android:layout_column="1"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_margin="8dp"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="center_vertical|center_horizontal">

                <ImageView
                    android:layout_width="123dp"
                    android:layout_height="140dp"
                    app:srcCompat="@drawable/ab1_transparent" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Astoria Boracay"
                    android:textStyle="bold"
                    android:textAlignment="center"/>
            </LinearLayout>
        </androidx.cardview.widget.CardView>

        <androidx.cardview.widget.CardView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_row="2"
            android:layout_column="0"
            android:layout_gravity="fill"
            android:layout_rowWeight="1"
            android:layout_columnWeight="1"
            android:layout_margin="8dp"
            app:cardCornerRadius="8dp"
            app:cardElevation="8dp"
            >
            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:gravity="center"
                android:layout_gravity="center_vertical|center_horizontal">

                <ImageView
                    android:layout_width="123dp"
                    android:layout_height="140dp"
                    app:srcCompat="@drawable/abh___transparent" />
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Astoria Bohol"
                    android:textStyle="bold"
                    android:textAlignment="center"/>
            </LinearLayout>
        </androidx.cardview.widget.CardView>

    </GridLayout>

</RelativeLayout>
</code>
Help please thanks!
Comment: share your `R.layout.activity_main` and  do you have another activity named `APZ`?
Comment: I've added my main activity xml codes
Comment: In xml you have ImageView, but in java you are using ImageButton? try using ImageView instead of ImageButton in java
Answer: You are using ImageButton in java. If you want to use it replace ImageView with ImageButton in your layout.xml


$T*T$ Notation and proof

Question: Let $T:H\to H$ be compact where $H$ is a Hilbert space and let $T^*$ be the adjoint operator of $T$. Prove that $T^*T$ is compact and self adjoint and that the eigenvalues of $T^*T$ are nonnegative. Find a compact self adjoint operator $S:H\to H$ such that $S^2=T^*T$
What will be a good approach for this question?
Answer: While there is a lot of context missing from the question, perhaps it is $T^* \circ T$, where $T^*$ is the adjoint of $T$?  That is easily seen to be self-adjoint and with positive eigenvalues: Since $(AB)^*=B^* A^*$ and $A^{**}=A$, we have that $(T^*T)=T^*T^{**}=T^*T$.  Further, since if $T*Tx=\lambda x$ and $x\neq 0$, then $$\lambda = \langle T^*Tx,x \rangle/ \langle x,x \rangle =\langle Tx,Tx \rangle/\langle x,x \rangle,$$ which is the quotient of two non-negative quantities, with non-zero denominator.
Finding the square root also isn't so bad.  Since the operator is self-adjoint, the spectral theorem gives an orthonormal basis of eigenvectors, and we already have that the eigenvalues are non-negative, and thus have real square roots.  Define $Sx$ on an eigenvector $T^*Tx=\lambda x$ by $Sx=\sqrt{\lambda}x$.  Verify that this is compact and self-adjoint.
It's been too long since I've taken functional analysis to recall the relevant facts about compactness, but hopefully this is enough that you can finish things off (by showing $T^*T$ and $S$ are compact).
Comment: @havakok The question itself may not have more to offer, but the place you found it might.  For example, the fact that $H$ is probably a Hilbert space.The question either came from a book (in which case information about the book and the chapter it was in could be relevant) or it came from a homework sheet, in which case information on the class and what you were covering could be relevant.  My answer made several assumptions about things that were not stated explicitly.
Comment: @havakok just because most Hilbert spaces are denoted by $H$ does not mean that most $H$s are used to denote Hilbert spaces. Just as $i,j$ are common indexing variables, they are also both used for $\sqrt{-1}$. Clearly communicating mathematics requires understanding what assumptions you are making and making them explicit. Small technical conditions can make big differences, and you cannot just assume that others will also assume the same unstated assumptions as you.
Comment: @havakok For you to have even been asking the question you asked, there had to have been a reason why you thought convolution was even an option. Perhaps you were dealing with $L^2(X)$ and were defining operators via integration?  And in a question involving adjoints, you didn't even consider that the star could be taking the adjoint.  If I don't assume there was context to explain your confusion, context to suggest that my answer isn't the only reasonable one, then I am left making unflattering assumptions about you. Do you "get" it?

$T*T$ Notation and proof


Is it possible to determine norm of elements?

Question: let R be an integral domain and I be an ideal of R generated by two elements. say I=(x,y)
we already know if there exists an element z in ring of integers such that N(z)=N(I) (right side is a norm of ideal), then I is a principal ideal.
Question : Given only an ideal I.
If we don't want to I is a principal ideal, then How to determine a z is not in ring of integers?
Suppose R is not a PID
Then we can choose two elements p,q such that (p,q) is not a principal ideal. How to choose? (existence of p and q is already known)
Comment: Do you mean to ask **If I is not principal, then how to find z such that N(z)=N(I) while z is not in the ring of integers**? I am not very sure of what you are asking.
Comment: sorry, I want to show how to choose p and q such that (p,q) is not principal ideal. And How to show that I is not a principal ideal. If we can show that N(z) is not equal to N(I), then we know I is not principal. but we cannot check all of z in ring of integer. So how to show I is not principal? ,in general
Answer: I am responding to the question in the comment, which is too long to fit into a comment.
In different cases there are different methods of showing the non-principalness of an ideal, e.g. $I=(x,y)\subseteq\mathbb Q[x,y]$ is not a principal ideal, by degree considerations, for example.
Also, even if you cannot check all $z$ in the ring of integers, you can still prove that such $z$ that $\operatorname{N}(z)=\operatorname{N}(I)$ cannot exist:
Let $R=\mathbb Z[\sqrt{-5}]$ and $I=(2,1+\sqrt{-5}).$ Then the norm of $I$ is equal to $|R/I|=|\mathbb Z/2\mathbb Z|=2$ (try to prove that $R/I\cong\mathbb Z/2\mathbb Z$ by considering the homomorphism $\mathbb Z\rightarrow R/I:1\mapsto(1+I)$ and noticing that $2\in I$). But there is no element $z$ with norm $2,$ as $\operatorname{N}(a+b\sqrt{-5})=a^2+5b^2\not=2, \forall a, b\in\mathbb Z.$
In other cases there are other ways to show a certain ideal is not principal, but I haven't come across with a universal way of doing so.
Hope this provides a hint to your question.
Comment: Thank you. I will try to think more
Comment: Can we calculate a norm of element in cyclotomic field?
Comment: Well, $\mathbb Q(i)$ is a cyclotomic field, and its norm is simply $\operatorname{N}(a+bi)=a^2+b^2.$ Other cyclotomic fields' norms might be calculated similarly.
Comment: If degree is large, then I think that it is hard to calculate norm of element.


Convert Sonicwall Export File to Plain Text

Question: I want to convert Sonicwall Export File to Plain Text
I used: https://www.base64decode.org/dec/Z29iYmxlZHlnb29r/
and: http://www.freeformatter.com/base64-encoder.html
but still it is not full readable.
anyone know the solution, please let me know.
Answer: If you mean the string converted from that website doesn't split character "&" , you can save the string to .txt (assume it is SonicWALL.txt reside at c:\ ) file then use powershell.exe to make it more readable :
<code>(get-content c:\sonicwall.txt) -replace "\&","`n"
</code>


Unique polynomial in $C[x,y]$

Question: I am working on the below problem:
Let $I$ be the ideal generated by $x$ and $y$ in $\mathbb{C}[x,y]$. Prove that there is a unique (up to scalar) polynomial $f(x,y)$ of degree $2$ in $I^2$ which satisfies $f(2,3) = f(-1,5) = 0$.
Here are my thoughts so far:
If $I = \langle{x,y}\rangle$ in $\mathbb{C}[x,y]$, from what I understand, $I^2 = \langle{x^2,y^2,xy}\rangle$ in $\mathbb{C}[x,y]$. Thus, if we have a polynomial of degree $2$ in $I^2$, $f(x,y) = ax^2 + by^2 + cxy$ for some complex scalars $a,b,c$.
Thus, if $f(2,3) = f(-1,5) = 0$, we have $0 = 4a + 9b + 6c$ and $0 = a + 25b -5c$. It remains to show that we can solve this system of $2$ equations in $3$ unknowns uniquely for $a,b,c$.
But, this seems impossible to me. A system of $n$ equations with $n + 1$ unknowns can't be solved uniquely. Where did my thinking go wrong? If I instead take $I^2 = \langle{x^2,y^2}\rangle$, the problem will work out -- we will arrive at a system of $2$ equations in $2$ unknowns, and the corresponding matrix will have full rank (determinant nonzero), so there will be a unique solution. But, this contradicts the notion of a square of an ideal.
With the right notion of the square of an ideal, is there a third equation I can arrive at from the given information?
Thanks!
Answer: I note that "up to scalar" allows a third degree of freedom.  Are you sure that your parametrized set of solutions are not all the same up to scalar multiple?
(When I solve it, this turns out to be the case.)

Unique polynomial in $C[x,y]$


How to build a dataset for time-series classification?

Question: I am beginning with time series classification and have some trouble understanding how my training set should be constructed. My current data look like this:
Timestamp       User ID  Feature 1   Feature 2   ...    Feature N  target
2002-10-30         1        0            0       ...       1        0
2002-10-31         2        0            1       ...       1        0
...
...
2017-10-30         1        0            0       ...       0        1
2017-10-31         2        0            1       ...       0        0

The features are one-hot encoded text features, recorded at time t for a given User ID. The target is an event occurring / not occurring at time t. I am willing to detect this event given a new set of features for all the User IDs of the dataset, at a new given time t.
I understood from this paper that one way to model this is by using a "sliding windows classifier".
For any time t, I could aggregate together the features from t, t-1, ... t-n and set a more flexible target that would be "the event occurred or not at either t, t+1, ... t+n". Is this the correct way to build such a classifier?
I am also considering more recent approaches like "recurrent neural network architectures (LSTM)". How could I build a training set to feed this model from the dataset above?
ps: I plan to use scikit-learn / Keras to build the classifiers.
Thanks in advance for your time and answers.
Comment: From what I see you have a simple binary classification problem (target is 0 or 1). So you have to find a relationship between input and target. No other pre-processing of data is required. You can use multiple techniques for this: Neural Networks, Genetic Programming etc ...
Answer: There is few ways as you can work with timeseries:

Straightforward use LSTM with some window, so you data will have shape like this (batch, window, data_features_dimensions...)
You can use Conv1D and other 1D methods, thus you can find some patterns.
You can build matrix from windows. This is not very logically at first sight but in such way you can find some shifted patterns in some way as LSTM do.
You can treat you timeseries as an signal and use same technics like in audio processing, and for example build spectrogram which you can process with CNN


How do I fix the The service "sanitize.userfields.commands" has a dependency on a non-existent service "entity.manager" error?

Question: I am running Drush the first time in a Drupal 9 site. I get the following error.

In CheckExceptionOnInvalidReferenceBehaviorPass.php line 86: The service "sanitize.userfields.commands" has a dependency on a non-existent service "entity.manager".

How can I fix this error?
drush --version and drush cr work.
Comment: At first glance looks like an outdated version of Drush, not compatible with Drupal v9. Try to upgrade
Comment: What command? A command provided by a module? Looks like it's not D9 ready. Can it be updated? It must have entity type manager instead. Can easily be fixed.
Comment: Currently, it is Drush Commandline Tool 10.0.3-dev
Comment: updated the question, drush was installed with drupal itself. Should we update it? How?
Comment: @hurdi and leymannx, upvoting you as it is solved by upgrading.
Comment: I had to upgrade drupal/webform to ^6.0.0.
Answer: As folks (Hudri, leymannx) alluded to in the comments, entity.manager was deprecated in Drupal 8 which means it was removed in Drupal 9. The project that has the code that's calling entity.manager is not ready for Drupal 9 (or at least the version you have installed is not ready for Drupal 9). You may want to look for alternative modules if the one your using isn't ready for Drupal 9.
This one particular error is relatively simple to fix though, you may just need to replace any references to entity.manager with references to entity_type.manager. This issue on d.o gives a good example of what you may have to do.
As @Jaypan noted in the comments, entity_type.manager may not always be the correct replacement. From the entity.manager documentation:

Use \Drupal::entityTypeManager() [i.e. entity_type.manager] instead in most cases. If the needed method is not on \Drupal\Core\Entity\EntityTypeManagerInterface, see the deprecated \Drupal\Core\Entity\EntityManager to find the correct interface or service.

Note: if this issue is being caused by a contributed package, e.g. a d.o module or theme or other package included by composer, you need to work within that project's issue queue to patch the project instead of updating the files directly in your codebase. At the very least, you'll want to create a local patch in your composer project and configure composer to apply the patch.
Comment: Note that `entity.manager` was split into multiple services, so `entity_type.manager` may not always be the correct replacement.
Comment: thanks for explaining possible scenarios, upvoting you.
Answer: Seems like Drush which came with the setup was not fully compatible.
I installed it again using the composer using
composer require drush/drush
It is working as expected.
Here is updated "require" section looks like in composer.json
   "require": {
        "composer/installers": "^1.9",
        "drupal/bootstrap_barrio": "^4.28",
        "drupal/bootstrap_sass": "^1.12",
        "drupal/core-composer-scaffold": "^9",
        "drupal/core-project-message": "^9",
        "drupal/core-recommended": "^9",
        "drush/drush": "^10.2"
    },

Comment: is working when i update to drush 10
Answer: For me the below works, obviously nothing any better than a band-aid fix, but an immediate remedy to a blocker

rm-rf vendor
composer install
Answer: Error I was facing  - The service "sanitize.userfields.commands" has a dependency on a non-existent service "entity.manager".
Drush old version 8
Updating composer version resolved my issue.
composer require drush/drush

After update Drupal version : 11.0.9
command to check drush version  drush version


Get latest on checkout is not supported in local workspaces. Checking out the local version

Question: I keep getting the message Get latest on checkout is not supported in local workspaces. Checking out the local version every time I do anything such as move or add controls to a frm. I wasn't getting this message till I did a check in of some code. This appears in the Output window and it's constantly happening.
I searched the web for this message with no luck. I didn't do any kind of check out as I knew that would happen as soon as I made any changes but I didn't expect this and I'm afraid of what might happen if I ignore it and lose all my work.
Can anyone help? I'm using VS 2015.
Answer: I can reproduce this issue on local workspace when enable get latest on check-out option.
Enable get latest on check-out option is only available for Server workspace (Refer to this link for details.). If you are using local workspace and enabled the get latest on check-out option, then the message "Get latest on checkout is not supported in local workspaces. Checking out the local version" will appear when you edit files.
However, you can ignore the message, the message just indicated that it checked out the local version but not the latest server version. You can Get Latest Version (right-click --> Get Latest Version) first if you want to check out the latest server version.
So, the problem on local workspace is caused by enabled the source control option: Get latest version of item on check-out in a server workspace. If you don't want to output the message, you can uncheck the option. (Tools -> Options... -> Source Control -> Visual Studio Team Foundation Server)
Comment: That appears to be the issue. Thanks much!
Comment: The reason I checked that in Tools -> Options was because I wanted people to automatically get the latest version every time they checked out a project. Am I right in saying that developers still have to explicitly do this when checking out projects?


How to compare current time with time range?

Question: I have two String variables - time1 and time2. Both contain value in the format HH:MM. How can I check:

If the current time is within
time1 and time2?
time1 will happen in the nearest
hour?

Upd.
I've implemented the following to convert time1 to Date format. But it uses depreciated methods:
Date clTime1 = new Date();

SimpleDateFormat timeParser = new SimpleDateFormat("HH:mm", Locale.US);
try {
  clTime1 = timeParser.parse(time1);
} catch (ParseException e) {
}

Calendar now = Calendar.getInstance();
clTime1.setYear(now.get(Calendar.YEAR) - 1900);
clTime1.setMonth(now.get(Calendar.MONTH));
clTime1.setDate(now.get(Calendar.DAY_OF_MONTH));
System.out.println(clTime1.toString());

Comment: If I use `java.sql.Time`, then I can easily get time value from my strings - `Time.valueOf(time1).getTime()`. But how should I get current time in the same format (`long`)?
Answer:
Convert the two strings to Date
objects (which are also time objects)
Create a new Date object.
This will
contain the current time.
Use the
Date.before() and Date.after() methods to determine if
you are in the time interval.

EDIT: You should be able to use this directly (and no deprecated methods)
public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String compareStringOne = "9:45";
private String compareStringTwo = "1:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(compareStringOne);
    dateCompareTwo = parseDate(compareStringTwo);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //yada yada
    }
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}

Comment: @CaspNZ, I've tried to do so, but didn't get how to convert string in my format (not like *20081013T160000Z*) to `Date`. Can you help me with this?
Comment: @DArkO - it looks like some of the Date _constructors_ are deprecated, but using a parser in my example above isn't deprecated - I think this is still supported.
Comment: @CaspNZ, ok, I have my strings now as Date: Jan 1, 1970 + my time1. How can I get current time with date equal to Jan 1, 1970 also?
Comment: make a new inputParser with a string of 'yyyy-MM-dd' and parse in '1970-01-01'. As you've left the time off, it'll fill it with the current time for you.
Comment: That does seem a little hackish, however. Another way would be to create a new empty date and extract the current Date and Year values from it and add them to your initial dates when you parse them in (you'd have to change your input format string).
Comment: @CaspNZ, first approach (_make a new inputParse ..._) doesn't work - the time returned is 00:00:00.
Comment: @CaspNZ, with regards to the second approach - I didn't manage to implement that (for ex., how to add leading zeroes?), so I've implemented that in a different way - see the code in the question. But I don't like such approach. And, is it fast enough?
Comment: Ok check out my new example - I think this one is going to work well. And it should be pretty fast.
Comment: And how would this work if the user picked, say, 5am for the start time and 3 am for the end time??
Comment: Well, this is an example solution, you might want to evaluate both cases for it to be completely accurate. It's not hard to change the code to handle this situation. Perhaps a better function name would have been "isNowBetween(startTime, endTime)"
Comment: @CaspNZ thanks for your help. it works for me.. thanks again. but I have a query, in your condition why did you just comparing the constant time (datecompareOne) with the variable time (date) ?.. What if I used this ((date.after(datecompareOne)) && (date.before(datecomparetwo)))
Comment: note that you have to use `HOUR_OF_DAY` if you want 24 hour format
Comment: how to get Am and Pm time difference? write now not able to difference between day and night timing.
Comment: Change the input format. Look up the input format for am and pm ( I think it's just 'HH:mm a'. Then parse as usual. I haven't been using Java for a long time, so can't help you anymore here.
Answer: This is what I used as simple function and it worked for me:
public static boolean isTimeWith_in_Interval(String valueToCheck, String startTime, String endTime) {
    boolean isBetween = false;
    try {
        Date time1 = new SimpleDateFormat("HH:mm:ss").parse(startTime);

        Date time2 = new SimpleDateFormat("HH:mm:ss").parse(endTime);

        Date d = new SimpleDateFormat("HH:mm:ss").parse(valueToCheck);

        if (time1.before(d) && time2.after(d)) {
            isBetween = true;
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return isBetween;
}

Answer: SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");

Date EndTime = dateFormat.parse("10:00");

Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));

if (CurrentTime.after(EndTime))
{
    System.out.println("timeeee end ");
}

Don't forget to surrounded with a try catch block
Answer: if you want time between after 9PM to before 9Am you can use following condition..
if(cal.get(Calendar.HOUR_OF_DAY)> 20 || cal.get(Calendar.HOUR_OF_DAY)< 9)
{
    // do your stuffs
}

Answer: Look into the Calendar class. It has the methods to support what you are asking. Date is deprecated and not recommended to use.
Here is the link to the API. Calendar
About the usage. First you need to call Calendar.getInstance() to create a calendar object.
Next you need to Set the two fields using cal.set(Calendar.HOUR, your hours) and Calendar.MINUTES the same way. Next you can call the compare function, before or after functions to get the desired info. Also you can get an instance with the current time in the current locale.
Answer: For example if you want to compare time between 11pm to 6am for calculating extra night fare for any vechicle. then following code will help you.
// Code
package com.example.timedate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

import android.os.Bundle;
import android.app.Activity;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView tv;
    Button bt;
    int hour,min;
    String AM_PM;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = (TextView)findViewById(R.id.textView1);
        bt = (Button)findViewById(R.id.button1);

        final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());*/

        bt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                Calendar c = Calendar.getInstance();
                hour = c.get(Calendar.HOUR_OF_DAY);
                min = c.get(Calendar.MINUTE);
                int ds = c.get(Calendar.AM_PM);
                if(ds==0)
                AM_PM="am";
                else
                AM_PM="pm";

                Toast.makeText(MainActivity.this, ""+hour+":"+min+AM_PM, Toast.LENGTH_SHORT).show();
                if((hour==11&&AM_PM.matches("pm")) || (hour<7&&AM_PM.matches("am"))  || (hour==12&&AM_PM.matches("am")))
                {
                    Toast.makeText(MainActivity.this, "Time is between the range", Toast.LENGTH_SHORT).show();
                }
                else
                    Toast.makeText(MainActivity.this, "Time is not between the range", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}`

Answer: As of now, I am thinking about the following approach:
int clTime = Integer.parseInt(time1.substring(0, 1))*60 + Integer.parseInt(time1.substring(3, 4));

Time now = new Time();
now.setToNow();
int nowTime = now.hour*60 + now.minute;

So, I'll need to compare just integer values clTime and nowTime.
Comment: If checking for a time within a *range*, you'll need to account for the overflow scenario. That is, the start time is later in the day than the stop time. Actually this situation is true regardless of the coding approach. I'm starting to like your solution for recurring daily time range checks.
Answer:     Try this if you have specific time Zone.

              try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("hh a");
            Date timeseven = dateFormat.parse("7 AM");
            Date timeTen = dateFormat.parse("10 AM");
            Date timeOne = dateFormat.parse("1 PM");
            Date timefour = dateFormat.parse("4 PM");
            Date timefive = dateFormat.parse("10 PM");
            //Get current time
            // Date CurrentTime = dateFormat.parse(dateFormat.format(new Date()));
            //Sample time
            Date CurrentTime = dateFormat.parse("9 PM");

            if (CurrentTime.after(timeseven) && CurrentTime.before(timeTen)) {
                Toast.makeText(this, "FIRST", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timeTen) && CurrentTime.before(timeOne)) {
                Toast.makeText(this, "Secound", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timeOne) && CurrentTime.before(timefour)) {
                Toast.makeText(this, "THird", Toast.LENGTH_SHORT).show();
            } else if (CurrentTime.after(timefour) && CurrentTime.before(timefive)) {
                Toast.makeText(this, "Fourth", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "Not found in your time zone", Toast.LENGTH_SHORT).show();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

Answer: class TimeRange {

    LocalTime from;
    LocalTime to;

    public TimeRange(LocalTime from, LocalTime to) {
        this.from = from;
        this.to = to;
    }

    public boolean isInRange(Date givenDate) {

        LocalTime givenLocalTime = getLocalDateTime(givenDate).toLocalTime();
        return givenLocalTime.isAfter(from) && givenLocalTime.isBefore(to);
    }

    public static LocalDateTime getLocalDateTime(Date date){

        return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
    }
}


Did anybody try to analyze Strange Meadow Lark by Dave Brubeck by functional analysis?

Question: I was trying to understand the chord progression in Strange Meadow Lark, but it comes to a point where the changes are a little bit blurry of what is going on. Did anybody try to? Maybe we can discuss it here.

As requested, an edit:
Ok, the part I was struggling is when the music is in G Major. The part that I got was this:
Gmaj7, Cmaj7 | D(b5 b9) , G6 | C6 | Gmaj7, C,, G7 | G7(b9) | Cmaj7 | D7(b9) | Gmaj7, G7 | Cmaj7, D7(b9) | G13, Db7(+11)* | C6, C#dim | Gmaj7, G6,, E7(b9)** | Fmaj7***, G |
I tried to put in functional analysis, but maybe this is wrong in some parts.
Imaj7, IVmaj7 | V(b5 b9), I6 | IV6 | Imaj7, IV,, V7/IV | V7(b9)/IV | IVmaj7 | V(b5, b9) | Imaj7, V7/IV | IVmaj7, V7(b9) | I13, ?* | Imaj7, I6,, ?** | ?***, I |
After this I didn't even try to.. but there is more.
Db(+11)* - I just could see it as a tritone substitution of a modal exchange chord... I think here I have no clue of what music theory to apply.
E7(b9)** - No clue
Fmaj7*** - Didn`t even try to think about it.
What am I lacking to understand it?
Thanks in advance.
Comment: Please post the changes for the part you're wondering about. Also, just know that functional analysis was developed to address Common Practice Era music and that jazz does not attempt to follow its principles.
Comment: Are you looking for a transcription of the chord changes?
Comment: No, I have it here.. but I tried to apply some functional anaylsis and some parts are not quite obvious..
Comment: Cool information.. I was seeing easily some I IV V, secondary dominant, etc.. but let me post and if you can help me understand, I'd really appreciate :)
Comment: @Aaron there's definitely a functional component to jazz harmony, though.  "Tritone substitution," for example, didn't come out of nowhere.  Yes, functional analysis is sometimes going to come up short, but more often than not it won't.  Besides, the same is true of classical music.
Answer: I don't want to go into the functional analysis talk, because it gets to the dumb "which words are correct" discussion, and it won't make you really understand the harmony. Real understanding means being able to handle the situations in your own playing, to be able to utilize the same tricks in your own chordal improvisation, and to recognize the patterns when you hear them. And this comes through practice and not fancy theoretic words and "analysis".
Instead, I'll try to give exercises that utilize the same harmonic patterns that I personally see in the chords you gave.

Db7(+11)* | C6, C#dim

For basically any chord movement anywhere in any existing song you know, when you move from anywhere to chord X, try inserting a dominant-seventh chord a semitone above, right before chord X. Practice this on a lot of tunes, until the trick becomes familiar to you, so much that you can use it as part of your own chordal improvisation, and that you start to recognize it in music when you hear it. Then you've REALLY LEARNED it, and who cares what you call it or what's a "correct" name. (Unless your target is to become a theory talk youtuber where the gig is to impress people by saying fancy things)
One example. You start with the progression G - C - D - G - Em - Am - D - G. With the added chords this becomes: G - Db7 - C - Eb7 - D - Ab7 - G - F7 - Em - Bb7 - Am - Eb7 - D - Ab7 - G.

Gmaj7, G6,, E7(b9)**

Play this progression: G - E7 - A7 - D7 - G (repeat). Notice any similarity? Then play: G - E7b9 - A7b9 - D7b9 - G.
Combine with the previous trick, inserting a dominant seventh chord a semitone above, before every chord. G - F7 - E7 - Bb7 - A7 - Eb7 - D7 - Ab7 - G.

Fmaj7***, G

Practice this: G - Fmaj7 - G - Fmaj7 - ... Play over those chords until you feel comfortable operating with what's happening. Make your playing so that G feels like home. Let's support G as a home: G  - F - G - F - G - F - G - D7 - G
Also try: Gmaj7 - Fmaj7 - Gmaj7 - Fmaj7 - Gmaj7 - Fmaj7 - Gmaj7 - D7 - Gmaj7 (just so that you'll have to keep switching the F note between sharp and natural)

In these exercises, play the progressions as chords, and use a looper or other accompaniment device and solo over the chords. After you've spent enough hours practicing, the questions about the Brubeck tune have been solved. Musical understanding comes through practicing, not through talking with fancy theory terms.
(caveat: I wrote this on my phone and didn't physically listen to the tune or any of the chords I wrote. If it sounds wrong when I get to an instrument to test it, I'll say oops and remove the answer)
Comment: I could do the same exercises to drill common heavy metal chord progressions into my head and gain a similar "understanding" of them (e.g. i - bII - i, i - VI - VII, i - #IV - i). However, this does *not* explain why these chord progressions are common or why they make any musical sense. (In particular, I've been forced to conclude that i - #IV - i is used precisely because it sounds transgressive and doesn't otherwise make musical sense.) I don't think this is a satisfactory answer as a result.
Comment: @I strongly disagree and claim that you are not only _wrong_ but also that that kind of thinking does a disservice to music. What I'm trying to say here, and what you obviously did not understand - is that real understanding comes from living and experiencing interactions and cause-effect relations in practice. Understanding does not and should not be required to come primarily from verbal descriptions, because verbal descriptions are a very badly working way to transfer the said real understanding from one person to another. Which was proven by your failing to understand what I tried to say.
Comment: @Dekkadeci I don't believe that descriptions in the prevailing theoretic language somehow provide more true answers to the "why" questions. Musical patterns are used because they work. Theory tries to give names to the practices. Theory is not a law of nature, and being able to verbally legitimize one's actions in a way that satisfies theory worshippers' judgement is not a better "understanding". The idolization of theoretic language is harmful, and it is the reason why the OP has been mislead to come to seek help from the gods of theory, when he should play more tunes to learn patterns
Comment: Drawing from my own experience, I am *not* convinced that playing tunes leads to naturally learning patterns as anything more than "these chord progressions are common/used and I don't know why". I had no understanding of why bII, augmented 6ths, and common-tone diminished 7ths were used until I took the RCM's Harmony 3 & 4 courses, despite encountering them in my piano repertoire before that point (and also failing to process them fully at that point to boot, a la "Schubert is using A major scales in an A flat major section and I don't know why").
Comment: As a result, I am convinced that "being able to verbally legitimize one's actions" *is* a better understanding than being unable to do so. Without this verbal legitimization, all I can conclude is that the chord progressions are common in some genre and, in order to compose in that genre, I should use those chord progressions - and the best justification is that imitating the masters makes my music sound like theirs and therefore be more societally acceptable simply because they're the trend-setters people like. This is unfortunately how I've self-learned heavy metal music theory.
Comment: @Dekkadeci There is no theory that's "behind" heavy metal or Schubert independently of people. There are only subjective ways of reasoning about things in music-making. Thinking "one fret higher" is fine, and it can be shown on a fretboard without talking. Composers of heavy metal may have used theory like that. Had they let themselves be mislead to believe that the language and discourse developed for the needs of people in the Western classical music for describing Western classical music, is needed for _all_ people and _all_ music, they would have created different music than they did.
Comment: I'm mainly arguing that, at least if the question asker is anything like me, after they've spent enough hours practicing your suggested chord progressions, their questions about the Brubeck tune have *not* indeed been solved and they need further verbal explanation to justify the chord progressions. There is even a nonzero chance that *no* verbal explanation will suffice, either (my "explanation" of the Fmaj7 - G portion is the sorriest in my answer and sounds the most like an excuse a la "the masters do it").
Comment: Quite a lot of music is easier to explain with a different theoretical framework than functional analysis (e.g. quartal harmony, gamelan, 12-tone serialism). Unfortunately, in my experience, that music basically *needs* to be explained verbally - no amount of practice will drill it into heads why the music was composed this way. Jazz harmony involves enough functional harmony (e.g. ii - V - I, rhythm changes) that we may as well take functional analysis as far as we can with it. (It's like using functional analysis to explain ragtime - it fits often enough.)
Comment: I understand what you are implying, and it's true about the construction of the hearing perception for a "cutural standard," but I totally disagree that it is giving fancy names only. Even though it was my question, I'd put it another way today. "Is there a way to understand this via functional..." etc etc..  if it is not possible, ok, I accept it; let's move on.

I believe that you are smart enough to understand which ways I'd argue, and we should do us both a favor by saving time. But thanks for the exercise anyway :)
Comment: @pbriquet Did you do the exercises I suggested in this answer?
Answer: Assuming the chord chart is correct...
Major-minor 7th (a.k.a. "dominant 7th") chords are so common in jazz that I treat none of them as secondary dominants. Until you hit the Db7(+11) chord, I wouldn't treat the music as straying from (a rather chromatic) G major at all.
The Db7(+11) chord resolves to a C6 chord and can therefore be interpreted as a tritone substitution of V7/IV. Note that both the Db7(+11) chord and V7/IV in G major, the G7 chord, have an F-B tritone in them.
The C#dim chord resolving to a Gmaj7 chord is hard to explain, but you can kind of treat the C#dim chord as vii°/V and the Gmaj7 chord as a I6/4(/3) chord that never properly resolves to V.
The E7(b9) chord resolves to a Fmaj7 chord, so I'd say the E7(b9) chord is a V7(b9)/ii chord with a deceptive (cadence-style) resolution to VI7/ii, a.k.a. bVII7. The b9 a.k.a. F in the E7(b9) chord should make the deceptive resolution more convincing.
bVII resolves often enough to I in pop-like music that we can treat the Fmaj7-G chord progression as bVII7-I.
Comment: Thank you so much. I'm reading carefully right now. The chords were in a music sheet I was using to play it, so I assumed to be correct, but I didn't double check it.


Are DFS and BFS interchangeable?

Question: I know DFS is good for some problems and BFS is good for some other problems but if something can be solved using DFS, can it be solved (maybe less optimally) with BFS (or vise versa)? And is there a proof for it? Thanks!
Comment: Does this answer your question? [When is it practical to use Depth-First Search (DFS) vs Breadth-First Search (BFS)?](https://stackoverflow.com/questions/3332947/when-is-it-practical-to-use-depth-first-search-dfs-vs-breadth-first-search-bf) Tl;dr absolutely not
Answer: No.
Shortest path is the canonical example of something that can be solved easily with BFS.  But with DFS you either have to accept the possibility of endless loops, or else avoid revisiting nodes and fail to find shortest paths in many cases.
Examples going the other way are harder to find.  But for example the Hopcroft-Tarjan algorithm for planarity testing relies on the fact that in a DFS you know properties of the entire path to the present node.  And that context you do not have in a BFS.

Are DFS and BFS interchangeable?


How to introduce keyboard functions in Opengl code

Question: I am new to opengl I tried to make an isosurface by reading from a text file .now I want to introdude keyboard functions in my code so that I can rotate an do all that stuffs. please tell me from where i can study that or give me a sample code
Sudhanshu
Comment: OpenGL does not have anything to do with Keyboards. What are you using to create your OpenGL context (SDL, ...), what OS are you on?.
Answer: OpenGL only deals with drawing stuff. It gives you a canvas and some primitive drawing tools. Nothing more. Anything beyond that is the task of the user interface system provided by the OS.
Maybe you're using GLUT and are mislead by its name. GLUT is not part of OpenGL; it's a rudimentary framework aimed at developing simple OpenGL example programs, but that's about it.


nginx location regex directive doesn't fire

Question: I'm trying a simple location directive in my nginx config, and it doesn't seem to be working all that well; I want to ensure that all requests to a local css or js file have an expires header, so I added the following to my server block (shown below). Am I missing something? The movies location block correctly works (and loads CSS), however it does not have the expires header as expected. I've tried putting the wanted location block inside the movies location block to no success.
server {
  server_name           www.example.com;

  index  index.php index.html index.htm;

  access_log            /var/log/nginx/example.com/access.log;
  error_log             /var/log/nginx/example.com/error.log;

  root /var/example.com;

  location / {
    try_files $uri $uri/ /index.php$is_args$args;
  }

  # CSS and Javascript -- this is the added location block
  location ~* \.(css|js)$ {
    expires 1y;
    access_log off;
    add_header Cache-Control "no-cache, public, must-revalidate, proxy-revalidate";
  }

  location = /movies {
    return 301 $scheme://$host/movies/;
  }
  location ^~ /movies {
    alias /var/example.com/movies/current/public;
    fastcgi_index index.php;
    try_files $uri $uri/ /movies/movies/index.php$is_args$args;

    location ~* \.php {
      fastcgi_pass unix:/run/php/php7.1-fpm.sock;
      fastcgi_split_path_info ^(.+\.php)(.*)$;
      include /etc/nginx/fastcgi_params;
    }
  }

  ## many other location blocks like the immediate above snipped

  # pass the PHP scripts to FastCGI server listening on /run/php/php7.1-fpm.sock
  location ~ \.php$ {
    try_files $uri /index.php =404;
    fastcgi_pass unix:/run/php/php7.1-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
  }
}

Comment: `location ^~ /movies` is not a regular expression, it is a prefix location that takes precedence over any regular expression location. Besides, you need URIs that begin with `/movies` to be processed by the `location ^~ /movies` block, as it has a different value for `root`/`alias`. So the correct solution is to use a nested location (and make it work).
Comment: Your `location ~* \.(css|js)$` block will not match URIs that begin with `/movies`. See [this document](http://nginx.org/en/docs/http/ngx_http_core_module.html#location).
Comment: Thanks, @RichardSmith. I'd apparently not nested it correctly somehow; it works correctly now. If you want to post this as an answer, I'd be happy to accept it.
Answer: The location ^~ /movies block is a prefix location, and the ^~ operator causes it to take precedence over regular expression locations. See this document for details.
This is exactly the behaviour you need, because URIs that begin with /movies require a different document root to be set.
To define special headers for URIs that begin with /movies and end with .css or .js, use another nested location block.
For example:
location ^~ /movies {
    ...
    location ~* \.php {
        ...
    }
    location ~* \.(css|js)$ {
        ...
    }
}


Permission problems of mysql under Debian

Question: After having had my huge hard drive crash (which was related to a LVM update of Debian, not the hardware) I am facing the next problem:
I try to reinstall mysql after that crash and did a dpkg --ignore-depends ... --purge mysql-... on the machine. No more MySQL, only dependent packages:
kermit:~# dpkg -l | grep -i mysql
ii  courier-authlib-mysql
ii  libdbd-mysql-perl
ii  libpam-mysql
ii  php5-mysql
ii  postfix-mysql
ii  proftpd-mod-mysql

No mysql process running, no directories like /var/lib/mysql, no nothing. Basically (that's what I think) a clean install of mysql. But no, it is not that easy. Step by step:
kermit:/var/cache/apt/archives# ls mysql-*
mysql-client_5.1.43-0.dotdeb.1_all.deb       mysql-common_5.1.43-0.dotdeb.1_all.deb  mysql-server-5.1_5.1.43-0.dotdeb.1_i386.deb
mysql-client-5.1_5.1.43-0.dotdeb.1_i386.deb  mysql-server_5.1.43-0.dotdeb.1_all.deb
kermit:/var/cache/apt/archives# dpkg -i mysql-*.deb
[...]
Stopping MySQL database server: mysqld.
100204 19:37:47 [Note] Plugin 'FEDERATED' is disabled.
100204 19:37:47  InnoDB: Started; log sequence number 0 44233
ERROR: 1146  Table 'mysql.user' doesn't exist
100204 19:37:47 [ERROR] Aborting

100204 19:37:47  InnoDB: Starting shutdown...
100204 19:37:53  InnoDB: Shutdown completed; log sequence number 0 44233
100204 19:37:53 [Note] /usr/sbin/mysqld: Shutdown complete

Starting MySQL database server: mysqld . . . . . . . . . . . . . . failed!
invoke-rc.d: initscript mysql, action "start" failed.
[...]

Boom! Not good. Only empty files in /var/log/mysql/ and nothing in /var/log/mysql.*. But behold, there's /var/log/daemon.log:
Feb  4 19:38:13 kermit mysqld_safe: Starting mysqld daemon with databases from /var/lib/mysql
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13 [Note] Plugin 'FEDERATED' is disabled.
Feb  4 19:38:13 kermit mysqld: /usr/sbin/mysqld: Table 'mysql.plugin' doesn't exist
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13  InnoDB: Started; log sequence number 0 44233
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13 [ERROR] Can't start server : Bind on unix socket: Permission denied
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13 [ERROR] Do you already have another mysqld server running on socket: /var/run/mysqld/mysqld.sock ?
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13 [ERROR] Aborting
Feb  4 19:38:13 kermit mysqld:
Feb  4 19:38:13 kermit mysqld: 100204 19:38:13  InnoDB: Starting shutdown...
Feb  4 19:38:18 kermit mysqld: 100204 19:38:18  InnoDB: Shutdown completed; log sequence number 0 44233
Feb  4 19:38:18 kermit mysqld: 100204 19:38:18 [Note] /usr/sbin/mysqld: Shutdown complete
Feb  4 19:38:18 kermit mysqld:
Feb  4 19:38:18 kermit mysqld_safe: mysqld from pid file /var/run/mysqld/mysqld.pid ended
Feb  4 19:38:27 kermit /etc/init.d/mysql[9108]: 0 processes alive and '/usr/bin/mysqladmin --defaults-file=/etc/mysql/debian.cnf ping' resulted in
Feb  4 19:38:27 kermit /etc/init.d/mysql[9108]: ^G/usr/bin/mysqladmin: connect to server at 'localhost' failed
Feb  4 19:38:27 kermit /etc/init.d/mysql[9108]: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
Feb  4 19:38:27 kermit /etc/init.d/mysql[9108]: Check that mysqld is running and that the socket: '/var/run/mysqld/mysqld.sock' exists!
Feb  4 19:38:27 kermit /etc/init.d/mysql[9108]:

Well, indeed no files there:
kermit:~# ls -larth /var/lib/mysql/ /var/lib/mysql/mysql/
/var/lib/mysql/mysql/:
insgesamt 0
drwx------ 2 mysql mysql  48  4. Feb 19:38 .
drwx------ 3 mysql mysql 192  4. Feb 19:38 ..

/var/lib/mysql/:
insgesamt 21M
-rw-rw----  1 mysql mysql 5,0M  4. Feb 19:35 ib_logfile1
-rw-r--r--  1 mysql mysql    0  4. Feb 19:37 debian-5.1.flag
drwxr-xr-x 42 root  root  1,1K  4. Feb 19:37 ..
drwx------  2 mysql mysql   48  4. Feb 19:38 mysql
drwx------  3 mysql mysql  192  4. Feb 19:38 .
-rw-rw----  1 mysql mysql 5,0M  4. Feb 19:38 ib_logfile0
-rw-rw----  1 mysql mysql  10M  4. Feb 19:38 ibdata1

Some more dirs:
kermit:/etc/mysql# ls -larth /var/run/mysqld/
insgesamt 512
drwxr-xr-x 13 root  root 672  4. Feb 19:35 ..
drwxr-xr-x  2 mysql root  48  4. Feb 19:35 .

kermit:~# ls -larth /var/log/mysql*
-rw-r----- 1 mysql adm  0  4. Feb 19:37 /var/log/mysql.log
-rw-r----- 1 mysql adm  0  4. Feb 19:37 /var/log/mysql.err

/var/log/mysql:
insgesamt 4,0K
drwxr-xr-x 15 root  root 4,3K  4. Feb 19:35 ..
drwxr-s---  2 mysql adm    48  4. Feb 19:35 .

Config:
kermit:/etc/mysql# grep -v ^# my.cnf  | grep -v "^$"
[client]
port        = 3306
socket      = /var/run/mysqld/mysqld.sock
[mysqld_safe]
socket      = /var/run/mysqld/mysqld.sock
nice        = 0
[mysqld]
user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
language    = /usr/share/mysql/english
skip-external-locking
bind-address        = 127.0.0.1
key_buffer      = 16M
max_allowed_packet  = 16M
thread_stack        = 192K
thread_cache_size       = 8
myisam-recover         = BACKUP
query_cache_limit   = 1M
query_cache_size        = 16M
expire_logs_days    = 10
max_binlog_size         = 100M
[mysqldump]
quick
quote-names
max_allowed_packet  = 16M
[mysql]
[isamchk]
key_buffer      = 16M
!includedir /etc/mysql/conf.d/

Anyone any idea?
Thanks!
Comment: It was a permission problem, but not mysql specific: the /var had the wrong permission, 700 instead of 755. Fixing that also fixed mysql.
Answer: move your /var/lib/mysql/ to /var/lib/mysql.bad and retry your install. dpkg will maybe reinstall all the databases.
You should maybe remove the packages because re-install...
Comment: `/var/lib/mysql*` were already deleted before I reinstalled.
Answer: I had this issue after updating mysql.
I did:
mysqlcheck --all-databases --repair -u root -p
mysql_upgrade -u root -p

But in your case, you may have to empty /var/lib/mysql/* before reinstalling, as it keeps transaction logs inside
Comment: MySQL didn't even start, so I couldn't connect to it.
Comment: So you should :
uninstall package
purge /var/lib/mysql and install again
install again
Answer: There are a couple of approaches to dealing with this:
Use a generic method of setting up the mysql server, according to the mysql documentation, but accommodating any Debian specificity. It will involve running mysql_install_db (probably with --user= and --datadir= just in case) and setting permissions on the relevant directories before you attempt to start the service, at least.
OR
Try to fix the Debian-created installation, probably by starting over, ensuring that everything is out of the way and no related processes are left running and re-obtaining just the packages you need and their dependencies. I'm not a Debian person, but I'd be inclined to let your package manager do the dependency resolution rather than handing a series of .debs to dpkg. (apt-get install mysql-server, IIRC).
Comment: The directory permissions were the thing: I already had thought about those but I never checked the upper levels. The `/var` directory had the wrong permission, 700 instead of 755. After fixing that, everything worked without a glitch!
Marking this as the correct answer.


Is this old, possibly Musima classic guitar worth keeping?

Question: I got a 1960-something Musima classic for 40 dollars on a flea market, I believe it is a classic (I can't find any information on the guitar anywhere, but it looks like a musima classic) but the fretboard is ripped up a bit and the tuning cogs are broken on the first string.
Is it worth it to restore or should I throw it away?
Comment: You should really find a classical guitar player to give you an opinion - some old instruments are worth keeping (if hand made from good materials), some not.  Also don't "restore" until you are certain it's not of value to collectors - changing any of the original components may reduce the "value" to the collector types.  (I just googled "Musima guitar" and found lots of information about this brand.)
Comment: Whether the wood is 56 or 100, if the guitar is not good, it's not good, no matter how much time you give the wood.
It will always be a 40 dollar guitar.

But I'll take it to an expert, thanks.
Comment: I would not trow away any wood that 56 years old.
Comment: If it is Brazilian Rosewood it is worth a fortune regardless of the level of luthier work that made it.
Comment: After scouring the internet, I can only find ONE guitar with the same bridge. This old Ebay ad: https://www.google.dk/url?sa=i&rct=j&q=&esrc=s&source=images&cd=&ved=0ahUKEwjVj9zc1-jKAhXCO5oKHQ98C84QjxwIAw&url=http%3A%2F%2Fm.ebay.co.uk%2Fitm%2F231432021399%3F_mwBanner%3D1&bvm=bv.113370389,d.bGs&psig=AFQjCNFdol4AG-bfxzEfkaU7RN0ZDvBYqQ&ust=1455038704067446&cad=rja
Comment: Large picture of the other guitar. I can't tell the name, though: http://i.ebayimg.com/00/s/MTAwMFg3NTA=/z/yvgAAOSwaNBUfikW/$_1.JPG
Answer: From the pictures you've posted, it seems to be in good shape.  A lot(!) of scratches on the soundboard behind the bridge, but no obvious problems.
I can't be sure, but the soundboard (lighter wood on the top) seems to be solid timber all the way through - meaning it's possibly one-piece, better than the thin plywood like you get on more modern cheap guitars.
It has a zero-fret which is unusual (though note, this is not a bad thing); I've read this is often seen on older European-made guitars though I'm not an authority on that.  (Some people will tell you a zero fret is a bad thing - but that's a myth, they're fine if the setup is OK.)
It may be possible to replace the tuner - they're usually supplied as two plates with three on each, but the size and the distance between tuner shafts and between fixing screws sometimes varies, so if replacing it you should check the tuners against the guitar when buying...
So: I wouldn't know about any value to collectors (I'm not one) but if it plays OK I would certainly keep it.
One thing I'd look out for: it appears to be a classical-style guitar, but it looks like it's wearing steel strings.  These probably have higher tension than the more usual nylon-style strings fitted to classicals.  So if you tune this up or put new steel strings on, beware of putting too much tension on the bridge and soundboard.  (I'd recommend classical guitar strings if you want to replace the ones it's got.)
Comment: Yeah, the steel strings are the source of the bridge damage. If it has good tonal quality (put some new cheaper classical strings on it and see) and has a decent fretboard feel, then it probably should be taken for a quote to fix the basics (setup and bridge repair) at least. Then the decision is more "is it competitive with a new guitar at that price point?" Without even getting into collector status/desirability. I work in an antique {item} business and we prefer to get things untouched so we can put people we trust on the repairs. Something to think about
Answer: Without seeing the guitar it'd be hard to tell. It would cost quite a bit to fix the issues you mentioned. I think the best thing would be to take it to an expert and see if it's worth anything. Keep in mind that it could be simply a 40$ guitar.
Another thing to consider is its sound. Do you like it? If you do, you should repair it and keep it.
Answer: Im a classical guitar player and yes it is in decent shape. But something music be done inorder to make it sellable
a) if you do nothing but this FIX THE TUNING COGS without these functioning it renders the guitar basically useless
b) change the strings they are old and worn out also, they are not for classical guitar. The steel strings will cause extra tension on the fretbpard causing it to spoil pretty quickly
If it is a solid top guitar you are in luck. Solid top guitars sound better the longer you play them for due tp the vibrations you create by playing the strings. If you have been playing it should make your guitar sound much better. The fretboard is just pointless to repair it playable it will do for a newby/intermediate. Many people are often concerned about the appearance of a guitar. These are not lacquer cracks but actual dents and scratches in the wood you could easily fill them in. You may get a bit more for the guitar. Do not get a proffessial to do it they will charge a fair amount and looking at how much you could make it may not be worth it. Do it yourself and if you screw it up oh well.
Good luck!
Source : 9+yrs playing the classical guitar
Answer: as far as i know, musima is an old, not more operating manufacterer from the so called 'Deutsche Demokratische Republik / DDR' - German Democratic Republic. I got one by myself. The guitars are nothing special, excluded their historical value for some people i guess.


Proving a function $f:\mathbb{Z}_{nm} \rightarrow \mathbb{Z}_n \times \mathbb{Z}_m$ is an isomorphism

Question:
Let $n,m$ be two coprime numbers. Prove that the function $f:\mathbb{Z}_{nm} \rightarrow \mathbb{Z}_n \times \mathbb{Z}_m$ such that  $f(\overline{r})=(\overline{r},\overline{r})$ is an isomorphism between rings.

I've already proven that $f$ is an homomorphism but I'm struggling with the bijectivity part.
Surjectivity:
We have to prove that for any $(\overline{a},\overline{b}) \in \mathbb{Z}_n \times \mathbb{Z}_m$ there exists $\overline{r} \in \mathbb{Z}_{nm}$ such that  $(\overline{r},\overline{r})=(\overline{a},\overline{b})$. But I don't know how to find such $\overline{r}$. However there are two requirements that such $\overline{r}$ has to meet:
$\overline{a}=\overline{r}  \iff a \equiv r \pmod n \iff a-r = c_1 n$
$\overline{b}=\overline{r}  \iff b \equiv r \pmod m \iff b-r = c_2 m$
But I don't really know how to continue from here.
Injectivity:
We have to prove that if $\overline{a} \neq \overline{b} \implies  (\overline{a},\overline{a})\neq(\overline{b},\overline{b})$. However I don't see why two elements of $\mathbb{Z}_{nm}$ being different implies they are different in both $\mathbb{Z}_{n}$ and $\mathbb{Z}_{m}$.
Comment: You have to add, that $n$ and $m$ are coprime because for example $\mathbb{Z}_{4}$ isn't isomorphic to $\mathbb{Z}_2\times \mathbb{Z}_2$
Comment: @Fakemistake thanks, corrected.
Answer: You first have to prove the map is well defined.
Define
$$
g\colon\mathbb{Z}\to\mathbb{Z}_n\times\mathbb{Z}_m
\qquad
g(r)=(\bar{r},\bar{r})
$$
This is a ring homomorphism with no assumption on $m$ and $n$. The kernel is
$$
\ker g=\{r\in\mathbb{Z}:r\in n\mathbb{Z}\cap m\mathbb{Z}\}=k\mathbb{Z}
$$
where $k=\operatorname{lcm}(n,m)$, by well known results on ideals in the ring of integers. Granted that $n$ and $m$ are coprime (which probably is what your exercise tells you), you have $\operatorname{lcm}(n,m)=nm$.
The homomorphism theorem therefore provides a unique injective ring homomorphism
$$
f\colon\mathbb{Z}_{nm}\to\mathbb{Z}_n\times\mathbb{Z}_m
$$
such that $f(\bar{r})=g(r)=(\bar{r},\bar{r})$.
Since $f$ is injective and domain and codomain have the same number of elements, $f$ is also surjective.
Answer: Since  you already proved that $f$ is an homomorphism, we need to find $\ker f=\{0_{nm}\}$ to prove that $f$ is injective. So let $x_{nm}\in \ker f$, we have $f(x_{nm})=(x_n,x_m)=(0_n,0_m)\iff x$ is multiple of $n$ and $m$ and then multiple of $lcm(n,m)=nm$. Hence $\overline x=0_{nm}$. Now, since the cardinals of  $\Bbb Z_{nm}$ and $\Bbb Z_n\times \Bbb Z_m$ are equal, $f$ is then bijective.
Answer: Show that every element of $\mathbb Z_{mn}$ can be written uniquely in the form $am+bn$, with $0\le a<n$ and $0\le b < m$. To do this, you need only show that all of the elements of the form $am+bn$ are distinct modulo $mn$, for $0\le a<n$ and $0\le b<m$. Once you've shown that, you know the map $f$ is of the form $f(am+bn)=(a,b)$, which is clearly bijective.
Given two such numbers, $am+bn$ and $cm+dn$, then if these were equivalent modulo $mn,$ you would have
$$
(a-c)m\equiv (d-b)n\pmod{mn}
$$
which implies that for some integer $k$,
$$
(a-c)m = (d-b)n + kmn
$$
The RHS is divisible by $n$, so the LHS is as well. Since $m$ and $n$ are coprime, this implies $n$ divides $a-c$, which since $a,c\in [0,n)$ implies $a=c$. Rearraning the equation to
$$
(a-c)m -kmn= (d-b)n
$$
allows you to use the same logic to conclude $d=b$, proving uniqueness.
Answer: Surjectivity, in particular, $n,m$ are relatively prime. $um+vn=1$ implies that $r=anv+bmu$.
Injectivity, $(\bar r,\bar r)=(\bar 0,\bar 0)$ implies that $r(um+vn)=r=0$ mod $m$ this implies that $rvn=0$ mod $m$ and $m$ divides $rv$, we deduce that $m$ divides $r$, since $m$ cannot divides $v$ since $um+rv=1$.


What are the concurrency (multithreading) implementation changes over different versions of JDK?

Question: What are the concurrency (multithreading) implementation changes over different versions of JDK? How exactly it differs from JDK 4/5 with JDK 7/8?
Comment: The changes are documented. Further, you will find tons of related tutorials in the internet.
Answer: Starting from 5, concurrency package has been added. Before that it was available as third party library.
Look at this URL for 8 changes
https://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/changes8.html
Also look at this URL for 7 changes
http://www.infoq.com/news/2007/07/concurrency-java-se-7


Evitar retorno null em métodos com retorno

Question: O retorno externo ao laço de repetição dentro do método só será alcançado, caso não seja encontrado nenhum valor na coleção do loop. Porém não sei se retornar null é a solução mais recomendada, como vocês fazem pra esses casos?
OBS: Acredito que o ideal seria lançar um exception, mas não consegui implementar devido a tipagem de retorno do método.
public static class ContaService
{
    public static ContaBancaria? BuscarConta(List<ContaBancaria> listaContas, string numero)
    {

        foreach (var conta in listaContas)
        {
            if (conta.Numero == numero)
            {
                return conta;
            }
        }

        return null
    }

Answer: Só você sabe o que é mais recomendado. Só você tem o contexto. O recomendado depende de contexto, porque senão vira a tal da "boa prática" que é só uma receita de bolo sem contexto para as pessoas seguirem.
Para uma resposta mais genérica pode ler Por que devemos evitar retornar códigos de erro?.
Lá verá que retornar um null não tem nada de errado, se isso for relevante e não trazer problemas para o que está fazendo.
Eu nunca gosto do uso de null, e prefiro seu uso apenas em casos onde ele é fundamental.
Este caso fica complicado dar uma solução com algum outro tipo de código de erro. No máximo poderia criar um Null Object, o que não muda muito.
Muitas pessoas preferirão usar uma exceção por não ter achado algo. Eu sou dos que acham esta uma das piores soluções porque não achar nada é algo esperado e não excepcional. Algo assim:
public static ContaBancaria BuscarConta(List<ContaBancaria> listaContas, string numero) {
    foreach (var conta in listaContas) if (conta.Numero == numero) return conta;
    throw new ContaBancariaNaoExisteException(numero);
}

Não vou postar como seria a exceção em si.
Ou pode fazer o que eu acho mais adequado, mas o C#/.NET não tem nada padrão (por isso em várias partes dele cada tecnologia usa um padrão diferente), o que torna algo que alguns consideram alienígena, mas que resolve do jeito que deve resolver sem os problemas de cada uma das outras soluções, ainda que ela também não seja perfeita. Você usa um Result, algo assim:
public static Result<ContaBancaria> BuscarConta(List<ContaBancaria> listaContas, string numero) {
    foreach (var conta in listaContas) if (conta.Numero == numero) return Result.Success(conta);
    return Result.Failure;
}

Aí no lugar que recebe em vez de verificar se é nulo ou usar um try-catch verificará se teve sucesso. Você não consegue usar o objeto sem fazer isto, ao contrário das outras soluções, ainda que se não fizer dará um erro em algum outro lugar. Algo assim:
var resultado = BuscarConta(contas, numero);
if (resultado.Ok) Write(resultado.Value);

Dá para fazer uma struct Result simples ou uma classe extremamente sofisticada que permite detalhar o erro, manter vários erros, vários valores, e ter muitas features extras. Algo assim:
Se a linguagem fosse melhor dava para fazer algo que impede o acesso em tempo de compilação. Terá como em futuras versões com o advento do ADT.
Consegue fazer a struct? Precisa de um campo para dizer se teve sucesso (pode ser uma propriedade), outro para o objeto que gerou o resultado (pode ser uma propriedade), e métodos de fábrica para gerar o erro ou o resultado certo, conforme mostra o código acima. Se pesquisar tem vários prontos.
Também pode usar o padrão TryCan ou TesterDoer ou ainda Error Hiding, como pode ser chamado, assim não precisa criar nada extra. O jeito antigo é com out, mas agora pode ser feito com tupla:
public static (bool Ok, ContaBancaria? conta) BuscarConta(List<ContaBancaria> listaContas, string numero) {
    foreach (var conta in listaContas) if (conta.Numero == numero) return (true, conta);
    return (false, null);
}

(var ok, var conta) = BuscarConta(contas, numero);
if (ok) Write(conta);

Mas eu acho que não é tão bom assim, permite o uso indevido.
Coloquei no GitHub para referência futura.


In Java, how should I declare the return type if a recursive method can return mixed values?

Question: I have the following method definition which is intended to search a JSON object for a given key and return either the JSONObject or the String value of that key. To ensure it searches through every level of the JSON object I have made it recursive, but only in the event that a deeper JSONObject can be returned. The compiler complains that this must return an Object because I have declared that return type. Fine. In two cases I am returning an object but I think its problem is that in some circumstances it will not return anything. If I add a final return false, or something, it will pass the compiler check but a call to this method will always then (eventually) return false making it useless. I am not used to a strictly typed language like Java so I haven't encountered a similar issue before. Any pointers would be appreciated.
public Object find(String contentId, JSONObject node) {
    JSONObject currentNode = (node != null) ? node : this.txtContent;
    Iterator<?> nodeKeys = currentNode.keys();

    while ( nodeKeys.hasNext() ){

        try {
            String key = (String) nodeKeys.next();

            if (key.equals(contentId)) {
                if (currentNode.get(key) instanceof JSONObject) {
                    return currentNode.getJSONObject(key);
                } else {
                    return currentNode.getString(key);
                }
            } else if (currentNode.get(key) instanceof JSONObject) {
                find(contentId, currentNode.getJSONObject(key));
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
}

Comment: Why would the method always eventually return false? (Note that returning `null` would normally be more appropriate than returning `false` here...) And why do you not do anything with the value returned by the recursive call to `find`?
Comment: It would always return false because I wasn't doing anything with the returned value from find(), as you pointed out.
Answer: Let's see, you should use the value returned by the find call and return null if not found:
public Object find(String contentId, JSONObject node) {
    JSONObject currentNode = (node != null) ? node : this.txtContent;
    Iterator<?> nodeKeys = currentNode.keys();

    while ( nodeKeys.hasNext() ){

        try {
            String key = (String) nodeKeys.next();

            if (key.equals(contentId)) {
                if (currentNode.get(key) instanceof JSONObject) {
                    return currentNode.getJSONObject(key);
                } else {
                    return currentNode.getString(key);
                }
            } else if (currentNode.get(key) instanceof JSONObject) {
                Object foundObj = find(contentId, currentNode.getJSONObject(key));
                if (foundObj!=null) {
                    return foundObj;
                }
            }
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }
    return null;
}

Comment: I see. I would normally return the call to find (e.g. return find()) but that seemed to cause different return type problems in this instance. I think that's what was throwing me off. Thank you for taking the time to help me.
Comment: No problem, I have had these kind of problems before.
Answer: The Either class was made for situations just like this.  See the documentation here
Usage:
Either<OneResultType,OtherResultType> result;

This avoids expensive instanceOf checks.  Return null if the object is not found.
Answer: add return null; below the while loop
Answer: This method would only keep returning false if it kept hitting the else if constantly until the while loop condition ends and you get to your "return false".
Instead of return false have return null; at the very end and in the calling method have a check to see if the returned object was null which means nothing was found


Sum of Normal Random Variables | Different Dimensions

Question: I would like to generate one random numer $single\sim N(0,1)$ and create the vector that contains only this one number: $one = [single, single, ..., single]$ . Later, I would like to combine with vector of multiple random numbers $several \sim N(0,1)$ using $weight$:
$New=weight*one+\sqrt(1-weight^2)*several$
Is it $New\sim N(0,1)?$
I thought so, because both $one$, and $several$ are random and generated from normal distribution. However, right now, I am not so sure. $one$ is in fact a vector of the same values so it might be treateat as constant here.
I tried to use R code to check below:
<code>results<-matrix(ncol=4,nrow<-0)

colnames(results)<-c("sd(Normal)", "mean(Normal)", "sd(New)", "mean(new)")

for(i in 1:100000){

  set.seed(i)
  one<-rnorm(1,mean=0,sd=1)
  several<-rnorm(4000, mean=0, sd=1)

  weight<-0.20

  NORMAL<-several #this is N(0,1)
  NEW<- weight*one+sqrt(1-weight^2)*several #not sure if N(0,1)

  vector<- c(sd(NORMAL), mean(NORMAL), sd(NEW), mean(NEW))
  results<- rbind(results, vector)
}

colMeans(results)*100 #BP
sqrt(1-weight^2)*100 #BP
</code>
Results:
<code>      sd(Normal)   mean(Normal)      sd(New)       mean(new)
      99.99548850  -0.00423462       97.97516937   0.04152757
</code>
The results sd(New) are very similar to the $sqrt(1-weight^2)*100=97.97959$ and that raised my question about $New$ variable.
Comment: Mathematically, your question doesn't make sense until you can explain what it means to add a scalar to a vector.  Could you edit the post to clarify this point?
Comment: Thanks for your comment: I have edited to make sure we are adding vectors.
Comment: In symbols, are you asking about the distribution of the vector $(Y_i)$ where $Y_i=a X + b Z_i$ with $a,b$ constants with $a^2+b^2=1,$ $X$ Normally distributed,  $Z_i$ multinormally distributed independently of $X$?
Comment: Yes, in R set.seed(1) we have: $X=[0.7083495, 0.7083495, 0.7083495, ...], Z_i = [-0.03846413,  0.94647475, 0.84385583, ... ]$ wheras $ Y_i = [0.1039829,1.0690220,  0.9684764]$ I am not sure if $Y_i ~N(0,1)$
Answer: $New=weight*one+\sqrt(1-weight^2)*several$ change to
$$Y_{ij}=wX_i +\sqrt{1-w^2}Z_{ij}$$ where $X,Z$ follows standard normal distribution and independent from each other, and $ 0\le w\le 1$.
Let $\gamma_i = wX_i$, then $\gamma_i \sim N(0,w^2)$. Let $\epsilon_{ij} = \sqrt{1-w^2}Z_{ij}$ then $\epsilon \sim N(0, 1-w^2)$.
$$Y_{ij}=\gamma_i+\epsilon_{ij}$$ It is the random part in the mixed model.
Let see the whole picture of $Y_{ij}$. Let $i=1,...,I$ and $j=1,..., J$. Let $Y = (Y_{11} ,Y_{12},...,Y_{1J},...,Y_{i1},...,Y_{IJ})'$
$$\begin{pmatrix}
Y_{11}\\
Y_{12}\\
...\\
Y_{1J}
\end{pmatrix} = \begin{pmatrix}
1& 1 &0 &...&0\\
1& 0& 1 &...&0\\
...&...&...&...&...\\
1&0&0&...&1
\end{pmatrix} \begin{pmatrix}
\gamma_1\\
\epsilon_{11}\\
\epsilon_{12}\\
...\\
\epsilon_{1J}
\end{pmatrix}$$
$$Var\begin{pmatrix}
\gamma_1\\
\epsilon_{11}\\
\epsilon_{12}\\
...\\
\epsilon_{1J}
\end{pmatrix} = \begin{pmatrix}
w^2& 0 & ...&0\\
0&1-w^2&...&0\\
...&...&...&...\\
0&0&...&1-w^2
\end{pmatrix}$$
Following $Var(AX)=AVar(X)A'$, you can get
$$Var\begin{pmatrix}
Y_{11}\\
Y_{12}\\
...\\
Y_{1J}
\end{pmatrix} = \begin{pmatrix}
1& 1 &0 &...&0\\
1& 0& 1 &...&0\\
...&...&...&...&...\\
1&0&0&...&1
\end{pmatrix} \begin{pmatrix}
w^2& 0 & ...&0\\
0&1-w^2&...&0\\
...&...&...&...\\
0&0&...&1-w^2
\end{pmatrix}\begin{pmatrix}
1& 1 &0 &...&0\\
1& 0& 1 &...&0\\
...&...&...&...&...\\
1&0&0&...&1
\end{pmatrix}=\begin{pmatrix}
1&w^2&...&w^2\\
w^2& 1&...&w^2\\
...&...&...&...\\
w^2&w^2&...&1
\end{pmatrix}_{J\times J} =\Sigma$$
Then $Y\sim N(0, I\otimes \Sigma)$.
What you did is setting $I=1$ and $J=4000$. The sample variance of $Y_{1j}, j=1,...,4000$ is the estimate of conditional variance $Var(Y_{ij}|i=1) = Var(Y_{1j}|\gamma_1) = Var(\epsilon_{1j}) = 1-w^2$
If you want to verify the unconditional variance of $Y_{ij}$ being 1, you can set $I = 200$ and $J=20$. and re-run roue code.
Comment: Many thanks for your help - I see that you put a lot of effort into writing the answer.
I just want to clarify this point: $\Sigma = \begin{pmatrix}
1&w^2&...&w^2\\
w^2& 1&...&w^2\\
...&...&...&...\\
w^2&w^2&...&1
\end{pmatrix}_{I\times I}$ how did you get this one?
Comment: The details were added in the Answer. Need matrix skill.
Comment: All is clear now, many many thanks  user158565!


ASP.NET with Active Directory: User Credentials

Question: I am an ASP.NET newbie and creating an inhouse application (will be used by 10 users inside group).
One of the objective is to add users to Active Directory group. For audit purpose, the app-users should do the AD change with there own credentials (and not with common id created for this sole purpose).The website is hosted on Windows Server 2008 R2/IIS 7.0 and everything is in enterprise domain.
IIS Settings:
Application Pool Name: UserAppMapping, Integrated, ApplicationPoolIdentity
Authentication: ASP.NET Impersonation and Windows Authentication only are Enabled.
VB.NET Code (i have removed all error checking so I can see the actual error):
<code>Public Sub AddUserToGroup(userId As String, groupName As String, Optional GroupDN As String = "")

        Using (HostingEnvironment.Impersonate())

            Dim domainName As String = "DOM"

            Dim ou = [String].Format(CultureInfo.InvariantCulture, "dc={0},dc=myorg,dc=com", domainName)

            Dim domain = [String].Format(CultureInfo.InvariantCulture, "{0}.myorg.com", domainName)

            Using insPrincipalContext = New PrincipalContext(ContextType.Domain, domain, ou)
                If insPrincipalContext IsNot Nothing Then
                    Dim insGroupPrincipal As GroupPrincipal = GroupPrincipal.FindByIdentity(insPrincipalContext, System.DirectoryServices.AccountManagement.IdentityType.Name, groupName)

                    Dim user As UserPrincipal = UserPrincipal.FindByIdentity(insPrincipalContext, userId)

                    If insGroupPrincipal IsNot Nothing Then
                        'add user to group
                        If user.IsMemberOf(insGroupPrincipal) Then
                            LabelErr.Text = userId + " is already part of " + groupName
                        Else
                            insGroupPrincipal.Members.Add(user)
                            insGroupPrincipal.Save()
                            Label1.Text = "User added successfully"
                        End If
                    Else
                        Label1.Text = "Cannot retrieve information about " + groupName + " from Active Directory"
                    End If
                Else
                    Label1.Text = "Principal Context is Null"
                End If
                insPrincipalContext.Dispose()
            End Using
        End Using
    End Sub
</code>
`
Problem:
Everything works fine but when following lines are encountered in the code:
insGroupPrincipal.Members.Add(user)
insGroupPrincipal.Save()
The application prompts for user credentials. While I understand the code in this function is running under the context of Windows Identity "IIS APPPOOL\UserAppMapping", it will prompt for credentials which has access to Active Directory. Is there a way for app user to modify the AD groups (I am assuming the user can modify the groups directly in AD) without typing extra credentials?
If I remove "Using (HostingEnvironment.Impersonate())" from the code, it fails right away when GroupPrincipal.FindByIdentity is encountered.
The web.config is set with:
authentication mode="Windows"
identity impersonate="true"
Thanks in advance.
Answer: Do the following.

Make sure that IIS Authentication is set to Windows Auth=enabled, Anonymous=false. This is required in addition to the web.config.

Step 2: You need an account has higher rights in AD than ApplicationPoolIndentity.

You need a Network Account to perform the AD work. Create a new network account and then in your application pool in IIS change it from ApplicationPoolIndentity to Custom Account. Then enter your new AD Account and password. (I would suggest making that AD Account password never expires)
Comment: IIS Authentication is already set to Windows Auth and ASP.NET Impersonation. Anonymous is set to False. If I create a new network account and set in application pool identity, shouldn't that account do all the writes in AD? How will then I know which app user has actually made the change?
Comment: Was a solution found?


can i cleanup buffer for some specified database instead of the entire sql server

Question: from what i know, if i execute 'DBCC FREEPROCCACHE' and 'DBCC DROPCLEANBUFFERS', the buffer of entire server will be cleanup.
i wonder if there's anyway to cleanup buffer of specified database only. therefore, query for other databases will not be affected.
Comment: No, you cannot - those are system-/server-wide commands, and there's no equivalent on a per-database basis
Answer: You can clear all execution plans from a single database using DBCC FLUSHPROCINDB(<db_id>). I'm not aware of any similar command to clear specific pages from the buffer cache.
However, you can set the database offline momentarily and then back online to clear both plan and buffer caches for a database if the situation allows for this.
Answer: Not a possibility with FREEPROCCACHE or DBCC FREEPROCCACHE
As per msdn https://msdn.microsoft.com/en-us/library/cc293622.aspx

DBCC FREEPROCCACHE This command removes all cached plans from memory
  DBCC FLUSHPROCINDB (<dbid>) This command allows you to specify a
  particular database id, and then clears all plans from that particular
  database.

db id can be fetched this way
DECLARE @intDBID INT;
SET @intDBID = (SELECT [dbid]
                FROM master.dbo.sysdatabases
                WHERE name = 'AdventureWorks');

-- Flush the procedure cache for one database only
DBCC FLUSHPROCINDB (@intDBID);


A practical way to do healthcheck for a new server?

Question: I am currently trying to do healthcheck for a new server in data center as a first QA before using by any application side.
"What is the practical way and tools to check that the server is fine to use?"
About the tools, I am looking at memtest86 to test the memory and IOzone Filesystem Benchmark.
But I hope there should be more other tests I should do and better tools than these two.
Answer: I used to do a good deal of hardware troubleshooting in large datacenters, I would recommend find a bootable Linux distribution, any will do.  Be sure to find one with a 64 bit image if you have a 64 bit CPU.  Stresslinux contains a whole suite of tools to stress your servers, and force any hardware failures out into the open.
I'm personal to the "stress" tool - it can hammer hard disk(s), memory, and processor(s).
stress
A quick note about memtest86+
This is not part of the stress suite, but obviously you know it exists.  Definitely make sure you're using memtest86+ (emphasis on +) - it handles 64 bit systems and large allocations of memory far better than the original memtest86.
Memory Testing
This will spawn n processes spinning on malloc() at 256MB each.
stress -m n &

So you would want to divide the amount of memory you have by 256MB (roughly), to hit all of it.  This will flush out any obvious errors, you'll likely see EDAC's or MCE's (depending on your processor/motherboard), or a kernel panic/hard crash.  Ideally you can let it run for a few hours to get the to heat up under load.  You can check syslog for those errors.
CPU Testing
This will spawn n processes spinning on sqrt().
stress -c n &

You'll want n to be the number of cores in your system.  The same concept here applies as far as letting it run for a while.
Disk Subsystem Testing
This requires the hard disks to be formatted in someway, if you are using RAID you'll get better results if you've already set that up prior to mounting the drives and stressing them.
Change directory to the partition/area of the disk you'd like to stress.  The more free space the better.
cd /hard/disk/partition

This will spawn n processes spinning on write() at 1GB each
stress -d 32 n &

Monitor disk IO with:
iostat -x 5

Killing Stress
To kill all stress processes, yes you can run memory, CPU, and hard disk checks simultaneously, but it makes isolating the components a bit tougher:
pkill -9 -f stress

Verifying Your Tests
Obviously you run all these things and you need to see some kind of result or confirmation.
Memory/CPU
You'll just want to check syslog for things like, Machine Check Exception (MCE), Error Detection and Correction (EDAC), Out of Memory (OOM), etc.
zgrep -i -P ".*(error|warn|fail|panic|edac|mce|exception|oom-killer|oops).*" /var/log/kern.log* /var/log/dmesg /var/log/daemon.log*

Disk Subsystem
This is probably the easiest to detect more than any other component, smartctl is usually installed on most *NIX operating systems, it's a part of the smartmontools package.  The following command requires root access:
The /dev/sda aspect may need to change if you have multiple disks or a RAID controller.
sudo smartctl -a /dev/sda

Below is some sample output of the full command, I'll specify what you should really be looking for farther down the page.
SMART Attributes Data Structure revision number: 16
Vendor Specific SMART Attributes with Thresholds:
ID# ATTRIBUTE_NAME          FLAG     VALUE WORST THRESH TYPE      UPDATED  WHEN_FAILED RAW_VALUE
1 Raw_Read_Error_Rate     0x000b   099   099   016    Pre-fail  Always       -       65537
2 Throughput_Performance  0x0005   136   136   054    Pre-fail  Offline      -       95
3 Spin_Up_Time            0x0007   121   121   024    Pre-fail  Always       -       320 (Average 304)
4 Start_Stop_Count        0x0012   100   100   000    Old_age   Always       -       18
5 Reallocated_Sector_Ct   0x0033   100   100   005    Pre-fail  Always       -       0
7 Seek_Error_Rate         0x000b   100   100   067    Pre-fail  Always       -       0
8 Seek_Time_Performance   0x0005   144   144   020    Pre-fail  Offline      -       28
9 Power_On_Hours          0x0012   098   098   000    Old_age   Always       -       15407
10 Spin_Retry_Count        0x0013   100   100   060    Pre-fail  Always       -       0
12 Power_Cycle_Count       0x0032   100   100   000    Old_age   Always       -       18
192 Power-Off_Retract_Count 0x0032   100   100   000    Old_age   Always       -       37
193 Load_Cycle_Count        0x0012   100   100   000    Old_age   Always       -       37
194 Temperature_Celsius     0x0002   253   253   000    Old_age   Always       -       22 (Min/Max 15/31)
196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       0
197 Current_Pending_Sector  0x0022   100   100   000    Old_age   Always       -       0
198 Offline_Uncorrectable   0x0008   100   100   000    Old_age   Offline      -       0
199 UDMA_CRC_Error_Count    0x000a   200   200   000    Old_age   Always       -       0

The main attributes you want to be aware of are the following:
Reallocated_Sector_Ct
This should be less than 1000 in general.
These are sectors that had to be reallocated to another part of the hard disk because the previous sector wasn't healthy.
Temperature_Celsius
This should be less than 55, the command itself will have a min/max in some cases - but sub 55 is where we saw healthy disk operation.
Current_Pending_Sector
Must be 0.
Offline_Uncorrectable
Must be 0.
UDMA_CRC_Error_Count
Should be 0, a few are okay (less than 100).
Also note these can be indicative of a bad SATA/SAS cable.
There are many ways to stress and benchmark your servers, this is just a way I'm comfortable with and have had great results with.
I hope this helps!
Comment: Thanks for very nice detail answer! I will try them within a week.