Replaced my guitar E string. Now tuner shows Hi E instead of E

Question: Beginner Here. My acoustic guitar E string broke. I replaced it with another E string that ordered online.
I use Android App for tuning guitar. Now, the tuner shows Hi E, instead of E for this new string.
Did I use wrong string or I replaced it incorrectly? Why doesn't it show normal E?
Comment: Even though you're a beginner, it will be good for you if you didn't rely, like so many do, on a little machine that supposedly tells you the information you need. They're not foolproof, so why not start using your own ears, and get the idea of what each string sounds like in comparison to the one below. There are plenty of googlable examples of how to tune a guitar by comparison with 5th and 4th fretted strings. It'll set you up as someone who actually knows what tuning a guitar is all about. Serious comment.
Comment: There are two E strings on guitars. Which are you asking about? Fat or thin?
Comment: See if you tuner has a manual mode and not auto. This will allow you to choose which string you are tuning and reduce confusion. Many free apps will have this feature. Just remember to put it back in auto or select the next string after.
Comment: Not much information here, I'm hoping the online vendor didn't send you a high E string to replace the low E string, you might wish to check the string gauge of the new string against the old string gauge.
Comment: @Tim It is the thin one.
Comment: @b3ko Yes, I have just tired it manually. Results are the same.
Comment: @skinnypeacock There is nothing written about low or high E on the package of replacement strings. It is just E. And its measurement is 0.010 inch or 0.25mm.
Comment: The GuitarTuna app also shows https://youtu.be/ISWjq_4suLM?t=90 as High E. Is it high E?
Answer: Tuners don't always detect the right octave very reliably.   Tune it to whatever E it thinks it is.
It might recognise it as low E if you pluck it a bit further from the bridge, or with a softer bit of your finger.   But it doesn't really matter.  It's not as if you're REALLY in danger of tuning it a full octave high, is it!
Comment: Just make sure you don't miss by an octave; OP is a beginner, and some beginners make that mistake. +1
Comment: Bit of vague info from OP, but yes, there is a danger of tuning a string an octave higher. Seen it happen, and no, it didn't break - itself or the guitar. We guess it's the low E that's been replaced, but it's only a guess. And if it is actually tuned to high E, it's defying the laws of physics!
Comment: I guess if the 'Hi E' display was a surprise, it must be low E.


How to realize a figured bass

Question: I am arranging a Bach piece. I know, what the challenge it is to do it. But I have been able to successfully arrange Mozart and later, Beethoven, so I think I'm ready.
But here is the challenge I am running into right now. How to realize a figured bass into full chords? I know some things about figured bass realization like:

If you don't see any numbers, the chord is in root position
If you see just a 6, the chord is in first inversion
If you see a 6 and a 4, the chord is in second inversion
7 for root position, 6 and 5 for first inversion, 4 and 3 for second inversion, and 4 and 2 for third inversion when it comes to seventh chords
No accidental means you just play a diatonic chord
An accidental instead of a number means that the accidental applies to the third
A slash through a number means to raise it a half step(so Bb becomes B, E becomes F, etc.)
An accidental next to a number means that you apply the accidental to whatever interval above the bass the number corresponds to
A number with a line means you suspend the note across the chord change(whether you rearticulate or tie the suspended note is up to you)

And I know some things about voice leading like:

Avoid leaps as much as possible
When you have to leap in a given voice, either go back in the opposite direction or form an arpeggio
Avoid intervals greater than an octave between 2 consecutive voices unless necessary
Never leap by an augmented or diminished interval, ever
Resolve tendency tones(so 4 to 3, 7 to 6 if 7 isn't the leading tone, 2 to 3, 7 to 1 if 7 is the leading tone)
Avoid unequal fifths in the outer voices(perfect fifth becoming a tritone for example)
No PPI's(parallel perfect intervals)
If you have to string together dissonances, no more than 4 before a resolution, preferably fewer
Parallel thirds and sixths are okay but if you have 4 or more in a row, they start sounding dependent
No tritones or other augmented or diminished intervals between outer voices unless a diminished 7th chord is specifically called for. It will just sound too dissonant to be acceptable

How do I go from these figured bass and voice leading rules and a bass line with figures to full 4 part chords? Is there a shortcut to finding a solution for any bass line and figures?
Comment: Did Bach, in fact think along the line of chords? Maybe not, so you disecting his work may not work.
Comment: @Tim I think it's pretty clear that Bach was thinking in terms of chords even though the system we now use for harmonic analysis of Bach's music was not yet invented.  Figured bass is a shorthand chord notation, but it does not depend on the concept of chords; they are merely a convenience in describing the system in modern terms.  For a piece with no flats or sharps in the key signature, a B in the bass with a 6 written above it means that the right hand should play a D and a G.  If there are two figures, a 6 and a 5, then the right hand should play D, F, and G.
Comment: @Tim I think that Bach's music shows that he could think in many ways, one of these ways is thinking in chords. What did Bach himself say? Well, here is a quote from Bach's Clavier Figured Bass Instructions: "Each chief note has a chord, either its own or borrowed". By "borrowed" chord he means an inverted chord. So he certainly talks about chords. Here is a link to the source of the quote: https://www.scribd.com/doc/123274053/J-S-Bach-s-Clavier-Figured-Bass-Instructions
Answer: I'd say there is no short cut, except of playing Bachs figured Bach  (e.g. keyboard accompaniment of Cantatas and Chorals) and  compare it with the rules.
You will find that Bach broke the rules as the figured bass accompaniment was not always following the strict four voice-leading rules. So when you have played some accompaniments like Jesu Joy of man's desiring, Bist du bei mir, Komm süsser Tod, or the accompaniment of the violin concertos you will get the ear and understand the language.
It is the same as learning a new language: you know the grammar and the vocabulary, but there is no short cut than to speak and apply the language.
This is what I am still working on.
So it will be a long way:
http://www.bach-cantatas.com/Scores/IndexScores3.htm
http://www.bach-cantatas.com/Vocal/BWV439-507.htm

copied from:
Bach
JOURNAL ARTICLE
The Figured-bass Accompaniment in Bach's Time: A Brief Summary of Its Development and An Examination of Its Use, Together With a Sample Realization, Part I
Marla Hammel
Bach
https://www.jstor.org/stable/41640029?seq=1#page_scan_tab_contents
This quotation is not related to Bach, but you might consider it too:

Basso continuo realization can vary from simple harmonization to extensive explorations of harmony and counterpoint. A "full accompaniment" may require as many notes as the fingers can accommodate, and in such cases the rules forbidding consecutive fifths and the like are waived, except as they apply to the two outside (bottom and top) parts.

https://www.britannica.com/art/basso-continuo
Answer: One hint: The figured bass realization doesn't need to have full four-part chords all the time.  Most written-out realizations are far too busy and detract from the other parts rather than supporting them.  Also, a realization that works well for harpsichord, or piano, or organ probably won't work nearly as well for either of the other two instruments.
I have a copy of Continuo Playing According to Handel, which I have found most informative.
But, obligatory snarky comment:

How to realize a figured bass into full chords?

Hire a well trained harpsichordist.

How to realize a figured bass


Check if passwordless access has been setup

Question: I would test via a python script whether a passwordless ssh login has been setup or not.
If i run the normal ssh command then it will wait to accept the password for some amount of time.
Is there a way where the ssh command should return an error as soon as ssh asks for a password.
Is it possible to achieve this?
Answer: The ssh command accepts quite a large set of options, so assuming that your Python code is calling shell commands do the following :
ssh -oNumberOfPasswordPrompts=0 <host> "echo hello"

This will instantly fail if the keys have not been setup, and instantly complete if they have, which is the reason for the command being passed to the host. This gives you a simple test.
Comment: I guess `-oBatchMode=yes` also works. I wonder if BatchMode also skips other human interventions.
Answer: paramiko will raise an AuthenticationException if you don't pass a password to the SSHClient's .connect() method and a working key cannot be found.
Answer: You can set a parameter to ssh command to only try the public key in the  authentication process and set a batch mode with a command that always return true when the command is executed in the remote host. With that approach you can capture the exit code in the var $? and do some decision.
ssh -o PreferredAuthentications=publickey -o BatchMode=yes <host> /bin/true &> /dev/null
if [ $? -eq 0 ]; then
    #DO SOMETHING, THE CONNECTION WAS SUCCESSFUL
else
    #CONECTION DENIED
fi

You can capture custom output to a variable by finding the "Permission denied" in the verbose output of the ssh command as is in the following code.
PERMISION=$([ ! -z "$(ssh -v -o PreferredAuthentications=publickey -o BatchMode=yes <host> /bin/true 2>&1 | grep " Permission denied")" ] && echo "GRANTED" || echo "DENIED")
if [ $PERMISION == "GRANTED" ]; then
    #DO SOMETHING, THE CONNECTION WAS SUCCESSFUL
else
    #CONECTION DENIED
fi

I hope this find you useful .
Answer: You may use the PasswordAuthentication option

PasswordAuthentication
  Specifies whether password authentication is allowed. The default is ''yes''. https://linux.die.net/man/5/sshd_config

Python code
import subprocess
completed_process = subprocess.run(
    """ ssh -o PasswordAuthentication=no user@localhost 'hostname' """,
    shell=True
)
assert completed_process.returncode == 0


Declare Instance of Class with Dynamic Name

Question: So I have created a Class called SnakeItem, I want to create a new instance of the snake item when the snake grows, they follow a naming convention of snake_Piece_[NUMBER]. There is already snake_Piece_0 and I want to declare a new instance in the code. I'm not sure how to put it...
SnakeItem snake_Piece_0;
public game_Window()
{
    InitializeComponent();
    snake_Piece_0 = new SnakeItem(Resource1.Black, 0, 0);
}

Then in this function, I want to create it. (after snake_length++:) I need to name to increment so it follows the snake_length Variable. i.e. if snake_length = 1 then it will create a piece with the name snake_Piece_1.
 private void fruit_Collision()
 {
    if (snake_Piece_0.Top == Fruit_Item.Top && snake_Piece_0.Left == Fruit_Item.Left)
    {
       snake_Length++;
    }
  }

I'm not sure what I can say if it's not possible I would have to declare all 400 snake pieces beforehand which is what I'm trying to avoid.
Comment: *"if its not possible I would have to declare all 400 snake pieces before hand"* .. well, or use an array or a list to insert the `SnakeItem` objects into and then access them by their index.
Comment: Im not sure how I would do that, could you post a full response.
Comment: Google for some C# tutorial (with focus on collections), and spend some time with it. It will pay off...
Comment: I actually read that thread but I didn't understand it and I thought it was about something else.
Answer: This is a common thing that beginners do - trying to dynamically create new variables with new names. I tried to do this too, until I learned about Lists.
Lists are objects that can store a variable number of objects. Here is how you can create an empty list of SnakeItem:
List<SnakeItem> snakeItems = new List<SnakeItem>();

You can add, access, and delete items in the list. Here are some examples:
snakeItems.Add(new SnakeItem(Resource1.Black, 0, 0)); // add a new item to the list
snakeItems[0] // access the first item in the list. 0 is the first, 1 is the second, etc.
snakeItems.RemoveAt(0) // remove the first item of the list

Basically, whenever you want to create a new "variable name", just Add a new item to the list:
    if (snakeItems[0].Top == Fruit_Item.Top && snakeItems[0].Left == Fruit_Item.Left)
    {
        snakeItems.Add(...);
    }

As you can see, snake_Length is not needed any more! You can access how many snake items there are using .Count. Replace all the snake_Length with snakeItems.Count.
Learn more about lists here.


Combine 2 Variables in JavaScript

Question: how i can combine the 2 variables torso and comb to access the the string in the array correctly
var comb = new Array("MT 1.1","MT 1.2","MT 1.3","MT 1.4","MT 1.5","MT 1.6","MT 1.7","MT 1.8","MT 1.9","MT 2","MT 2.1","MT 2.2");

var torso = 2;
var num = comb[+torso+];

Comment: Do you know how to access an array element without a variable? (i.e. directly using the index).
Comment: torso will submit an number, that i want to use as index to access the the position in the array
Comment: why are you putting `+` around `torso` in your statement?
Answer: use the torso variable as index to access an item from the comb array:
var num = comb[torso];

With the value 2 for torso, num will contain the third item from the array; "MT 1.3".

Combine 2 Variables in JavaScript


Scala - Generic implicit with lower bound

Question: Consider the following:
class Super
class Sub extends Super

implicit val implicitOption: Option[Super] = None
def f[A, B >: A](a: A)(implicit i: Option[B]) = println("It worked")

If I call f(new Super), it works fine, but f(new Sub) gives me a compilation error (could not find implicit value for parameter i).
Why can't implicitOption be used as the implicit parameter when A = Sub?
Comment: The compiler hasn't any input to infer `B`. What exactly do you want to achieve?
Comment: Thanks for your help, I think I see what you mean. I started off with a simpler problem and overcomplicated things with the `B` parameter. Solved it a different way now, though.
Comment: Ok, I think I see what you're getting at but could you elaborate?
Comment: Depending on what you really want to do / really need to solve. We may come with a workaround.
Answer: In this case, compiler needs some help figuring out which B to use. So
f[Sub, Super](new Sub)

works just fine.
--- Old answer - still relevant but approaches from different perspective --
Because Option is covariant - which means you can pass Option[Sub] where Option[Super] is expected, but not the vice versa.
To make this work, you'd need a contravariant class (let's call it ContraOption for now) - so that you can pass ContraOption[Super] where ContraOption[Sub] is expected.
Continuing on your example:
class Super
class Sub extends Super

implicit val implicitOption: Option[Super] = None

sealed abstract class ContraOption[-A]
case object ContraNone extends ContraOption[Any]
case class ContraSome[A](value: A) extends ContraOption[A]

implicit val implicitContraOption: ContraOption[Super] = ContraNone

def f[A, B >: A](a: A)(implicit i: Option[B]) = println("It worked")
def f2[A, B >: A](a: A)(implicit i: ContraOption[B]) = println("It worked 2")

f(new Super)  // It worked
f2(new Sub)   // It worked 2

Note that both trying to do f(new Sub) (as in your example) and f2(new Super) fails compilation with "implicit not found".
For more fundamental understanding of co- and contravariance, please refer to the docs. But simply put, covariant generic class "follows" the ancestor-descendent links, while contravariant classes reverse the direction. To illustrate (in pseudo-scala):
class Super
class Sub extends Super

class Covariant[+A]
class Contravariant[-A]

This gives us the following relationships:
Sub <: Super
Covariant[Sub] <: Covariant[Super]
Contravariant[Super] <: Covariant[Sub]

Comment: In my example, `Option[B]` is expected where `B >: A`. So wouldn't `None: Option[Super]` be accepted when `A` is `Sub`?
Comment: You're right, updated (more like "rewritten, but kept the old one for future reference" :))
Answer: The solution turned out to be to move the parameter B from f to implicitOption by changing their definitions like this.
implicit def implicitOption[B <: Super]: Option[B] = None
def f[A](a: A)(implicit i: Option[A]) = println("It worked")

Comment: This is very different from the question. Now `implicitOption` is divorced from and unrelated to `Super` and `Sub`, and the type parameters to `implicitOption` and `f()` are now completely independent, unrelated, and unbounded.
Comment: Fair point. I've edited the type parameter to `implicitOption` to connect it to `Super`.


Server 2012 new AD domain next to existing SBS domain

Question: I've got the following scenario.

Server 2003 SBS with an active directory domain: COMPANY.LOCAL
Server 2012 Standard 2012 with a workgroup: WORKGROUP
No computers in the company are  part of the existing SBS domain (COMPANY.LOCAL)

We have some users who access shares on the SBS server using local admin account.

I would like to create a new domain on the 2012 server without joining it to the existing SBS domain (COMPANY.LOCAL)  or  migrate any user or groups.
Would it be possible to install AD services onto the 2012 server and create a domain called: ad.company.co.uk?
One word of warning on this
When you get to the point of choosing your netbios name, you won't be able to choose COMPANY as this will already be taken by your SBS server.
Answer: Yes that should be absolutely fine, you can have multiple domains on the same network without any issues.
You may want to take care with your DHCP/DNS configuration so that domain name resolution works correctly but without any more details on what you plan to do with the domain its hard to give any more concrete advice


Map User from User document to FirebaseUser in Java Android Studio

Question: it was created a user document in cloud firestore database while registration. User are able to login if comparison is true. problem is firebaseuser return null with FirebaseAuth.getInstance().getCurrentUser() as it's not recognized a current login user.
My question is, is it possible to map a user from user document to a firebase user?
I know I can use firestore built-in authentication. but is not a good time for me to change with my deadline.
this is login code
<code>            db.collection("users")
                    .whereEqualTo("UserName", tools.editText.get(R.id.username_txt))
                    .whereEqualTo("Password",tools.editText.get(R.id.password_txt) )
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete( Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                                if(task.getResult().size()>0) {
                                    Log.w("Rabby","success");
                                    Intent i=new Intent(LoginActivity.this,HomeActivity.class);
                                    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(i);
                                }else
                                {
                                    Toast.makeText("invalid user").show();
                                }
                            } else {

                            }
                        }
                    });
</code>
after user login, I cannot get a current user coz firebase.getcurrentuser() does not know the login user. it is possible to map user to firebase user?
anyone can suggest me?
a million thanks
Comment: Please check the duplicate to see how you can check if a user already exists.
Answer: check if you enabled cloud firebase firestore database for more details follow the link
https://codelabs.developers.google.com/codelabs/firestore-android/#0
then used following line

StorageReference storageReference =
  FirebaseStorage.getInstance().getReference(); FirebaseFirestore db =
  FirebaseFirestore.getInstance();

which create firebase firestore instance. Then used following getUid() to get current user id.

String u_id = FirebaseAuth.getInstance().getCurrentUser().getUid();
Comment: as FirebaseAuth.getInstance().getCurrentUser() return null, couldnot get getUid() as well


What statistical distribution would best capture a set of Wordle outcomes?

Question: Wordle is a simple and popular word game. It is based on an older game, and has recently gone viral and attracted attention. It is available in several languages and the original site (now owned by The New York Times is here)
The rules are simple. Each day, there is a secret target five letter word. You guess a five letter word, and you get hints of which letters in your guess belong to the target word and whether the letter is in the same position. You have six tries after which the letter is revealed. That is, the outcome is the number of tries, which we can index by $1, ..., 6$ and assign the $7$ to the failure to guess the word.
Let's say I play Wordle 100 times and I want to model the distribution of outcomes. Each game yields an outcome $y \in \{1,...,7\}$. In order to simplify the question, I am assuming that failing and succeeding in seven tries is the same. I am not so much interest in Wordl but on the statistical distribution of this outcome.
If we were just flipping a coin until seeing a Head, we would have a geometric distribution. But in Wordle each try gives hints and changes the probability: it is close to impossible to guess the word in one try and pretty common to guess the word in 4 to 6 tries, and the geometric distribution does not capture this.
How would you model this distribution? It seems like "cheating" to try to fit something more flexible like a Negative Binomial just to fit the data. Is there a distribution that generalizes the geometric distribution with a probability parameter that changes monotonically after ever try?
Just to clarify, I don't care about linking the peculiar characteristics of World itself. I Just want something more flexible than the geometric distribution, without having to go full non-parametric and model the whole thing using seven parameters.
Comment: (1) Failing to guess the word in 6 tries might reasonably be equated to guessing it in 7 or more tries; not to guessing it in precisely 7. (2) You seem to be undecided between asking about a mechanistic model of the outcome of a stochastic process, in which case you'd need to describe how the word to guess is selected, & the algorithm that's playing the game; & asking about an empirical model of outcomes achieved by actual (human) players, in which case a (censored) negative binomial distribution doesn't sound like cheating at all.
Comment: Also it'd be helpful to at least outline the game & link to the detail of the rules, rather than assume all potential answerers are already familiar with it.
Comment: Maybe something like a `Dirichlet-Multinomial` might help... Doesn't quite get to the monotonicity that you mentioned.
Comment: (3) "Is there a distribution that generalizes the geometric distribution with a probability parameter that changes monotonically after ever try?" - any distribution with support over the integers having monotonically increasing hazard. A negative binomial distribution with 'shape'/'size' parameter greater than one would in fact meet this criterion - though now I've played the game a little it's clear you don't want a distribution *more* dispersed than a Poisson.
Comment: @Scortchi a good strategy in the game is to have a second and possibly also third guess with ruled out words in order to gather more information about additional letters. Say the first guess 'STORY' and you get the 'ST...' correct. Then instead of guessing something with the same letters again e.g. 'STEEP' it would be better to replace the already known first 'ST' with other letters like 'BLEEP'. So I would say that the 'hazard' in the second and third steps is probably lower. (Unless there would be an incentive to guess the word as fast as possible, but the goal is to guess within six).
Comment: I will add some edits in response to these comments.
Comment: (4) Note that the constraint of monotonically increasing hazard rests on the assumptions that (a) the compositor has an equal chance of picking any target word from the lexicon, & (b) the player never guesses words that have already been ruled out (to do so is legal, & sometimes not unreasonable).
Comment: @SextusEmpiricus: Yes, you're very unlikely to guess right from just ST___, so it'd make sense to explore with the full 6 letters rather than only four. Even if you were prepared to take risks to guess the word in fewer tries, there's a non-negligible chance of getting it in three with this approach.
Answer: The categorical distribution is the most general and has parameters to assign a probability to every single outcome.
$$\begin{array}{rcl}
P(y = 1) &=& p_1\\
P(y = 2) &=& p_2\\
P(y = 3) &=& p_3\\
P(y = 4) &=& p_4\\
P(y = 5) &=& p_5\\
P(y = 6) &=& p_6\\
P(y = 7) &=& p_7\\
\end{array}$$
When you are looking for something like a geometric distribution or other distribution with less parameters, then there is some continuous mechanism, like a coin flip for each turn, and you can use the properties of that coin flip to parameterize the distribution.
As Scortchi mentions in the comments, such a mechanism is not necessary in order to use a parametric distribution. But these parametric distributions tend to relate to some mechanism and when you apply the parametric distribution then you could see the related mechanism as a model for the underlying mechanism of the distribution.
For the wordle outcomes it is unlikely that you can generate a distribution based on a single parameter or few parameters. There are too many factors and effects in order for the distribution to be easily modelled by a few parameters.
You have many mechanisms that are not much related

The probability to make the first guess

The probability to make the second and third guess based on how the first few hints worked out.
(In my personal strategy these probabilities are zero. Even if I would have only one letter left over to guess, then I would still try a different wordt that incorporates multiple letters)

The probability to make it in the fourth or fifth guess with more hints. Depending on how well the initial words match one can guess in the fourth or fifth. But I don't think that these can be modelled with only a single parameter.

The probability to not guess after six.
If the algorithm to guess the word fails. With a good strategy the probability should be nearly zero. This probability requires a seperate parameter and is unrelated to the probabilities to guess in 4 or 5 turns.

These mechanisms are much unrelated and can not be easily combined and modelled by a smaller set of parameters.
It is also difficult because guessing words leads to an algorithm that is not very uniform. It depends on what you get. If you would instead have something like mastermind then you could create something like a parametric distribution (e.g. the probability to guess in turn $k$ as function of the length and number of colours).
Comment: @SextusEmpiricus: I wouldn't necessarily have qualms about modelling these outcomes with a categorical distribution, but the assertion that a model with fewer parameters would require a mechanistic justification seems too strong. People use models all the time on no stronger grounds than that they're constrained/flexible in roughly the right ways & fit the observed data pretty well.
Comment: @Hernan for such a small amount of categories I see little problems in using a full parametric model. But maybe you mean to do something else. You say "I don't care about linking the peculiar characteristics of Wordle itself", but could you you explain what you are trying to do. Is your problem about Wordle? Why do you want to have "something more flexible than the geometric distribution". What is the point?
Comment: @Hernan: There are in effect six parameters: as the probabilities must sum to one, $p_7$ can be written as $1-\sum_{i=1}^6 p_i$. The structure you've specified amounts not to a further reduction in parameters but to a constraint on the values they can take
$\frac{p_i}{\sum_{j=i}^7 p_j}$ < $\frac{p_{i+1}}{\sum_{j=i+1}^7 p_j},\ i=1, \ldots, 6$.
Comment: @Hernan: As I've already commented, *any* discrete distribution can be looked at as "a sequential fail/success trial with changing probabilities". You could stipulate *how* they change, say $\log \Pr(X=x) - \log \Pr(X>x) = \alpha + \beta x, x=0,1,\ldots$, & the distribution thus defined could be a good or a bad fit to the observed data.
Comment: Thanks for the answer. This is what I meant with "without having to go full non-parametric".  There is a bit more structure to the problem that somehow should constrain the probabilities and would not require seven parameters.
Comment: I see, I missed that clarification.
Comment: The problem is more general than Wordle itself. It is the problem of a sequential fail/success trial with changing probabilities. It could be a new drug development, an innovation context, geological search. Every attempt provides information and makes a success in the following attempt more likely.
Comment: @Hernan I think I do not understand this clearly. Is the question about Wordle or not? There are a lot of different type of discrete distributions with changing success probabilities. Do you want a list of those?
Answer: The probability models being suggested seem to depend on considering the selection of letters as equally likely. This does not seem very realistic to me. The word choice for #1 comes from the 26 characters in the alphabet, letters 1, 2, 3, 4, 5.
Vowels a,e,i,o,u and y have an order from most to least likely and consonants have a similar order. This to me would be the starting point.
Comment: "The probability models being suggested" which are these and how do they make the consideration of equally likely letters?
Comment: It's hard to square this with what's known about the game.  The target word is chosen from a relatively small dictionary and the frequencies of letters in the probe words are determined as much by the game strategy and history as anything; they are rather unlike the frequencies of letters in common English texts, for instance.
Comment: This does not provide an answer to the question. Once you have sufficient [reputation](https://stats.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](https://stats.stackexchange.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/324411)
Comment: I have played Wordle 162 times with 6 fails. My distribution is (1,0), (2,9), (3,36), (4,57), (5,41), (6,13), (7,6). Mean = 4.19, Mode = 4.00, Median = 3.64. Chi-Square? Looks like it could be and model parameter might be function of attempts.


How to I properly measure the network performance of SQL Server across a WAN?

Question: We're in the process of migrating a number of servers to a different data center.  As a stop gap measure, we've moved a set of web servers to the new data center and have left their supporting SQL Servers in our existing data center.  The two are connected across a WAN link via VPN.
How do I properly measure the impact of this move on network performance and utilization?
My end goal is two fold:

To assess the impact on end-user performance of the websites
Determine if we need to spend more on a larger pipe
Answer: Sorry, if you weren't doing it before, you have absolutely no way of knowing the impact after. You would only have the "after" numbers.
That said, you should measure it from the front-end using a tool that acts like a user, logging into the site and measure the time to complete specific operations. That's the approach that most "performance monitoring" suites take. Or you could have your web application keep its own log of the time that it takes to perform SQL queries and transactions, but you'd have to write that into it and keep the data somewhere.
Also - the typical problem with a WAN link between app and DB is latency, not available bandwidth, so buying a bigger pipe might get you absolutely nothing except a bigger bill. But that's really easy to figure out now - run NTOP or NetFlow or something on your WAN device (or even your web servers) and see how much bandwidth is being used by the SQL protocol.
Answer: What is your aim here? Are you trying to measure speed to compare different links / sites? Or are you studying whether or not something performs adequately for your needs?
If the former, then as mfinni says, if you don't have the "before" figures then you won't have anything to compare the "after" figures with. Simple as that.
If the latter, then simply create a fair 'Service Level Agreement' for performance and availability based on what users need to the changes, and just measure further performance and availability against the SLA.


Intervals of Sets

Question:
Suppose $S$ is a set with the property that $|x-y| \geq 1$ for any two
  different elements $x$ and $y$ of $S$. Show that an interval $(a,a+1)$
  can contain at most one element of $S$. Does this result change if a
  half-open or closed interval is used instead of an open interval?

I have no clue where to start with this.
Comment: Perhaps you meant $|x-y|>1$?
Comment: @grand_chat no it should be |x-y|>=1 which is the same as |x-y|>0
Comment: I feel there's a lot of confusion. What are the elements of $S$?
Comment: If $x = .5$ and $y = .6$, $|x-y| > 0$, but $|x-y| \not\geq 1$.  Do you want $S$ to be a set of integers?
Comment: X and y are elements of S
Comment: @D_S I'm not sure. My book doesn't specify, but possibly
Comment: $|x-y|$ being $\geq 1$ is clearly not equivalent to $|x-y| > 0$, as my example shows.  Unless $S$ has some additional property you haven't mentioned, the thing you're trying to prove is impossible.
Comment: Then assume |x-y|>=1
Comment: X and y are elements of S – britgirl5 ... what is $S$???!!! Positive natural numbers? Complex numbers? Real numbers? Integers with exactly 42 different prime factors?
Answer: Try drawing a picture.  The elements of $S$ are at least one unit apart.  So naturally there can't be two elements of $S$ within a the space of one unit.
Formally, suppose $x \in (a,a+1)$, with $x \in S$.  If $y$ is another element of $S$ which is also in $(a,a+1)$, we want to show that actually $x = y$.  If this is not the case, then one of these numbers has to be less than the other, say $x < y$.  So we have $$a < x < y < a+1$$ which implies that the difference $y-x$ is less than the difference between $(a+1)$ and $a$ (do you see why?).  But the difference between $(a+1)$ and $a$ is one.  Thus $|y-x| < 1$, contradiction.

Intervals of Sets


WPF window in a main window

Question: I have few WPF windows.
When I want to open a new window, I will close the current one, and load a new one:
ProductMain productMain= new ProductMain();
productMain.Show();
this.Close();

I know you can put user control into window.
Can I load the window in a main window?
Thank you.
Answer: You can do something like that by setting the Window's owner property. To get the main window use:
Application.Current.MainWindow

After that, you can set the owner of the ProductMain window:
ProductMain productMain= new ProductMain();
productMain.Owner = Application.Current.MainWindow;
productMain.Show();

WPF window in a main window


How to call default node validation functions

Question: I have a custom node-creation form for which I have my own validation function. How can I make sure that after my validation function the form goes through the same validation that it would have done on the original node-creation form?
Some thing like node_validate looks like the kind of thing I need, but it works on $node objects rather than forms.
The order of operations I perceive to be the best is

On submit run custom validation
If custom validation passes run the normal node validation
If node validation succeeds insert values in the database

Is that a good and Drupal way?
Comment: Apparently `node_validate()` is useless on a custom form because the errors get displayed but aren't acted on.  There doesn't seem to be a way to catch the errors, even with `form_get_errors()`.
Answer: If your form has a structure similar to the one used for the node edit form, then you can use node_validate(), which is called from the form validation handler for the node edit form.
function node_form_validate($form, &$form_state) {
  node_validate($form_state['values'], $form);
}

node_validate() converts the first argument in an object using the following code.
  // Convert the node to an object, if necessary.
  $node = (object) $node;
  $type = node_get_types('type', $node);

Your form validation handler's code should be similar to the following one.
function mymodule_form_validate($form, &$form_state) {
  // Run your validation code.
  node_validate($form_state['values'], $form);
}

As general rule, the validation code should go in the form validation handler. If the form validation handler set any error, the form submission handler is not called, and the user is returned to the form to correct what is wrong in the data that has been submitted.
Comment: I was surprised that I could pass `$form` to `node_validate()` when it's expecting a `$node`.
Comment: `$form` is necessary for `node_validate()`, as it is the parameter required from `hook_validate()`, and `hook_nodeapi('validate')` (`hook_node_validate()` in Drupal 7), which are invoked by `node_validate()`.
Comment: CAN YOU say how to do it in drupal 7
Answer: node_validate() will solve the problem.  The original validation process will not be affected.


Split the string in a list and match the last splitted string in python

Question: I have a long list of this
| 0x60000000 | _loc_NO_BOOL_CONST_GROUP
| 0x60000020 | _loc_NO_BOOL_GROUP
| 0x60000020 | _loc_NO_BOOL_TEXT_GROUP
| 0x6000ffe0 | _loc_NE_BOOL_GROUP
| 0x6000ffe0 | _loc_NE_BOOL_TEXT_GROUP
| 0x60010000 | _loc_NO_FIXED_DATA_GROUP
| 0x60013dc0 | _loc_NE_BOOL_CONST_GROUP
| 0x60013dc0 | _loc_NE_FIXED_DATA_GROUP

I need to split _loc_NO_ and _loc_NE_ and have to match splitted LAST STRING , if
match found, return the corresponding value.
suppose in _loc_NO_BOOL_CONST_GROUP we splited _loc_NO_ and last string is BOOL_CONST_GROUP
similary in _loc_NE_BOOL_CONST_GROUP we splited _loc_NE_ and last string is BOOL_CONST_GROUP
both the string is matching so now, I have to return the corresponding value i.e. "0x60000000" and "0x60013dc0"
so the output should be like:
BOOL_CONST_GROUP = first address value (i.e. 0x60000000), 2nd address value (i.e. 0x60013dc0).
likewise BOOL_TEXT_GROUP = first address value, 2nd address value
Comment: What do you mean by _this_, is it a `text file`, `iostream` or `string` data ?
Comment: @sushanth yes ,a text file
Comment: What is that you have tried so far & where is it you have got stuck ?
Answer: To my mind this is a good place to use regex. Here's a full working solution with some additional restraints inferred from your examples.
Inferred rules:

you're looking for valid hex values which in this case should only be lowercase
the instruction is the last item on each line in your data file
your data is in a datafile.txt

import re
from collections import defaultdict

strings_to_find = ['_loc_NO_', '_loc_NE_']

pat = re.compile(
      r'\| (?P<location>0x[0-9a-f]{8}) ' +
      r'\| (?P<instruction>%s)' % '|'.join(strings_to_find) +
      r'(?P<instruction_detail>.*?)$',
      re.MULTILINE | re.DOTALL)

with open('datafile.txt', 'r', encoding='utf-8') as infile:
    data = infile.read()

results = defaultdict(list)

matches = pat.finditer(data)
for m in matches:
    results[m.group('instruction_detail')].append(m.group('location'))

for k, v in results.items():
    print(k, v)

Comment: I don't follow. Are you saying this doesn't work exactly as presented? Is that because you're needing to group the outputs?
Comment: the last 4th line of inferred rule is  output should be like:
BOOL_CONST_GROUP = first address value (i.e. 0x60000000), 2nd address value (i.e. 0x60013dc0).

likewise BOOL_TEXT_GROUP = first address value, 2nd address value..  i need these two values for the further calculation.
Comment: updated to reflect your grouping by instruction_detail


How to deal with an SVM with categorical attributes

Question: I have a space of 35 dimensions (attributes). My analytic problem is a simple classification one.
Out of 35 dimensions, more than 25 are categorical and each attribute takes more than 50+ types of values.
In that scenario, introducing a dummy variable also will not work for me.
How can I run an SVM on a space which has a lot of categorical attributes?
Answer:
If you are sure the categorical attribute is actually ordinal, then just treat it as numerical attribute.
If not, use some coding trick to turn it into numerical attribute. According to the suggestion by the author of libsvm, one can simply use 1-of-K coding. For instance, suppose a 1-dimensional category attribute taking value from $\{A,B,C\}$. Just turn it into 3-dimensional numbers such that $A = (1,0,0)$, $B = (0,1,0)$, $C = (0,0,1)$. Of course, this will incur significantly additional dimensions in your problem, but I think that is not a serious problem for modern SVM solver (no matter Linear type or Kernel type you adopt).
Comment: Isn't creating k-1 dummy variables enough for a k level categorical variable? eg A=(1,0,0), B=(0,1,0) here, skipping (0,0,1)?
Comment: Interesting! The "recursive partitioning" sounds a (binary) tree to me. Any difference between these two ideas? Besides, SVM is already able to deal with continous feature, why shall we turn it to bins (again, categorical data) ?
Comment: +1 This is what I was going to say, as well! As an aside, I'd also add that recursive partitioning is sometimes used to identify where to best make cuts in continuously-valued features, to partition them into bins.
Comment: follow up question: is no additional scaling required of the dummied 0-1 data?
Comment: @Outlier It should be A=(1,0), B=(0,1), C=(0,0). I don't think u need the third column


Descobrir qual número de 1 a N está faltando em uma lista com N - 1 números

Question: Escreva uma função que, dada uma lista com N − 1 inteiros numerados de 1 a N, descubra qual número inteiro desse intervalo está faltando.
Entrada: O parametro de entrada é uma lista L de tamanho N − 1 contendo numeros inteiros (não
repetidos) de 1 a N.
Saída: A função deve retornar o número inteiro x que pertence ao intervalo [1, N] mas que não
pertence a lista de entrada L.
Exemplos
Entrada: [3,1] ; Saída: 2
Entrada: [1,2,3,5] ; Saída: 4
Entrada: [2,4,3] ; Saída: 1
    def quebracabecas(lista_pecas):
        i = 1
        while i < len(lista_pecas):
            if i not in lista_pecas:
                return
            contador += 1
        return lista_pecas

Comment: Importante você [edit] sua pergunta e explicar de maneira objetiva e pontual a dificuldade encontrada, acompanhada de um [mcve] do problema e tentativa de solução. Para aproveitar melhor o site, entender e evitar fechamentos e negativações vale a pena entender [O que é o Stack Overflow](https://pt.meta.stackoverflow.com/q/7256/70) e ler o [Guia de sobrevivência (resumido) do Stack Overflow em Português](https://pt.meta.stackoverflow.com/q/8089/70).
Answer: Dadas as restrições do problema e o fato de que não é preciso validar a lista (ou seja, posso confiar que os números estão entre 1 e N e a lista sempre tem N - 1 números e não há repetidos), dá pra fazer de um jeito "esperto".
A soma de todos os números entre 1 e N se dá pela fórmula da soma da PA: N * (N + 1) / 2.
Sendo assim, eu posso calcular a soma da PA (ou seja, de todos os números de 1 a N), e deste valor eu subtraio a soma dos elementos da lista. O resultado será o número que está faltando:
def quebracabecas(lista_pecas):
    n = len(lista_pecas) + 1
    somatotal = n * (n + 1) // 2
    return somatotal - sum(lista_pecas)

print(quebracabecas([3, 1])) # 2
print(quebracabecas([1, 2, 3, 5])) # 4
print(quebracabecas([2, 4, 3])) # 1

Como a lista tem N - 1 números, basta somar 1 ao tamanho dela para obter o N.
Depois obtenho a soma de todos os números de 1 a N, usando a fórmula já citada (só usei o operador de divisão inteira // para que o resultado não seja um float, até porque no caso da soma da PA é garantido que o resultado é inteiro então não há perigo de haver arredondamento indevido).
Depois basta subtrair a soma dos elementos da lista (obtida com sum).

Outra alternativa (menos eficiente) é ordenar a lista e depois ver qual está faltando:
def quebracabecas(lista_pecas):
    valores = sorted(lista_pecas)
    for i in range(len(valores)):
        if i + 1 != valores[i]:
            return i + 1 # valor não corresponde à posição, retorna
    # se percorreu todos é porque o último é o que falta
    return len(valores) + 1

Após ordenar a lista, basta ver se o primeiro elemento é 1, o segundo é 2, etc. O que não corresponder à posição é o que está faltando.
Answer: Eu faria assim usaria um criaria um set com o range do seu array de entrada, e usaria ele para conferir qual item esta faltando, o big O nao é muito bom mas para resolucao do problema e para datasets pequenos acredito que esta ok
def quebracabecas(lista):
    teste_set = set(range(lista[0],lista[-1]))
    for i in lista:
        if i in teste_set:
            teste_set.remove(i)

    return teste_set

Comment: Vc chegou a testar com os exemplos da pergunta? Porque esse código não funciona: https://ideone.com/AyQTtE
Comment: Creio que seu range dentro do set teria que começar de 1 e antes disso você teria que ordenar sua lista. Algo assim: `lista = sorted(lista)
    teste_set = set(range(1,lista[-1]))`. Abraço!
Comment: @lmonferrari Isso ainda falha se o número faltante for o "N" - ex: se a lista for `[2, 1]`, o número que falta é o 3, mas esse código retorna um `set` vazio: https://ideone.com/AsY5JU - outro detalhe é que está sendo retornado um `set` contendo o número, em vez do próprio número.
Comment: @hkotsubo, bom dia! O que eu havia entendido sobre o problema é que deveria retornar um número dentro de um range, [2,1] na minha visão não deveria retornar nada pois bastaria ordenar. Caso tenha que retornar o 3, realmente falha. Abraço!
Comment: @lmonferrari O problema diz que tem "N - 1" números entre 1 e N. Se N for 3, ela tem 2 números entre 1 e 3 e portanto na lista `[2,1]` está faltando o 3 - do enunciado: "*A função deve retornar o número inteiro x que pertence ao intervalo [1, N] mas que não pertence a lista de entrada L*"


Error: No method named "destroy" for popover bootstrap

Question: I want to close popover automatically after a delay time. but its showing an error error image
$('#prev_button').popover('show');

$('#prev_button').on('shown.bs.popover', function() {
  var $pop = $(this);

  setTimeout(function() {
    $pop.popover('destroy');
  }, 1000);
});

bootstrap.bundle.js is included to ensure popover method works. Can't figure out a solution
PS: using v4.1 bootstrap
Answer: As of version 4.1, the method destroy has been replaced by dispose. You can find more details here.
$pop.popover('dispose');

Answer: Please share bootstrap version details for better help & it would be better if you could prepare a jsfiddle.
Here is a jsfiddle link where you can find your code working with Bootstrap 3.0.
If you are using Bootstrap 4 following reference would help.
Some suggestions:
1. If you just intend to close it you should use hide rather than destroy.
2. You can also directly pass delay as an option to delay show or hide such that
delay: {
   show: "500",
   hide: "1000"
},

HTH
Answer: The Popover plugin is similar to tooltips. To destroy the shown popover you can use the following code-snippet:
$pop.popover('destroy'); // jQuery < 4.1
$pop.popover('dispose'); // jQuery > 4.1

You can also remove all created popovers from your DOM via .popover class (each popover has an id, so by knowing the IDs you can be more precise)
$('.popover').remove();


Creating a steady state vector

Question: I'm confused on where the intuition came from to divide $w$ by the sum of its entries to find $q$. I don't really see the relation from the sum of its entries with "every solution being a multiple of the solution $w$".
Comment: If we want $q$ to represent a probability vector, then we want every entry of $q$ to be in the interval $[0,1]$ and to have all of the entries add up to one.  In order to make it add up to one, this is easily accomplished by dividing by the sum of the entries since $\frac{w_1}{w_1+w_2+\dots+w_n}+\frac{w_2}{w_1+w_2+\dots+w_n}+\dots+\frac{w_n}{w_1+w_2+\dots+w_n}=\frac{w_1+w_2+\dots+w_n}{w_1+w_2+\dots+w_n}=1$
Comment: As for every solution being a multiple of $w$ (*or a multiple of $q$ for that matter*), that is a result of the eigenspace corresponding to the eigenvector of $1$ for any normal stochastic matrix will be one-dimensional.  Any one-dimensional space you have all vectors in the space (*in this case, our space of steadystate vectors*) will be multiples of one another (*except for being a multiple of the zero vector*).  This is unrelated to the sum of the entries.
Answer: In comments the user JMoravitz gives an answer. The solution to the question says that he wants to find the probability set of all solutions. So he finds a vector that solves the equation: $\vec{w} = (3,4)$ and then you normalize it. So the entries of $\vec{q}$.
Answer: This question is quite old, but it's been viewed enough times where I think people are finding it to assist their learning and I feel the other answers aren't providing an explanation beneficial to help learn.
The first stage that you appeared fine with was actually solving out the equation to find a vector $x$ such that
$$
Px = x.
$$
The first question you had is why are all solutions scalar multiples. I'll show that if $k$ is a scalar then $kx$ is also a solution. Now scalar multiplication commutes and also associates, so we can see that
$$
\begin{align}
P(kx) = (Pk)x = k(Px) = kx
\end{align}
$$
since we know that $Px=x$. As such all scalar multiples are also solutions. As for why you cannot have a different vector linearly independent from $x$ as a solution, the null space of $(P-I)$ is one dimensional so if there was another linearly independent vector from $x$, the null space would be two dimensional which isn't possible.
Now to answer your second question of what is the intuition to divide by $w$?, remember that the steady state represents a probability of where you will be after a very very long time. Probabilities have to add up to $1$, so if we pick
$$
q = \frac{x}{\sum_{i=1}^2 x_i}
$$
we'll end up with a vector of values that has sum $1$.
Why in the book did they choose $w=[3,4]$ instead of something else before dividing? Because integers are pretty and they probably thought it would make the division seem more clear -- which it seems it wasn't haha

Creating a steady state vector


Solving differential equations by definite integration

Question: I'm used to solving differential equations through indefinite integration and then making use of the boundary constraints to find the constants. Now I've learned they can also be solved by using definite integrals, but I don't quite understand the approach yet. Take e. g. the ODE $$ C\frac{d^2u(x)}{dx^2}+p=0 $$ where the domain for $x$ is $[0;l]$ and the BCs are $u(l)=u_1$ and $C\frac{du(0)}{dx}:=Cu'(0)=-N$. ($C$, $p$, $l$, $u_1$ and $N$ are all constants). Could anyone explain how to solve the problem using definite integration? (I have the solution here, but I have no idea how it's done ;).
Answer: I'm on my phone so I won't go too in depth. The TLDR is to just integrate from the IC of your independent variable (e.g. $x_0$), to your dependent variable (e.g. $x$).
$C\frac{d^2u}{dx^2}+p=0$
$\int_{x_0}^x(C\frac{d^2u}{dx^2}+p)dx= \int_{x_0}^x0dx$
$(C\frac{du}{dx}+px)\Big|_{x_0}^x=c\Big|_{x_0}^x$
$C(\frac{du}{dx}-\frac{du}{dx}\big|_{x_0}) +p(x-x_0)=0$
$C(\frac{du}{dx}-u'_0) +p(x-x_0)=0$
$\int_{x_0}^x(C(\frac{du}{dx}-u'_0) +p(x-x_0))dx= \int_{x_0}^x 0dx$
$(C(u(x)-u'_0x)+p(\frac{1}{2}x^2-x_0x)) \Big|_{x_0}^x=0 \Big|_{x_0}^x$
$C(u(x)-u_0-u'_0(x-x_0))+p(\frac{1}{2}(x^2-x_0^2)-x_0(x-x_0))=0$.
You can solve for $u$ as it takes a while to LaTeX on the phone. And you'll have to find someone else on using definite integrals to solve boundary condition problems (e.g. $x(0)=x_0, x(1)=x_1$) as I'm not sure on that front.
Comment: Ah, ok. To be clean you should use an auxiliary variable in the integral (i.e $\int_{x_1}^x f(y)dy$) since $\int_{x_1}^x f(x)dx$ is a bit "sloppy" (though we all have done it ;). The BCs can then be inserted readily since evaluation of the definite integral (in case of a first order ODE) yields $f(x)-f(x_0)$, where $f(x_0)$ is our known BC value. For a second order ODE (as described above), we have to play the game twice (after the first integration, we can insert our $u'(0)=-N$ BC and after the second integration we plug in the $u(l)=u_1$ BC). Thanx


How to create complex conditional clauses / queries?

Question: I've been reading the documentatoin on conditional clauses and also studied the api description for db_and() and db_or() but I fail to create a $query with 3 ->conditions:

select all between 0 and 100
but exclude 23, 48 and 97
select also 107, 123, 126 and 128

That's what I have tried so far:
$query->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN'));

But I get the following error:
PHP Fatal error:  Call to undefined method SelectQuery::db_or() in [... first line]

I've tried to play around with the syntax like that:
$query->condition(->db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));

But again getting errors like that:
PHP Parse error:  syntax error, unexpected T_OBJECT_OPERATOR, expecting ')' in [... first line]

I also tried working with variables:
$cond01 = array('my_field', array(107, 123, 126, 128), 'IN');
$cond02 = array('my_field', array(0, 100), 'BETWEEN');
$cond03 = array('my_field', array(23, 48, 97), 'NOT IN');
$db_and = db_and();
$db_and->condition($cond02);
$db_and->condition($cond03);
$db_or = db_or();
$db_or->condition($cond01);
$db_or->condition($db_and);
$query->condition($db_or);

But this again yields drupal errors like that:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'

How to create a complex conditional database query with both AND and OR statements?
Comment: Why down-vote this? I asked a clear question, showed what I've researched and tried so far, showed example code snippets including the resulting error messages. What's wrong with that?
Answer: Actually your final method is a right way, however the condition function is expecting 2 or 3 arguments(else only one DatabaseCondition instance as Molot said) and if you're not passing DatabaseCondition instance then your first argument should be the table column name. But you're passing an Array as the first argument. That's why you got unknown column 'Array' error.
So you should revise it like below,
$db_and = db_and();
$db_and->condition('my_field', array(0, 100), 'BETWEEN');
$db_and->condition('my_field', array(23, 48, 97), 'NOT IN');
$db_or = db_or();
$db_or->condition('my_field', array(107, 123, 126, 128), 'IN');
$db_or->condition($db_and);
$query->condition($db_or);

Further note your second approach is also right, however you put a extra -> before calling the db_or() function. So you should write it in the following way,
$query->condition(db_or()
  ->condition('my_field', array(107, 123, 126, 128), 'IN')
  ->condition(db_and()->condition('my_field', array(0, 100), 'BETWEEN')
                      ->condition('my_field', array(23, 48, 97), 'NOT IN')));

Answer: Drupal is not cleanly OO, and is not cleanly procedural. db_or() is not a method. It's a function. This function returns DatabaseCondition object you can use to attach other conditions to it, like:
$or = db_or()->condition('tid1', 5)->condition('tid2', 6);
db_delete('term_relation')->condition($or)->execute();

Note that you cannot just put arrays into condition method. It accepts either DatabaseCondition instance, or 3 parameters. 3 element arrays are not equivalent of 3 parameters in PHP.


Code not in window hierarchy root view

Question: I'm facing a problem trying to link my UIViewController but I got my final error.
Attempt to present ViewController whose view is not in the window hierarchy

Here's my code :
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

    if([title isEqualToString:@"Wokay"])
    {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        UIViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"Vibes"];
        [self.window.rootViewController presentViewController:vc animated:YES completion:nil];

    }
}

Code Error:
Warning: Attempt to present <ViewController: 0x110634bc0> on <Login: 0x10951e7f0> whose view is not in the window hierarchy!

Comment: can you copy paste the detail error?
Comment: You can't do this if the root view controller's view is not currently in the window hierarchy.
Comment: @rdelmar , aww the only thing i need to redirect them back when the reminder pops out .
Comment: @user3546239 why you have to present vc from rootViewController? shouldn't it be presented from current view controller?
Comment: @highwing , when I add my other controller as initial controller it fails and shows me that message but when I change my initial controller it works.
Answer: It seems like that your UIViewController(Login) is not in Window Hierarchy.
You may be adding your LoginViewController as a subView in UIWindow.
If so, set it as the UIWindow's rootViewController
AppDelegate.m
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    //Other code parts

    [self.window setRootViewController:loginViewController];
    return YES;
}

OR
If you are adding LoginViewController's view as subView in any UIViewController(say FirstViewController), present it instead
In your FirstViewController.m,
-(void)viewDidLoad{
    [super viewDidLoad];

    LoginViewController *loginViewController ;//Instantiate LoginViewController here
    [self presentViewController:loginViewController animated:NO completion:Nil];
}

Comment: No luck . I'm using both also UIViewController . when I set other UIViewController the redirect works but when i put another UIViewController(LOGIN) , it will make it to stuck.
Comment: @user3546239 so the question is: what's the diffferent between other UIViewController and LOGIN? did you assign the correct storyboard ID to LOGIN?

Code not in window hierarchy root view


Prove that $[X, Y] = \frac{\partial^2}{\partial s \partial t} \bigg|_{0} \left[\text{exp}(sX), \text{exp}(tY)\right]$ in a Lie group

Question: Suppose that $G$ is a Lie group, and let $\mathfrak{g}$ be the Lie algebra of $G$. For each $g \in G$, we get the conjugate map $C_g: G \to G; x \mapsto g x g^{-1}$.
I know that for each $X, Y \in \mathfrak{g}$, that $$[X,Y] = \frac{\partial^2}{\partial s \partial t}\bigg|_{0} C_{\text{exp}(sX)} \left( \text{exp}(tY)\right). \tag{1} \label{eq1}$$ The sketch of a proof is covered here on page 3.
After testing some examples when $ G = \text{GL}_2(\mathbb{R})$ on Mathematica, identifing the Lie algebra of $\text{GL}_2(\mathbb{R})$ with $M_2(\mathbb{R})$,  it seems that the identity
$$ [X, Y] = \frac{\partial^2}{\partial s \partial t} \bigg|_{0} \left[\text{exp}(sX), \text{exp}(tY)\right] \tag{2} \label{eq2}$$ may be true for each $X, Y \in \mathfrak{g}$, where the bracket on the right hand side is the commutator in $G$ given by $[g,h] = g h g^{-1} h^{-1}$, $g, h \in G$.
For example, both $(1)$ and $(2)$ are true when $G = \text{GL}_2(\mathbb{R})$, $X = \begin{pmatrix}
1 & 1 \\
0 & 1
\end{pmatrix}, Y = \begin{pmatrix}1 & 0 \\ 1 & 1  \end{pmatrix}.
$
Is $(2)$ true in general? If it is, what are some hints to prove it? It is quite similar to the first identity, which at first led me to believe that it is false, but alas it holds for some simple examples.
Answer: Using the Baker-Campbell-Hausdorff formula, we can expand the group commutator $[\exp(sX),\exp(tY)]$, ignoring terms of order $\ge 2$ in $s$ or $t$.
$$
\exp(sX)\exp(tY)\exp(sX)^{-1}\exp(tY)^{-1}
$$
$$
=\exp(sX)\exp(tY)\exp(-sX)\exp(-tY)
$$
$$
=\exp\left(sX+tY+\frac{st}{2}[X,Y]+\dots\right)\exp\left(-sX-tY+\frac{st}{2}[X,Y]+\dots\right)
$$
$$
=\exp\left(st[X,Y]+\dots\right)
$$
This, combined with the appropriate identifications (namely the canonical identification $\mathfrak{g}\cong T_0\mathfrak{g}\cong T_eG$ with the second isomorphism given by $d_0\exp$), gives the desired result.


How to update rows in the same table if the ids are the same?

Question: I have a database that I created from screen scraping from this company. However, because the company has changed the way they display data, I want to update my database too. Here's an example of what I want to do: (A: Name, B: ID)
A                            B
Apple                        0020
McIntosh Apple               0020
Ambrosia Apple               0021
Cortland Apple               0022
Apple                        0022

As you can see from the table above, the first row only has the name "Apple" and the key "0020", but the second row has the different name but the same key. Similarly, the forth and the fifth row has the similar problem. What I need to do is check each row, and if the ids are the same, then copy the name which has longer length to the shorter one so that the names for each ids are the same. But I'm not sure how to do this. I'm using SQL Server 2008. Can you pleas help? I'm also trying to achieve this using SSIS, and I'm still playing around with this. Since I'm not very experienced with SQL query, I'm having trouble wrapping my head around the logic to write the query.
Thank you
Comment: Honestly, the best practice is to ensure that you have unique identity keys.  If the second column MUST be able to have duplicates, add a third colum named RecordId and use it as a real unique ID.
Comment: So you don't mmind duplicate rows finally ? I.e Mcin apple 0020, Mcin apple 0020 etc. ?
Comment: Honestly, I don't even know where to begin. Can you give me some ideas? I'm thinking something along like update table set A = select max(length(A)) from table. But what I can't understand is how is it going to check the B values and update it
Comment: I do, but for now I'm fine with duplicate. Cause I'll be using SSIS to split the tables to create multiple ones for each column. the apple table is just an example.
Comment: I made a mistake in my previous comment: I meant it like this:  update table set A = select A from table where length(A) = (select max(length(A)) from table)
Comment: @DavidStratton - I was wondering if you could give me some feedback for my answer. I'd appreciate it very much. Thanks.
Comment: @DavidStratton that's a valued suggestion. The question I had is from a bigger database. When I created it, I had very limited knowledge about the data. Now that I know what those data mean, I immediately saw the issue with creating database like that. That's why I want to split the table into multiple tables so that the tables are normalized and contains no duplicates. Your suggestion is appreciated since I might need it in the future. Thank you for commenting.
Answer: A simple self join and length of column A can help us here. Once we get the query for that, we will use that query to perform an update (statement). Assume that the name of your table is junk.
Would'nt it be nice and easy if there was a column C which contained the longer name for each row in A ? In that case we could simply issue a statement UPDATE Junk SET A = C. Lets try to make this happen somehow. Lets get that "column C" first with the query below -
select *
from
(
select j1.A as A1,j1.B as B1,j2.A as C1
from Junk as j1
inner join Junk as j2 --self join
on j1.B = j2.B
and LEN(j1.A) < LEN(j2.A)
) as s1

Now lets try to make the results of this query "join" our Junk table and create
a column C. Once we do that properly, we can do a "simple" update. In the above
query, replace select * with an update statement as follows -
update Junk
set Junk.A = s1.C1
from
(
select j1.A as A1,j1.B as B1,j2.A as C1
from Junk as j1
inner join Junk as j2
on j1.B = j2.B
and LEN(j1.A) < LEN(j2.A)
) as s1
WHERE Junk.A = s1.A1
and Junk.B = s1.B1

To verify if this query works, run the first query. If you get zero rows, it works.
You can delete the duplicates or keep them if you wish.


How to render in Qt3D in standard GUI application?

Question: I enjoy using Qt3D, but all of the examples I see for it are full window applications. What I can't understand from the examples is how to add a qt3d rendering window to a regular qt gui application.
Basically what I want is a little rendering widget for my Qt5 Gui application.
I've looked into Qtgl widget, but I really want to use the scene management abilities of Qt3D.
How can I render as a sub window inside of a qt Gui window?
Is this possible?
Update
So I added this to my MainWindow.cpp It is loosely based off of this https://www.qt.io/blog/2013/02/19/introducing-qwidgetcreatewindowcontainer
LoadModelView *view = new LoadModelView(); //Crashes on this. Will not compile with
                                           // LoadModelView(this)

    QWidget *container = QWidget::createWindowContainer(view);
    container->setFocusPolicy(Qt::TabFocus);

    ui->gridLayout->addWidget(container);

which seems right.
my load_model.cpp begins like this:
#include "qglmaterialcollection.h"
#include "qglmaterial.h"
#include "qglscenenode.h"
#include "qgllightmodel.h"
#include "qglabstractscene.h"
#include <QtGui/qmatrix4x4.h>

#include <QPropertyAnimation>
#include <QtCore/qmath.h>

#define DEGREE_TO_RAD (3.1415926/180.0)

LoadModelView::LoadModelView(QWindow *parent)
    : QGLView(parent)
    , m_pSTLScene(0)
{
    loadModels();

    camera()->setCenter(QVector3D(0, 0, 0));
    camera()->setEye(QVector3D(0, 4, 10));
}
LoadModelView::~LoadModelView()
{
    delete m_pSTLScene;
}

void LoadModelView::paintGL(QGLPainter *painter)
{
    QMatrix4x4 stlWorld;
    stlWorld.setToIdentity();
    stlWorld.scale(0.1);
    stlWorld.translate(QVector3D(2.0,0.0,0.0));

    painter->setStandardEffect(QGL::LitMaterial);
    painter->setFaceColor(QGL::AllFaces,QColor(170,202,0));

    painter->modelViewMatrix() = camera()->modelViewMatrix() * stlWorld;

    m_pSTLScene->mainNode()->draw(painter);
}

void FixNodesRecursive(int matIndex, QGLSceneNode* pNode)
{
    if (pNode) {
        pNode->setMaterialIndex(matIndex);
       // pNode->setEffect(QGL::FlatReplaceTexture2D);
        foreach (QGLSceneNode* pCh, pNode->children()) {
            FixNodesRecursive(matIndex, pCh);
        }
    }
}

void LoadModelView::loadModels()
{
    {
        m_pSTLScene = QGLAbstractScene::loadScene(QLatin1String(":/models/Sheep.stl"), QString(),"CorrectNormals CorrectAcute");
        Q_ASSERT(m_pSTLScene!=0);
        QGLMaterial *mat = new QGLMaterial;
        mat->setAmbientColor(QColor(170,202,0));
        mat->setDiffuseColor(QColor(170,202,0));
        mat->setShininess(128);

        QGLSceneNode* pSTLSceneRoot = m_pSTLScene->mainNode();
        int matIndex = pSTLSceneRoot->palette()->addMaterial(mat);
        pSTLSceneRoot->setMaterialIndex(matIndex);
        pSTLSceneRoot->setEffect(QGL::FlatReplaceTexture2D);
        FixNodesRecursive(matIndex,pSTLSceneRoot);
    }
}

It crashes with:

This application has requested the runtime to terminate it in an unusual way.

And in the qt application output:

Invalid parameter passed to C runtime function.

EDIT Added the rest of the class in question
I notice that in the example I am adapting https://github.com/Distrotech/qt3d/blob/master/tutorials/qt3d/penguin/main.cpp the window is initialized by saying:
LoadModelView view;

However, saying
LoadModelView *view = new LoadModelView(this)

crashes
Comment: I want something like: Qt3DExtras::Qt3DWindow view; ui->widget = QWidget::createWindowContainer(view);
Answer: You can subclass QGLView class which extends QGLWidget with support for 3D viewing:
class GLView : public QGLView
{
    Q_OBJECT

public:
    GLView(QWidget *parent = 0);
    ~GLView();

protected:
    void initializeGL(QGLPainter *painter);
    void paintGL(QGLPainter *painter);

private:
    QGLAbstractScene *m_scene;
    QGLSceneNode *m_rootNode;
};

GLView::GLView(QWidget *parent)
    : QGLView(parent)
    , m_scene(0)
    , m_rootNode(0)
{
    // Viewing Volume
    camera()->setFieldOfView(25);
    camera()->setNearPlane(1);
    camera()->setFarPlane(1000);

    // Position of the camera
    camera()->setEye(QVector3D(0, 3, 4));

    // Direction that the camera is pointing
    camera()->setCenter(QVector3D(0, 3, 0));
}

GLView::~GLView()
{
    delete m_scene;
}

void GLView::initializeGL(QGLPainter *painter)
{
    // Background color
    painter->setClearColor(QColor(70, 70, 70));

    // Load the 3d model from the file
    m_scene = QGLAbstractScene::loadScene("models/model1/simplemodel.obj");

    m_rootNode = m_scene->mainNode();
}

void GLView::paintGL(QGLPainter *painter)
{
    m_rootNode->draw(painter);
}

Qt 5.1 introduces the function QWidget::createWindowContainer(). A function that creates a QWidget wrapper for an existing QWindow, allowing it to live inside a QWidget-based application. You can use QWidget::createWindowContainer which creates a QWindow in a QWidget. This allows placing QWindow-subclasses in Widget-Layouts. This way you
 can embed your QGLView inside a widget.
Comment: I *think* I already do that. http://pastebin.com/tRi9BVwn What I am asking is how do I get this to pop up in a already existing Window. Can you show how to call this from mainwindow.cpp? If I try to add w.show, then view.show, then everything crashes. I want a normal window with buttons etc... and a 3d render embedded in it below the buttons.
Comment: https://qt-project.org/forums/viewthread/22465 This thread gets at my question. Doesn't answer it either.
Comment: You can use QWidget::createWindowContainer in Qt 5.1. I have updated th answer.
Answer: This is how I did it on Qt5.10. This example shows a scene with a cuboid. Scene you can than use like a button or so... To use this add QT += 3dextras to your project file.
szene.h
#ifndef SCENE_H
#define SCENE_H

#include <QObject>
#include <QWidget>

class Scene
      : public QWidget
{
    Q_OBJECT

private:
    QWidget *container;

public:
    explicit Scene(QWidget *parent = nullptr);

protected:
    // reimplementation needed to handle resize events
    // http://doc.qt.io/qt-5/qwidget.html#resizeEvent
    void
    resizeEvent ( QResizeEvent * event );

public slots:
    void
    resizeView(QSize size);
};

#endif // SCENE_H

scene.cpp
#include "scene.h"

#include <Qt3DExtras/Qt3DWindow>
#include <Qt3DExtras/QForwardRenderer>
#include <QQuaternion>
#include <Qt3DCore/QEntity>
#include <Qt3DCore/QTransform>
#include <Qt3DRender/QCamera>
#include <Qt3DExtras/QCuboidMesh>
#include <Qt3DExtras/QPhongMaterial>

Scene::Scene(QWidget *parent)
   : QWidget(parent)
{
    auto view = new Qt3DExtras::Qt3DWindow();

    // create a container for Qt3DWindow
    container = createWindowContainer(view,this);

    // background color
    view->defaultFrameGraph()->setClearColor(QColor(QRgb(0x575757)));

    // Root entity
    auto rootEntity = new Qt3DCore::QEntity();

    // Camera
    auto camera = new Camera(rootEntity,view);
    auto cameraEntity = view->camera();

    cameraEntity->setPosition(QVector3D(0, 0, 50.0f));
    cameraEntity->setUpVector(QVector3D(0, 1, 0));
    cameraEntity->setViewCenter(QVector3D(0, 0, 0));

    // Cuboid
    auto cuboidMesh = new Qt3DExtras::QCuboidMesh();

    // CuboidMesh Transform
    auto cuboidTransform = new Qt3DCore::QTransform();
    cuboidTransform->setScale(10.0f);
    cuboidTransform->setTranslation(QVector3D(0.0f, 0.0f, 0.0f));
    cuboidTransform->setRotation(QQuaternion(1,1.5,1,0).normalized());

    auto cuboidMaterial = new Qt3DExtras::QPhongMaterial();
    cuboidMaterial->setDiffuse(QColor(QRgb(0x005FFF)));

    // assamble entity
    auto cuboidEntity = new Qt3DCore::QEntity(rootEntity);
    cuboidEntity->addComponent(cuboidMesh);
    cuboidEntity->addComponent(cuboidMaterial);
    cuboidEntity->addComponent(cuboidTransform);

    // Set root object of the scene
    view->setRootEntity(rootEntity);
}

void
Scene::resizeView(QSize size)
{
    container->resize(size);
}

void
Scene::resizeEvent ( QResizeEvent * /*event*/ )
{
  resizeView(this->size());
}


error C4430: missing type specifier - int assumed. Note: C++ does not support default-int"

Question: I have this error:

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int"

with this code example:
Comment: Please put the code in this question.  As text, not a picture of text.  Questions often get closed if they are mostly on other websites or not in a format that a compiler could understand.
Comment: [Why not upload images of code/errors when asking a question?](https://meta.stackoverflow.com/questions/285551/)
Answer: The error message means that NTSTATUS is not defined, so the compiler is assuming the function returns an int instead.
Add #include <Ntdef.h>.  Or, just use LONG instead, which is what NTSTATUS maps to.
Comment: thz so much and it woked also how i fix this "unresolved external symbol "int_cdcel CleanProcess(void)" (?CleanProccess@@YAHXZ)"
code is std::thread t1(VanguardDrivers);
 t1.detach();

 std::thread t2(ProcessKiller);
 t2.detach();

 std::thread t3(GayMacChanger);
 t3.detach();

 std::thread t4(DriverLoad);
 Sleep(7000);
 t4.detach();

 std::thread t5(CleanProcess);
 t5.detach();

 std::thread t6(CleanCaches);
 t6.detach();
Comment: [What is an undefined reference/unresolved external symbol error and how do I fix it?](https://stackoverflow.com/questions/12573816/) You have *declared* `CleanProcess()` but have not *defined* it, ie the linker can't find its implementation, either because you didn't write one yet, or you are not compiling/linking the `.cpp` file that does.
Comment: but i put int CleanProcess(); because the int CleanProcess() in a clean.c file  so i put that so the int clean can call it and i can use it in the main.cpp file
Comment: `int CleanProcess();` is a *declaration*, not a *definition*. The linker is complaining about a missing *definition*. The filename `clean.c` implies that file *may* get compiled as C code, not as C++ code. If that is the case, then either tell the compiler to compile the file as C++ instead, or change its name to `clean.cpp`, or else try applying `extern "C"` to the *declaration*.
Comment: it starts to compile then it stops at 1>Generating code do u know fix?
Comment: That is not a helpful description. Please provide a [mcve] that demonstrates the error.


Identifying and quantifying variables (predictors) to understand the relationship

Question: What type of analysis do I need to understand and/or gain information from a set of data?
For example, I have students' data for SATScore, HighSchoolGPA, HighSchoolRank, etc., and FreshmenGPA.
Now I want to develop a model which tells me which of the criteria are important for FreshmenGPA and by how much. I want to quantify the importance of these categories (SATScore, HighSchoolGPA, HighSchoolRank, etc.).
What options do I have? Which is the most accurate methodology to do such analysis?
What I Want to find out from the data:
I want is to identify which of these variables(SATScore, HighSchoolGPA, HighSchoolRank, etc.) can help me predict Students FreshmenGPA.
I did some reading on what I need to do for this but there is no definite source or a definite answer. From what I roughly understand, it looks like I need to find out which of these variables are helpful in predicting FreshmenGPA, and whether there is an interaction variable(combination of two or more variables) which is a better predictor than any individual variable. How can I do this?
Once I know which variables and/or interaction variables are important for my model, I will need to quantify the variable importance, for this I'll need to find out the weights(coefficients) for variables which I found are important for FreshmenGPA.
Could anyone show me the steps I need to follow to understand and do this? Also, It looks like there are multiple ways of doing this, Not sure if this is correct, but If so which of these methods give the most accurate model for the data?
Comment: Sometimes the answer is wait, but my main comment remains that it's not clear what you expect here. No one is likely to write a long essay on what you might do. Probably more than half statistics falls under your very general title. So, try to make it much more specific. What do you _next_ want to know?
Comment: While you are waiting, you should consider looking over the other threads with the [tag:model-selection] (and maybe [tag:multiple-regression]) tags.  I'm pretty sure your question has already been fully and elaborately answered.
Comment: "enough" means that someone will answer in a way that satisfies you; that's doubly difficult to predict. As @whuber advises, do look at what's already on-site.
Comment: As a somewhat recent graduate I know the following: you do not have enough measures to determine success.  With incomplete data you are going to have imperfect results.  How do you account for the friends they make? (rf?) How do you measure the party culture on campus?  What happens if they get their heart broken?  GPA doesn't have enough information to tell you those "why" answers to the question of freshman GPA.  It doesn't speak to proper match of aptitude and interest with course selection.  Emotional baggage.  Teen angst.
Comment: @EngrStudent Wouldn't that be the case with most of the models? no matter how well we model we will always miss some predictor which could better our models prediction power? Is there some analysis we can perform to show what % of dependent variable is explained with data we have? for e.g This data describes 60% of dependent variable(GPA) and we are 90% confident about it?
Comment: Your tags suggest that you already know a short answer here, multiple regression. It's not quite clear what kind of answer you expect otherwise.
Comment: That is to say, your original tags included multiple regression. That's still my own short answer.
Comment: @NickCox Do you suggest updating my tags? I chose whichever poped up while writing analysis, prediction, variables, relation etc.
Comment: Yes indeed; "multiple regression" makes sense to me; "information-retrieval" means something quite different from your question.
Comment: @NickCox Someone else edited my tags again. Not sure what I need to do to get an answer :\
Comment: @NickCox I updated my question with more details, is this enough or do i need to be more specific for a detailed explanation/answer?
Comment: "Enough" is the important value here.  If you only have x-coordinate, but not y-coordinate, how effectively can you track x-y position?  At some point there is a transition from incomplete data to substantially underinformative data.  When you make that transition then you can't make anything but the most general (and low value) conclusions.  Human behavior and educational outcomes is not "my thing" so I can't tell you from coursework where the textbooks say that boundary is.  I do have experience, and my education/engineering-modeling experience says its not enough information for my comfort.
Answer: As was noted, your question is very general, and as such there are MANY different approaches.

Perform linear regressions on y ~ x (y=one variable only) with FreshmanGPA as your dependent variable. The weights of each variable explain the interactions. Looking at the p-values will determine if the variable is likely to be useful (low p-values are better).
Calculate the correlation between FreshmanGPA and all other variables. The variable with the highest correlation is the most associated with FreshmanGPA. Then go back and run the linear regression on this variable.
Run a discriminant analysis on all the data, calculating for FreshmanGPA. The coefficient size are proportional to the predictive power of the variable.
Run linear regression on the interaction terms and compare how the model performs compared to a single variable.

These are only a few ideas. The calculations can be done in many different programs, such as R, SAS, Stata, and many others that I am not familiar with.
In order to compare which factor is the most important, you are basically looking for a relationship that either (1) explains the current data the best. That is to say, if you have a linear regression, your residual errors is the smallest, or (2) predicts a new dataset the best. For (2) you will need to split your data into a testing and training sample. Each time you run a training model, you then predict the FreshmanGPA on the testing sample and see how close you are (the residual error).
Which you choose depends on the purpose of the test. From the question, I expect the first option is better suited.
For detailed examples on how to run this, you will need to specify what program you are using, and give an example of the dataset. Try searching within the forum for a few specific terms. For example:

linear regression R (SAS, Stata, etc)
Discriminant Analysis
Comparing linear regressions
How to calculate interaction terms in R (SAS, Stata, etc)
Comment: For the percent explained, it depends on the type of study you use, but all options will present this information. For example, linear regression will tell you the amount of deviance explained by each variable. A discriminant analysis will tell you the amount of variance explained by each axe (which is a combination of different variables). Confidence intervals can be made on the estimates of the variables (how correct are we?), and it usually requires more assumptions on the data. I would suggest creating a new question once you've decided what method to use to get a specific answer.
Comment: Is there some analysis we can perform to show what % of dependent variable is explained with data we have? and also show a confidence interval for our estimate. for e.g This data describes 60% of dependent variable(GPA) and we are 90% confident about it?


every relation in a special structure $M$ which is first-order definable with parameters has cardinality $< \omega$ or $= |M|$.

Question: Let $M$ be a special structure. I'm trying to proof that every relation in $M$ which is first-order definable with parameters has cardinality $< \omega$ or $= \lambda$.
By a first-order definable with parameters relation I mean a set $A = \left \{ \psi(a_1, \cdots, a_m, b_1, \cdots, b_n): a_1, \cdots, a_m \in M,\, b_1, \cdots, b_n \in X, \, \psi(\overline a, \overline y) \text{ formula} \right \}$ for fixed $m$ and $X \subset M$.
I don't know even how to start this question. If I suppose that a set $A$ as above has cardinality $\geq \omega$, we proof that $|A| = |M|$, but how can I proceed?
Comment: What is a special structure?
Comment: @Mark: I've never been more ashamed in my life as I am now, of the fact that we are in the same logic group.
Comment: @asaf The definition I know is that a structure $A$ of infinite cardinality $\kappa$ is special if it is the union (colimit) of an elementary chain $(A_i)_{i < \kappa}$ where each $A_i$ is $|i|^+$-saturated.
Comment: @Mark: I thought you're on a plane.
Comment: @asaf there is lots of downtime around a flight. For example, now I actually found the time to write an answer.
Comment: @Mark: And yet you didn't have any time to find the shift key and write `Asaf`... tsk tsk tsk.
Comment: @asaf i'm on my phone, so i can't be bothered
Answer: In this answer I will not distinguish between elements/variables and finite tuples of elements/variables (so you may read every lowercase letter as if it denotes a finite tuple).
First I should say that your definition of "definable" it's not quite right. The way you defined it, every set would be definable. The correct definition is that $A$ is definable (in $M$) if there is a formula $\phi(x,y)$ and $b \in M$ such that
$$
A = \{a \in M : M \models \phi(a,b)\}.
$$
We call $b$ the parameters.
Let me also recall the definition of a special structure here (to introduce some notation at the same time). A structure $M$ of infinite cardinality $\kappa$ is special if it is the union $\bigcup_{i < \kappa} M_i$ of a chain $(M_i)_{i < \kappa}$ such that for every $i < \kappa$ the structure $M_i$ is $|i|^+$-saturated.
Now that is out of the way, we can actually have a look at your question.
Let $A \subseteq M$ be infinite and $|A| < |M|$. Suppose that $A$ is definable by some $\phi(x, y)$ with parameters $b$. We will aim for a contradiction. Since $b$ is just a finite tuple of parameters, there will be some $\lambda < \kappa$ such that $b \in M_\lambda$. We may assume that $|A| \leq \lambda$ (otherwise replace $\lambda$ by $|A|$). Now define
$$
\Sigma(x) = \{x \neq a : a \in A \cap M_\lambda\} \cup \{\phi(x, b)\},
$$
then clearly $\Sigma(x)$ is finitely satisfiable. So we can extend $\Sigma(x)$ to a complete type $p(x)$ over $(A \cap M_\lambda) \cup \{b\}$. Since $|(A \cap M_\lambda) \cup \{b\}| < \lambda^+$ and $M_\lambda$ is $\lambda^+$-saturated we then must be able to find a realisation $c \in M_\lambda$ of $p(x)$ and thus of $\Sigma(x)$. But that means $M_\lambda \models \phi(c, b)$, so $c \in A \cap M_\lambda$ while the first part of $\Sigma(x)$ says that $c$ must be different from every element in $A \cap M_\lambda$. We thus reach our desired contradiction, and we can conclude that of $A$ is infinite and $|A| < |M|$, then $A$ cannot be definable in $M$.
Comment: Right - the point is that special models (of singular cardinality) provably exist in ZFC for all theories, while saturated models do not.
Comment: @user242964 yes, I defined $\kappa$ as $|M|$ in the paragraph before. For your other questions. (1) We use here that $A$ is infinite, so every finite part of $\Sigma(x)$ will say at most "$x$ is in $A$ but unequal to a finite part of it". So then we can definitely find some realisation of that. (2) If something is finitely satisfiable it must have a realisation in some elementary extension (indeed by compactness), then taking the type of that realisation is a completion.
Comment: @user242964 For (1) it may also be good to note why $A \cap M_\lambda$ is indeed infinite as well. This is because it is defined by $\phi(x, b)$ and the sentence "there are at least $n$ different $x$ such that $\phi(x, b)$" is true in $M$, and thus in $M_\lambda$, for all $n \in \mathbb{N}$.
Comment: @Kat That is not needed, because if something is $\lambda$-saturated then it realises any $n$-type over less than $\lambda$ parameters. If your definition only mentions 1-types, you can still prove this statement from that definition (so it is equivalent). That may be a nice exercise (hint: induction).
Comment: Not every special structure is saturated, though...
Comment: @Alex Ah, you are right, I guess I assumed that the structure has regular cardinality, which makes the question more general than I first thought. So then we will need to replicate the argument in one of the structures in the chain, I will edit my answer.
Comment: @Alex That is indeed a very good reason for this version. I have corrected my answer. Thank you for your input!
Comment: Sorry for the delay to respond. But your $\kappa$ in the fourth paragraph means $|M|$?
Comment: @MarkKamsma  I'm stucked in two parts. 1) Why can you say that your $\sum$ is finitely satisfiable? and 2) Is it by compactness that you can extend to a complete type $p$?
Comment: Can this solution be extended to the case $A \subset M^n$?  I cannot see how.
Comment: @Kat yes, the exact same proof works for the case $A \subseteq M^n$. You just have to replace the use single elements by finite tuples everywhere (as I indicated at the start of my answer). Often in model theory we do not distinguish between single elements or finite tuples, because all the proofs work the same anyway.
Comment: But we still want in this case $\Sigma(x)$ be a 1-type in M, right? It will be?


Adding theme JS library in custom module

Question: My theme documention.libraries.yml file is defined as follows :
global-styling:
  version: VERSION
  css:
    base:
      styles/dist/styles.css: {}
tocbot:
  js:
    libraries/tocbot/tocbot.js: {}
    js/tocInit.js: {}
  css:
    layout:
      libraries/tocbot/tocbot.css: {}
layout_tweaksLib:
  js:
    js/layout_tweaks.js: {}

My custom module implements a custom template which also requires the theme functionality defined in tocInit.js. So I'm trying to include the tocbot library from my theme in my module.
I have tried including a dependencies clause in my_module.libraries.yml file, resulting in the following :
my_module:
  js:
    js/my-module.js: {}
  dependencies:
    - documentation/tocbot
  css:
    component:
      css/my-module.css: {}

However, the tocInit.js script is not being loaded on the modules' custom template.
I would appreciate some help, please.
Answer: From documentation.libraries.yml, extend the module's definition of the my_module library to include documentation/tocbot's assets using libraries-extend.
# documentation.libraries.yml
libraries-extend:
  my_module/my_module:
    - documentation/tocbot


Сonvert trigonometric equation to quadratic equation

Question: I am struggling to know how to transform this equation as it involves more than one type of trigonometric function, I know how to do it with one repeated function.
Question:
$\sin^2 \theta/2$ + $\sin \theta$ + $1$ = $0$
In must be transform in pure quadratic form:
$t^2$ + $t$ + $1$ = $0$
Comment: Note that the trigonometric equation has at least the solution $\theta=-\pi/2$, while the trinomial $t^2+t+1$ has no real root (the discriminant is $<0$).
Comment: Is it $\sin \frac{\theta}{2}$ or $\frac{\sin \theta}{2}$?
Answer: Observe that $$\sin \theta = 2 \sin \left (\frac {\theta} {2} \right ) \cos \left (\frac {\theta} {2}\right ).$$
Comment: I think this doesn't help!
Comment: Who says you?  Put $t = \sin \left (\frac {\theta} {2} \right ).$ Then we have $$\begin{align*}t^2+2t \sqrt {1-t^2} + 1 - t^2 & = t^2  \implies (t+ \sqrt {1-t^2})^2 = t^2 \\ \implies t+ \sqrt {1-t^2} & = \pm t. \end{align*}$$
Comment: It is not correct again, $$\cos(\frac{x}{2})=\pm\sqrt{1-\sin^2(\frac{x}{2})}$$
Comment: I don't understand what are you trying to say?
Comment: Then read my comment. Do you know the $$\pm$$ sign?
Comment: Are you the only person to know the sign $\pm$?
Comment: Senseless the discussion, have a nice day.
Comment: I get your point. According to you we must have $$t \pm \sqrt {1-t^2} = \pm t.$$ Right?
Answer: This is what is sometime called a "trick question" since it does not require you to solve a quadratic equation.
Notice that if $\sin^2\left(\dfrac{\theta}{2}\right)+\sin\theta+1=0$, then it follows that $\sin^2\left(\dfrac{\theta}{2}\right)=-\sin\theta-1\ge0$. So it must be the case that $\sin\theta\le-1$. So $\sin\theta=-1$.
Therefore one would think that $\theta=-\dfrac{\pi}{2}+2\pi n$. But this will contain extraneous solutions. For example, $-\dfrac{\pi}{2}$ is not a solution since
$$ \sin^2\left(-\frac{\pi}{4}\right)+\sin\left(-\frac{\pi}{2}\right)+1\ne0 $$
This raises the question "Are there any values of $n$ which yield a solution?"
\begin{eqnarray}
&&\sin^2\left(-\frac{\pi}{4}+\pi n\right)+\sin\left(-\frac{\pi}{2}+2\pi n\right)+1\\
&=&-\frac{\sqrt{2}}{2}\cos(\pi n)+0-\cos(2\pi n)+0\\
&=&-\frac{\sqrt{2}}{2}\cos(\pi n)-1
\end{eqnarray}
But, since $\cos(\pi n)=\pm 1$ there are no values of $n$ which will give $0$.
So the equation has no solutions.
ADDENDUM
If it is the case that OP intended to write $\dfrac{\sin^2\theta}{2}+\sin\theta+1=0$, that also has no solutions since
\begin{eqnarray}
&&\sin^2\theta+2\sin\theta+2\\
&=&(\sin\theta+1)^2+1\ge1
\end{eqnarray}
SECOND ADDENDUM
Here is an even faster way to show that there are no solutions.
Rewrite the equation using the identity $\sin^2\left(\dfrac{\theta}{2}\right)=\dfrac{1-\cos\theta}{2}$ to obtain
$$ 2\sin\theta-\cos\theta+3=0 $$
$$ \sqrt{5}\left(\frac{2}{\sqrt{5}}\sin\theta-\frac{1}{\sqrt{5}}\cos\theta\right)+3=0$$
Letting $\sin\psi=\dfrac{1}{\sqrt{5}}$ this can be re-written
$$ \sqrt{5}\sin(\theta-\psi)+3=0 $$
But $\sqrt{5}\sin(\theta-\psi)+3\ge3-\sqrt{5}>0$. So there are no solutions.


Can parameters to dust.js helpers be anything but a string (e.g. an array)?

Question: While parsing JSON data with a dust.js template, I call a helper and pass an array from the JSON data to the helper as one of its parameters. It's an array of strings like:
"foo": ["a", "b", "c"]

Inside the dust.js helper the value becomes this string: "a, b, c". typeof reports its type as a string. Is there a way to thwart this automatic conversion? I don't want to do a split on the commas, because the individual strings in the array may contain commas.
Answer: It depends how you pass in param into a helper. {@myHelpers arrayParam=myArray /} will be passed in as Array (granted that myArray is an Array) vs {@myHelper arrayParam="{myArray}"/} will be passed in as a String because of the interpolation. Note how first example does not have {} around myArray param.
Here is a working demo of these two examples in JSFiddle.


evaluate function limit by change of variable

Question: I'm struggling with this limit, tried everything on it but can't treat this indeterminate form...
$$ \lim_{x\rightarrow  0} \frac{\sin\frac{1}{x}}{e^{\frac{1}{x}} + 1}$$
Ideally, I want to evaluate it using a change of variables, but every other method would be most welcome.
I thank you guys for your explanation and your help.
Comment: If $u=\dfrac1x$, then we have $$\lim_{u\to\infty} \frac{\sin u}{e^u+1}.$$  What do you know about the convergence of this?
Comment: @AndrewChin That is not correct. The limit you've written can exist, but the one OP wrote still may not.
Comment: First, think about the same limit where the numerator is the constant $1$. How does the denominator behave depending on whether $x$ is positive or negative? For example, evaluate the denominator for $x=0.1$ and for $x=-0.1$.
Comment: @DonThousand Are you able to explain that to me in brief?
Comment: @AndrewChin The limit you've written is equivalent to $$\lim\limits_{x\to0^+}\frac{\sin\frac1x}{e^{\frac1x}+1}$$That isn't exactly the limit OP is asking for.
Comment: Right on, I see your answer.  Would it be fair to say that if $\lim\limits_{u\to\infty} f =\lim\limits_{u\to -\infty} f = L$, then the limit would exist?
Comment: @AndrewChin That would be correct.
Answer: Let $y=\frac1x$. The limit becomes $$\lim\limits_{y\to\pm\infty}\frac{\sin y}{e^y+1}$$Note that when $y\to-\infty$, $e^y+1\to1$, so the limit becomes $\lim\limits_{y\to-\infty}\sin y$ which does not exist, so the overall limit does not exist.
If you solely care about the limit as $x\to0^+$, then we consider $y\to\infty$ in our transformed limit, as below$$\lim\limits_{y\to\infty}\frac{\sin y}{e^y+1}$$ As $e^y+1\to\infty$, while $|\sin y|\leq1$, this limit equals $0$.
Answer: The right limit exists and it is $0$ because the numerator is bounded and the denominator goes to $\infty$
The left limit does not exist because the denominator approaches $1$ while the  numerator does not have a limit as it jumps up and down between $1$ and $-1$
Thus the limit does not exist.
Answer: Use that $$\left|\frac{\sin(u)}{e^u+1}\right|\le \left|\frac{1}{e^u+1}\right|$$