jQuery div expand/collapse

Question: Have a look at following sample:
http://jsfiddle.net/EWJGJ/13/
I want to customize this sample such a way that:

Expand of give div should happen over click and not mouse hover. Currently it is on mouse hover.
The clicked div should expand on all of the div. That is, in the link above, there are 9 divs. If I click on any of the div, it should expand over all of the divs.
The behavior should be toggle. If I again click on expanded div, it should shrink to its original position and making others div visible.

Any sample code or link will be really helpful. I am basically trying to create Windows 8 style tile based interface having such behavior.
Code
HTML:

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

[immagine]

"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

Javascript:
    $(window).load(function(){
$('.contenitore').hover(function() {
    $(this).animate({
        width: 300,
        height: 400,
        top: -80,
        left: -45
    }, 'fast');
    $(this).animate().css('box-shadow', '0 0 5px #000');
    $(this).css({
        zIndex: 100
    });
}, function() {
    $(this).animate().css('box-shadow', 'none')
    $(this).animate({
        width: 210,
        height: 240,
        top: 0,
        left: 0
    }, 'fast');
    $(this).css({
        zIndex: 1
    });
});
});

CSS:
.tabellainizio {
    margin-top:100px;
}
.bordini {
    border: 1px #DDD solid;
}
.principale {
    height: 240px;
    width: 210px;
    position: relative;
}
.principale .contenitore {
    background-color: #fff;
    height: 240px;
    width: 210px;
    position: absolute;
    display: block;
    top: 0;
    left: 0;
}
.immagine {
    border: 1px solid maroon;
    margin: 15px auto;
    height: 168px;
    width: 168px;
    position:relative;
}
.content {
    display: none;
    margin: 15px;
}
.contenitore:hover {

}
.contenitore:hover .content {
    display: block;
}
.contenitore:hover .immagine {
    position:relative;
}

Comment: Look's like a BIG task. The question should be migrated to _doThisForMe.stackoverflow.com_
Comment: @MohammadAdil hi any link or resource would be sufficient. I can try it on my own. Just need pointer to some links or resource.
Comment: http://api.jquery.com/click/  ,,,,  http://api.jquery.com/toggle/
Answer: Replace hover with toggle, get the index of the clicked element parents td -> for column number and tr -> for row number, move clicked element to the top left corner:
$(window).load(function () {
    $('.contenitore').toggle(function () {

        $(this).css({
            'box-shadow': '0 0 5px #000',
            zIndex: 100
        }).animate({
            width: 212 * 3,
            height: 242 * 3,
            top: 0 - ($(this).parents('tr').index() * 242),
            left: 0 - ($(this).parents('td').index() * 212)
        }, 'fast');
    }, function () {

        $(this).animate({
            width: 210,
            height: 240,
            top: 0,
            left: 0
        }, 'fast', function () {
            $(this).css({
                zIndex: 1,
                'box-shadow': 'none'
            });
        });
    });
});

jsfiddle
Comment: Thanks @razzak. I followed adil's link above and just did it bit similar to this using click. However, your solution is in clean code than mine. So will follow your code now and will modify it accordingly. Thanks a lot! good to learn.

jQuery div expand/collapse


Does KNN have a loss function?

Question: I didn't find a definition of loss function on wiki in the context of machine learning.
this one is less formal though, it is clear enough.
At its core, a loss function is incredibly simple: it's a method of evaluating how well your algorithm models your dataset. If your predictions are totally off, your loss function will output a higher number. If they're pretty good, it'll output a lower number. As you change pieces of your algorithm to try and improve your model, your loss function will tell you if you're getting anywhere.
it seems that the error rate of KNN is not the function that could guide the model itself optimize, such as Gradient Descent.
so, Does KNN have a loss function?
Answer: $k$-NN does not have a loss function that can be minimized during training. In fact, this algorithm is not trained at all. The only "training" that happens for $k$-NN, is memorising the data (creating a local copy), so that during prediction you can do a search and majority vote. Technically, no function is fitted to the data, and so, no optimization is done (it cannot be trained using gradient descent).
Comment: kNN doesn't use a loss function during "training", but that doesn't mean there *isn't* a loss function that defines kNN. For example: It is well known that the median minimizes the mean absolute difference loss. But you don't ever calculate the mean abs loss, and you don't use optimization like gradient descent to calculate the median either. It's still a useful fact that it minimizes mean abs loss sometimes. In the same way, you could probably construct a loss function that kNN always minimizes
Comment: @nikie that's true, but in kNN uses them just as local aggregation functions among the neighbors (hard to translate to overall loss to minimize). Also for k=1 you don't use any such function. Moreover it is not used for training. Calling it a loss function is merely a mental exercise to force kNN to fit some definition of classifier, I don't find compelling reasons for defining it that way.
Comment: I thought the question seemed theoretical in nature, but you are right that there isn't any practical use in knowing the loss. Maybe OP was looking for something like neighborhood component analysis? I linked it in the answer.
Comment: @nikie - I added the loss function in a new answer. Tim - the advantage of writing it this way is that it's easier to see how one can make the objective "softer" by switching from a top hat kernel (counting the number of points - the usual kNN) to a Gaussian kernel (weighting points by proximity).
Comment: @Miles it's true, but it is not useful anyhow besides theoretical, academic, discussion. In practical terms, the algorithm is not trained using loss function and it wouldn't be practical to do so. I'd say that talking about loss function for kNN is more confusing then helpful in most cases.
Answer: As an alternative to the accepted answer:
Every stats algorithm is explicitly or implicitly minimizing some objective, even if there are no parameters or hyperparameters, and even if the minimization is not done iteratively. The kNN is so simple that one does not typically think of it like this, but you can actually write down an explicit objective function:
$$ \hat{t} = \text{argmax}_\mathcal{C} \sum_{i: x_i \in N_k(\{x\}, \hat{x})} \delta(t_i, \mathcal{C}) $$
What this says it that the predicted class $\hat{t}$ for a point $\hat{x}$ is equal to the class $\mathcal{C}$ which maximizes the number of other points $x_i$ that are in the set of $k$ nearby points $N_k(\{x\}, \hat{x})$ that also have the same class, measured by $\delta(t_i, \mathcal{C})$ which is $1$ when $x_i$ is in class $\mathcal{C}$, $0$ otherwise.
The advantage of writing it this way is that one can see how to make the objective "softer" by weighting points by proximity. Regarding "training," there are no parameters here to fit. But one could tune the distance metric (which is used to define $N_k$) or the weighting of points in this sum to optimize some additional classification objective. This leads into Neighborhood Component Analysis: https://www.cs.toronto.edu/~hinton/absps/nca.pdf which learns a distance metric.
Comment: You've written the decision rule for a KNN classifier as an optimization problem. This is a valid point, but seems somewhat different in spirit than what the question is asking. Typically, we define a hypothesis space of possible classifiers, and the loss function is defined on this space. I.e. it maps each possible classifier to a value measuring how good/bad it is. Learning then consists of selecting the classifier with minimal loss. Your objective function isn't defined on the space of classifiers, but on the space of class labels for a given input point.
Comment: I agree–for real problems, one wants to use a classification objective. But this is the loss that gives us a kNN, just as, say, mean absolute error as a loss gives us the median. It's ambiguous what the original poster was actually looking for; this answer is my interpretation (but could be wrong).
Comment: I found your answer very helpful I would really appreciate if you could help me answer this question too: Relevant question to the subject : https://stats.stackexchange.com/questions/501229/i-want-to-formulate-mathematically-the-k-nn-objective-function-and-neighborhood

Does KNN have a loss function?


Finding the general solution of a DE using substitution

Question: Use the substitution $u=y^{-2}$ to find the general solution to the DE: $\\$ $\frac{dy}{dx} + xy + x^3y^3=0$
First, I found what $y$ was in terms of $u$, so
$$y=u^{-\frac{1}{2}} \rightarrow y'=-\frac{u^{-\frac{3}{2}}}{2}$$
Now plugging this into the DE, we get
$$\frac{dy}{dx}=-xy-x^3y^3=-\frac{u^{-\frac{3}{2}}}{2}$$
$$xu^{-\frac{1}{2}}+x^3u^{-\frac{3}{2}}=\frac{u^{-\frac{3}{2}}}{2}u'$$
$$xu^{-\frac{1}{2}}+x^3=\frac{u'}{2}$$
Integrate
$$u=2x^3u+4xu^{\frac{1}{2}}+Cu^{-1}$$
$$1=2x^3+4xu^{-\frac{1}{2}}+Cu^{-2}$$
I am stuck around here, as I don't know if it was right to integrate as early as I did, since it didn't seem to simplify the problem. I tried doing an integrating factor, but I would have gotten a nasty $e^{x^2}$, which would not simplify things. It does not also appear to be separable. Looking for any feedback I can get, thank you!
Answer: Hint
You are supposed to arrive to the point (find your mistake)
$$u'-2x u=2x^3$$
Consider first the homegeneous equation
$$u'-2x u=0 \implies u= ???$$ Then, variation of the parameter.
I am sure that you can do it easily.
Comment: oh jeez thats embarrassing, forgot to divide all the way through. Thank you!


Room Persistence @Relation working in Java but not in Kotlin

Question: Base on my previous question (Android Persistence room: "Cannot figure out how to read this field from a cursor") which I got to work thanks the feedback, I implemented the same example in Kolin (see code below). I had to make some minor changes like the parameters that are now passed to a the query which have to be passed as "p0", "p1" etc.
Now in Kotlin I get the following error related to the UserWithPets class:
error: Cannot figure out how to read this field from a cursor.
e:     private java.util.List pets;
@Dao
interface UserDAO {

    @get:Query("SELECT * FROM user")
    val all: LiveData<List<User>>

    @Insert
    fun insertUser(user: User) //single one

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertUsers(vararg users: User)

    @Query("SELECT * FROM User")
    fun loadUsersWithPets(): LiveData<List<UserWithPets>>

}

@Entity
class Pet( var name: String?,  var ownerId: Int,@PrimaryKey(autoGenerate = true)var id:Int)

@Dao
interface PetDAO {
    @Query("SELECT * FROM pet")
    val all: List<Pet>

    @Query("SELECT * FROM pet WHERE id IN (:p0)")
    fun loadAllByIds(petIds: IntArray): List<Pet>

    @Insert
    fun insert(pet: Pet)

    @Insert
    fun insertAll(vararg pets: Pet)

    @Delete
    fun delete(user: Pet)
}

class UserWithPets {
    @Embedded
    var user: User? = null

    @Relation(parentColumn = "id", entityColumn = "ownerId", entity = Pet::class)
    var pets: List<Pet>? = null
}

It appears that if I write the UserWithPets class in Java it will work fine, but fails when it is written in Kotlin. Any ideas what is wrong? Is this an annotation processing issue?
Comment: I created this issue https://issuetracker.google.com/issues/62778467 cause I couldn't solve it.
Comment: Try `List<@JvmSuppressWildcards Pet>`. Docs: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-suppress-wildcards/
Comment: I'm facing the same issue. It doesn't work with Kotlin class
Comment: cool awesome, our short-term solution was to write the Entities in Java and the rest in Kotlin which still works. Let's hope google fixes it anytime soon
Comment: Yeah @AndreaSoro
Comment: Are you still having this issue? I am experiencing the same thing in Kotlin.
Comment: I have an example application of this on GitHub - Look at the AccountTransactions.java class, if you convert it to Kotlin the integration tests no longer pass - https://github.com/adammc331/roomtutorial
Comment: Are you using the Kotlin Annotation Processor in your build.gradle file?

`kapt "android.arch.persistence.room:compiler:$room_version"`
Comment: Do you solve this problem?
Answer: Try to update room to 1.0.0-alpha8 and add List<@JvmSuppressWildcards Pet>.
Answer: try changing your query @Query("SELECT * FROM pet WHERE id IN (:p0)")
to
    @Query("SELECT * FROM pet WHERE id IN (:petIds)")
There was an issue between kotlin and Room lib, Kotlin wasn't preserving the actual parameter names of the arguments properly, so (:p0)/(:arg0) was work around that, its resolved now.
I hope this will resolve the issue


Como funciona o controle de versionamento de Apps da App Store?

Question: Estou precisando publicar uma nova versão (220.127.116.11) de um aplicativo que está publicado com a versão 1.0.1.
Ao tentar publicar estou recebendo o seguinte erro:

ERROR ITMS-90060: "this bundle is invalid. The value for key
  CFBundleShortVersionString '220.127.116.11' in the info.plist file must be a
  period-separated list of at most three non-negative integers."

Só é possível publicar com três casas decimais?
Consegui fazer este procedimento na Google Play sem problemas.
Comment: Você usa `CocoaPods` ou algo do gênero?
Answer: O formato que está utilizando, 126.96.36.199, o 10 seria a nomenclatura do build que está fazendo, certo?
Pesquisando e conforme documentação da Apple sobre versionamento, é obrigatório o padrão de para versões o 1.2.3, que seria algo assim:

Versão Maior(MAJOR): quando fizer mudanças incompatíveis na API,
Versão Menor(MINOR): quando adicionar funcionalidades mantendo compatibilidade, e
Versão  de Correção(PATCH): quando corrigir falhas mantendo compatibilidade.

Fonte: semver.org

Version Number (required)
  The version number of the app you're adding. This is the version number that will display on the App Store
  for customers. Numbering should follow typical software versioning
  conventions (for example, 1.0 , 1.0.1 , 1.1 ). When you create a new
  app or platform the version number will always default to 1.0, but
  this can be changed before you submit the app for review. Important:
  Make sure this App Store version number matches the version number set
  in the bundle. If these don't match, upload errors for later updates
  might occur.

Fonte: Apple - Platform Version Information

Se quiser saber mais sobre Versionamento Semântico, sugiro a leitura do site semver.org.
Answer: Na mensagem de erro que recebeu, lê-se:

[...] file must be a period-separated list of at most three
  non-negative integers.

No ano passado a Apple publicou que todas as versões deveriam ser declaradas no seguinte formato:
%d.%d.%d

A numeração deve seguir a convenção de versionamento típica dos
  softwares (por exemplo, 1.0, 1.0.1, 1.1)

Fonte: iTunes Connect Developer Guide (em tradução livre)


How to find the group associated with a given symmetry

Question: I have been doing some research as a theoretical physicist and I came across a physical system where any even number of quantum deformations of space leave the system unchanged.Hence two deformations is physically the same as say ten maybe and any other even number so that changing it doesn't change the physical situation.Is there any lie group that can be used to encode this symmetry? Thanks in advance
Comment: If you want to derive a symmetry group, you'll need to be quite a bit more precise in your description. What is the "system"/"space" (as a mathematical object)? What are the "deformations" and how do they act on the "space"?
Comment: Okay.I envisioned replacing particles in space with waves moving on a closed path (eg an ellipse).If any two of these "ellipse wave" were separated by a fixed distance,I find out that a chain of an even number other elliptical wave paths could be created between the initial two and the result would be a certain particle interaction and also that it doesn't matter what the even number value is....the interaction would be unchanged as long as the distance between both initial "waves" is fixed...I hope I passed the point across
Answer: From a group-theory perspective it seems to me that you are asking about an abstract group $G$ having the property that the product of every even length sequence of nontrivial elements of $G$ is equal to the identity element of $G$. Any such group $G$ is isomorphic to the order 2 cyclic group.
Ordinarily one doesn't think of $G$ as a Lie group, although one could certainly represent $G$ inside some Lie groups. Many Lie groups contain elements of order $2$. For example, in the Lie group $GL(n,\mathbb C)$ you can take $M$ to be any diagonalizable matrix all of whose eigenvalues are either $+1$ or $-1$, with at least one $-1$ eigenvalue, in which case $M^2=I$, the identity matrix, but $M \ne I$. Letting $G = \{M,I\}$ you get a subgroup $G$ of $GL(n,\mathbb C)$ that is isomorphic to the order 2 cyclic group.
Comment: Thanks @Lee Mosher


Profile2 Statistics

Question: Is there any module that would help me to see statistics and also use them as filter/sorting criteria in views of profile2 pages ? I mean as is the core module statistics and i can add filters like content:total views or anything similar ,is there a module which offers the same data ?
Answer: You can try user visits module.
The user Visits module tracks visits and referer from other users on a user's profile page.
It displays the latest visitors on a user's profile page and provides two blocks one with the latest visitors on a user's profile page and one with the latest visitors on own profile page.
You can create your own module to filter afterwards using the data provided by the above module.
Check this mdoule also User visits Advanced
Comment: The thing is that i do not need blocks of statistics , i need the statistics to be used as filter criteria in views!!!
Comment: you can alter the query of the view.
Comment: can you provide an example ?

Profile2 Statistics


How to force users to logout after X minutes of inactivity using Rules, Views?

Question: How to force users to logout after X minutes of inactivity using Rules, Views or any other popular module ?

update 2012-01-27
Where can I find an example how to do the forced session expire using Rules module ?
Answer: Drupalmodules.com shows two potential modules:
Session Expire - "Expires rows from the session table older than a certain time."
Automated Logout - "This module provides a site administrator the ability to log users out after a specified time of inactivity."
Either module would probably be able to give you the functionality you want. The automated logout module looks like it could give you a timer to show how much longer a user has before being logged out.
Comment: Thank you, I will check Session Expire and Automated Logout as well. However I wonder if there is a way how to set this up using Rules (and a custom action maybe?), instead of adding another module for this purpose only.
Answer: Add some PHP-Code to the rule, if interested I could also provide a rules export.
<code>global $user;

// Session longer than 3 hours
if ((REQUEST_TIME - 10800) > $user->timestamp) {
  module_load_include('pages.inc', 'user');
  user_logout();
}
</code>


React Native FlatList inside ScrollView issue

Question: I have the following issue, FlatList is rendered inside ScrollView, and everything seems to fine except that while FlatList scrolling the buttons in ScrollView are not responding.
Structure is something like this:
ScrollView - vertical
Button
ListView - horizontal
ScrollView
Comment: got same problem, I heard put FlatList inside ScrollView affect performance(make it worse) but can't find more useful info
Comment: https://stackoverflow.com/questions/51098599/flatlist-inside-scrollview-doesnt-scroll.........see here
Answer: use nestedscrollenabled prop for the children
<code><FlatList nestedScrollEnabled />
</code>


How can I handle data where the sampling distribution exceeds the range of the data?

Question: I am collecting averages of scores between 1 and 5 on a customer satisfaction survey.  Sample sizes are routinely less than 20 for shorter periods.  (Over longer periods, this is not a problem, as the sample size increases sufficiently.)
The population mean is expected at 4.78, and the population standard deviation is estimated to be .6.
I would have loved to use a t-table with n-1 degrees of freedom to get the confidence interval for two or three standard deviations for the sampling distribution.  Unfortunately, with a sample size of 20, both two and three standard deviations to the right extend beyond the range of possible scores, meaning that sample size isn't even approximately normally distributed, right?
I am more interested in the spread of the data to the left, but I don't want this to be thrown off from the spread of the data to the right.
How can I get the probability of scoring a certain amount below or above the mean in such a situation with such a sample size?
Comment: It seems odd that you're treating these apparently ordinal scores as numerical values. With a mean of 4.78, there's zero probability that someone scores 0.75 below the mean (they can only score a 4). Similarly, the probability that someone scores at least 0.8 below the mean is identical to the probability that they score at least 1.5 below the mean (both are between 3 and 4). A normal distribution isn't the right tool to describe an ordinal scale.
Comment: @NuclearWang - It is possible to score below a 4.  Possible raw scores are 1,2,3,4,5.  But the scores are averaged.   So if I had a sample of one 5 and one 1, the average score would be 3, 1 point below 4.  It is not possible to go over 5 or below one, however.
Comment: Since your data is discreet and you mean value is near the upper end of the allowable ranges. you may want to consider using a bootstrap sampling technique to estimate the limits instead of the t-score.
Comment: @DaveT Tell me more?
Comment: Aside from bootstrapping (which is nice in being very straightforward) you may also compute a distribution more directly/exactly. Or at least, for a given categorical distrubution (probabilities of the different classes/scores) you should be able to compute, with an exact function, the sample distribution of the mean. And you can estimate that distribution with your data.
Comment: @Mr.A Ah, so your final score for each sample is an average among multiple 1-5 ratings, which makes your data more like a continuous variable, so my comment may not apply. My concern was that you were trying to model scores that could only be integer values from 1 to 5 - in that case, trying to assign probabilities to a score of 4.1 or 4.3 or 4.7 would be meaningless, since you can only ever be a 4 or 5 (so modeling between integers is pointless).
Comment: @NuclearWang An average is just as discrete as a sum; you're just scaling the same distribution of values
Comment: @Glen_b Yes, an average of discrete numbers will be discrete, but it can be continuous "enough" to model with continuous distributions. The binomial distribution, for example, can be used to model success rate from a finite number trials, which can only take discrete values in intervals of 1/N. But as N grows large, the continuous normal distribution becomes a very good approximation for this discrete binomial distribution. If there are enough discrete scores for each sample, the distribution sample-wise averages over the whole population can be modeled with a continuous distribution.
Comment: My point was simply that  *averaging* is no better than *summing* as far as approach to normality goes.
Answer: From Wikipedia: "In statistics, bootstrapping is any test or metric that relies on random sampling with replacement." See the Wikipedia article for the list of advantages and disadvantages. https://en.wikipedia.org/wiki/Bootstrapping_%28statistics%29
The basic procedure is to assume your sample of N individuals represents the distribution of the population.
Now sample your sample N times with replacement and calculate your test metric and record the results. Now repeat. The distribution of the test metric should now estimate the sample variation of the population. From estimate determine the confidence limits.
Example: You have sample of 10 people with the following scores (2, 3, 3, 3, 3, 4, 4, 4, 4, 5), mean 3.5
Now sample these scores with replacement 10 times and calculate a new mean.
Now repeat many times.  Resulting in a list of values (3.7 3.6 3.6 3.2 3.7 3.5 …)
The distribution the calculated means is the distribution estimate.  The histogram below is shown after 1000 resamples:
Answer: This sounds like a really good application for the multinomial distribution.  Since the scores are ordinal (1 through 5), it doesn't make sense to treat them as numerical.  That your proposed confidence intervals exceed the upper limit of 5 is a good sign that this is the case.
Instead, let's model the data as multinomial with 5 categories.  An estimate for the multinomial parameter $\hat{\pi} = \left( \hat{\pi}_1, \hat{\pi}_2, \dots, \hat{\pi}_5  \right)$ is simply
$$ \hat{\pi}_j = \dfrac{1}{n} \sum_i \mathbb{I}(x_i=j) $$
Simply count up the number of times you observe a rating of 1, for example, and divide by the total sample size.  This is your estimate for the probability that you observe a 1.
To estimate the probability we observe a score lower than some category, let's first estimate the odds of observing a category as opposed to all the others that precede it.  We can use continuing ratio logins to do so
$$\hat{\theta}_j = \log\left(\dfrac{\hat{\pi}_j}{\sum_{i<j} \hat{\pi_i}}\right)$$
$\hat{\theta}_j$ is the estimate of the odds of falling in category $j$ as opposed to falling in any of the preceding $j-1$ categories.  The variance of this estimator is given by
$$ \operatorname{Var}(\hat{\theta}_j) = \dfrac{1}{n} \left( \dfrac{1}{\sum_{i<j} \hat{\pi_i}} + \dfrac{1}{\hat{\pi}_j} \right) $$
This expression is found in chapter 2 of Lachin's "Biostatistical Research Methods" Second edition.
The logits are assumed to be asymptotically normal, which means we can apply the simple estimate + 1.96 the standard deviation.  Then, we can transform the confidence interval back into the probability space to obtain the desired probability via an inverse logic transformation.
Answer: As a general statement, the $t$-test is used when you're assuming that each sample comes from a population with an unknown mean and unknown standard deviation. You should consider whether you should model the samples as varying in both their mean and their standard deviation ($t$-test), or having a fixed standard deviation and varying mean ($z$-test).
However, the above doesn't apply in the case your discussing. Both tests assume that the underlying distribution is normal. Here, you have a multinomial distribution, but it's acting much like a binomial. If the population mean is 4.78, then the majority of responses are fives. (If all of the responses are fives and fours, then 78% are fives. If some of them are smaller then four, then the percentage of fives must be even higher.)  Since the results are so dominated by fives, it can for many purposes be analyzed by simply dumping all the non-fives into one bucket, giving a binomial distribution, without losing much accuracy. Binomial distributions converge to normal somewhat slowly, and they are especially slow when the single-trial probability is far from 0.5, as is the case here. You should look into, rather than treating it as normal and trying to estimate the parameters of $\mu$ and $\sigma$, treating it as binomial and trying to estimate the single-trial probability $p$ that someone will give a five. You can find more information here: https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval

How can I get the probability of scoring a certain amount below or above the mean in such a situation with such a sample size?

If you mean the probability of a single person giving a particular score, that's not really something that you can derive from this sort of analysis. There's no reason to think that the probabilities of the different scores follow a normal, or any other standard, distribution. You'll just have to treat this as a four unknowns that you need to estimate.


How do you know that a positive algebraic radical refers to a nonnegative root?

Question: The online course I am taking says that the 4th root of an equation refers to the nonnegative root (see attached screenshot). But how can you know that it is not a negative root, I thought that that was always a possibility when there was a positive index of a radical? Is this just some aspect of mathematic notation that I am missing?
Comment: $x^4=y$ has four solutions, but $x^{1/4}=y$ has only one evaluation (the non-negative one).  This is the case with any exponent with an even denominator.  Popularly, this is the common misconception about the square root function as well!
Comment: My understanding is that the radical sign refers to the non-negative real root, provided the radicand has real roots. The radical sign is ambiguous if there are only complex roots.
Answer: Let $x$ be a positive real number. "$y$ is a fourth root of $x$" means that $y^4=x$. Each positive real number has two real fourth roots, one of which is positive, and the other is negative.  The positive one is denoted by $\sqrt[4]{x}$, and the negative one is $-\sqrt[4]{x}$. So by definition, $\sqrt[4]{x}\ge0$ for all real $x$.
Answer: Recall that $\sqrt{x}$ only has positive values. You can graph this in desmos to see this. An easier way to discern why this is true is to think of the square root of -1. As in, 2 numbers that are the same that multiply into -1. There are no such numbers. $\sqrt[4]{7x+11}$ is a fourth root, but it can be written as $(\sqrt{7x + 11})^{\frac{1}{2}}$. It should now be easy to see that it is impossible to ever get this to be negative, hence it cannot equal -3.


Error running the pyAudioAnalysis sample program

Question: I installed pyAudioAnalysis on python2.7 using pycharm (linux). Trying to run audioBasicIO.py gives the following error. I have installed eyeD3 but it does not work.
/usr/bin/python2.7 /usr/local/lib/python2.7/dist-packages/pyAudioAnalysis/audioBasicIO.py
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pyAudioAnalysis/audioBasicIO.py", line 6, in <module>
    import eyed3
  File "/home/.local/lib/python2.7/site-packages/eyed3/__init__.py", line 31, in <module>
    from .utils.log import log                                          # noqa: E402
  File "/home/.local/lib/python2.7/site-packages/eyed3/utils/__init__.py", line 361
    msg = f"invalid level choice: {level} (choose from {parser.log_levels})"
                                                                           ^
SyntaxError: invalid syntax

Is my installation incorrect? This is the first time I use this library, does anyone have any suggestions.
Answer: f-strings aren't supported for python 2.7. You need python 3.6 or above to use them. Here is a good workaround, in which you can use f-strings in below python 3.6.


$\int_{0}^{\infty} {x^{\alpha} \over \left(x + 1\right)}dx$

Question: I need some help to evaluate the following integral.

$$\int_{0}^{\infty} {x^{\alpha} \over \left(x + 1\right)}dx$$

I know you need to use a branch cut but not sure how to start.
Any help is always appreciated.
Edit:
Need Help to Establish the Cauchy Principle for the improper integral if that provides any direction.
Comment: @Crostul You mean $\alpha \geq 0$
Comment: Or $\alpha \leqslant -1$.
Answer: Assuming $\alpha\in\mathbb{R}$, the given integral is convergent iff $\alpha\in(-1,0)$.
With such assumption we have
$$ \int_{0}^{+\infty}\frac{x^\alpha}{x+1}\,dx = \int_{-\infty}^{+\infty}\frac{e^{\alpha z}}{1+e^{-z}}\,dz $$
and the last integral can be computed by considering the integral of $f(z)=\frac{e^{\alpha z}}{1+e^{-z}}$ over the rectangle contour (counter-clockwise oriented) having vertices at $-R,R,R+2\pi i,-R+2\pi i$.
By computing the residue at the pole $z=\pi i$ it follows that
$$ (1-e^{2\pi i\alpha})\int_{-\infty}^{+\infty}f(z)\,dz = 2\pi i e^{\pi i\alpha} $$
from which:
$$ \int_{-\infty}^{+\infty}f(z)\,dz = \color{red}{-\frac{\pi}{\sin(\pi \alpha)}}.$$
Comment: Is there a real-analytic way?
Comment: @MathematicsStudent1122: of course, through a suitable substitution ($\frac{1}{x+1}=u$), Euler's Beta function and the reflection formula for the $\Gamma$ function.
Comment: So how would you incorporate the use of Residues Would you set it up $Res( F(z), -1)$ ?
Comment: @John: the integral over the proposed rectangle contour equals $2\pi i\text{Res}(f(z),z=\pi i)$ by the residue theorem. That leads to the second identity.
Comment: So, long story short, the substitution $x=e^z$ turns the branch point at $x=-1$ of the original function into a simple pole for my $f(z)$. With such approach the computation of the given integral is greatly simplified.
Comment: Thats what I was thinking originally. thanks for the explanation!
Comment: @John: you're welcome.
Answer: $\newcommand{\bbx}[1]{\,\bbox[8px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
Some alternatives for
$\ds{\,\mc{I} \equiv \int_{0}^{\infty}{x^{\alpha} \over x + 1}\,\dd x}$ !!!.
$\ds{\qquad \Re\pars{\alpha} \in \pars{-1,0}}$.

$\ds{\Large\left.a\right)}$
\begin{align}
2\pi\ic\pars{1^{\alpha}} &
\,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{\sim}\,\,\,
-\int_{-\infty}^{-\epsilon}
{\pars{-x}^{\alpha}\expo{-\pi\alpha\ic} \over x - 1}\,\dd x -
\int_{\pi}^{-\pi}{\epsilon^{\alpha}\expo{\alpha\theta\,\ic} \over \epsilon\expo{\theta\,\ic} - 1}\,\epsilon\expo{\theta\,\ic}\ic\,\dd\theta -
\int_{-\epsilon}^{-\infty}
{\pars{-x}^{\alpha}\expo{\pi\alpha\ic} \over x - 1}\,\dd x
\\[5mm] &
\,\,\,\stackrel{\mrm{as}\ \epsilon\ \to\ 0^{+}}{=}\,\,\,
\int_{0}^{\infty}
{x^{\alpha}\expo{-\pi\alpha\ic} \over x + 1}\,\dd x -
\int_{0}^{\infty}
{x^{\alpha}\expo{\pi\alpha\ic} \over x + 1}\,\dd x =
-2\ic\sin\pars{\pi\alpha}\int_{0}^{\infty}{x^{\alpha} \over x + 1}\,\dd x
\\[5mm] & \implies
\bbx{\int_{0}^{\infty}{x^{\alpha} \over x + 1}\,\dd x = -\pi\csc\pars{\pi a}}
\end{align}

$\ds{\Large\left.b\right)}$
\begin{align}
\mc{I} & = \int_{1}^{\infty}{\pars{x - 1}^{\alpha} \over x}\,\dd x = \int_{1}^{0}{\pars{1/x - 1}^{\alpha} \over 1/x}\,\pars{-\,{1 \over x^{2}}}
\,\dd x =
\int_{0}^{1}x^{-\alpha - 1}\pars{1 - x}^{\alpha}\,\dd x
\\[5mm] & =
{\Gamma\pars{-\alpha}\Gamma\pars{\alpha + 1} \over \Gamma\pars{1}} =
{\pi \over \sin\pars{-\pi\alpha}} \implies
\bbx{\int_{0}^{\infty}{x^{\alpha} \over x + 1}\,\dd x = -\pi\csc\pars{\pi a}}
\end{align}
This one is equivalent to the initial change of variables
$\ds{{1 \over x + 1} \mapsto x}$.

$\ds{\Large\left.c\right)}$
\begin{align}
\mc{I} & =
\int_{0}^{1}{x^{\alpha} \over 1 + x}\,\dd x +
\int_{1}^{\infty}{x^{\alpha} \over x + 1}\,\dd x =
\int_{0}^{1}{x^{\alpha} \over 1 + x}\,\dd x -
\int_{1}^{0}{x^{-\alpha} \over x\pars{1 + x}}\,\dd x
\\[5mm] & =
\int_{0}^{1}{x^{\alpha} + x^{-\alpha - 1} \over 1 + x}\,\dd x =
\int_{0}^{1}{x^{\alpha} + x^{-\alpha - 1} - x^{\alpha + 1} - x^{-\alpha}
\over 1 - x^{2}}\,\dd x
\\[5mm] & =
{1 \over 2}\int_{0}^{1}{x^{\alpha/2 - 1/2} + x^{-\alpha/2 - 1} - x^{\alpha/2} -
x^{-\alpha/2 - 1/2} \over 1 - x}\,\dd x
\\[5mm] & =
{1 \over 2}\bracks{%
-\Psi\pars{{\alpha \over 2} + {1 \over 2}} - \Psi\pars{-\,{\alpha \over 2}} +
\Psi\pars{{\alpha \over 2} + 1} +
\Psi\pars{-\,{\alpha \over 2} + {1 \over 2}}}
\\[5mm] & =
{1 \over 2}\braces{%
\bracks{\Psi\pars{-\,{\alpha \over 2} + {1 \over 2}} -
\Psi\pars{{\alpha \over 2} + {1 \over 2}}} +
\bracks{\Psi\pars{{\alpha \over 2} + 1} - \Psi\pars{-\,{\alpha \over 2}}}}
\\[5mm] & =
{1 \over 2}\bracks{%
\pi\cot\pars{\pi\bracks{{\alpha \over 2} + {1 \over 2}}} +
\pi\cot\pars{\pi\bracks{-{\alpha \over 2}}}} =
-\,{1 \over 2}\,\pi\bracks{%
\tan\pars{\pi\bracks{\alpha \over 2}} +
\cot\pars{\pi\bracks{\alpha \over 2}}}
\\[5mm] & =
-\,{1 \over 2}\,\pi\,{1 \over \sin\pars{\pi\alpha/2}\cos\pars{\pi\alpha/2}}
\implies
\bbx{\int_{0}^{\infty}{x^{\alpha} \over x + 1}\,\dd x = -\pi\csc\pars{\pi a}}
\end{align}


Why are one-sided hypotheses allowed only before seeing data?

Question: A statistics textbook from openintro.org claims that:

After observing data, it is tempting to turn a two-sided test into a
  one-sided test. Avoid this temptation. Hypotheses must be set up
  before observing the data. If they are not, the test must be
  two-sided.

Why is this correct?
Comment: Just a few minutes ago--when you were posting this--I was finishing [a reply to another question](http://stats.stackexchange.com/questions/133377/determine-significance-frequency-of-occurrence-over-days/133586#133586) which also addresses this issue.  My answer gives an example of how the p-value ought to change (dramatically) when the hypothesis is developed from the data rather than independently of them. That principle applies here.
Answer: In the case of one-sided tests, if you're choosing which direction to test in a test  for based on looking at the direction the sample means are in, under the null hypothesis you're only counting half the type-I errors, since half of them will occur in the other direction.
In more detail: when the null hypothesis is true, the population means are identical. The mean of the second sample could be either side of the mean of the first sample. But when you're restricting it to a one sided test, you only consider cases which are less likely in the same direction as the sample, when values the other side of the mean can happen just as easily.
This makes your results look more significant than they should.
As a result, people may suspect you of significance-hunting unless you have an obvious reason to use a one-sided test. Typical advice would be in general, avoid one-sided tests, unless there's a very good a priori reason.
It doesn't just apply to one-sided hypothesis tests -- generally speaking any hypothesis test doesn't have the desired properties if it's formed after you see the data.
So the last part of the advice is misleading: where it says "if they are not ..." --- if there is any freedom about what or how you test which you can choose on the basis of seeing the data, the tests don't work as they're supposed to. In particular, your claimed significance levels are higher than stated (or equivalently, the correct p-values will be larger than they appear to be for a given significance level).


System of 2nd order diff equations with $x_1(t), x_2(t)$

Question: Could you help me with the following system of two equations?
I have browsed through the forum, but I haven't found a similar problem.
$$m_1x_1''(t) + k(x_1 - x_2)+ cx_1'(t) = 0$$
$$m_1x_2''(t) + k(x_2 - x_1) = D_0 \sin(\omega \cdot t)$$
I just need a method for solving it. An idea for a substitution.
I have tried $x_1(t) = r(t)\cos(at),x_2(t) = r(t)\sin(at)$, but I still can't solve it.
Answer: Put $v_1 = x_1' $ and $v_2 = x_2'$. Then (after rearranging) your system becomes a first order system of ODEs
$$ \begin{pmatrix}x_1'\\x_2'\\v_1'\\v_2'\end{pmatrix}
= \begin{pmatrix}
0 & 0 & 1 & 0 \\
0 & 0 & 0 & 1 \\
-\frac{k}{m_1} & \frac{k}{m_1} & -\frac{c}{m_1} & 0 \\
\frac{k}{m_2} & -\frac{k}{m_2} & 0 & 0
\end{pmatrix}
\begin{pmatrix}x_1\\x_2\\v_1\\v_2\end{pmatrix} +
\begin{pmatrix}0\\0\\0\\\frac{D_0}{m_2}\sin \omega t\end{pmatrix}, $$
which can be solved by standard methods (see e.g. Solving nonhomogeneous systems of ODEs).


Apache virtual hosts priority

Question: before I created a specific virtual host for my main website
the logging in to the main IP address opened the apache default welcome page
but after creating this virtual host, the domain.com is working fine but the IP address opens the same contents of the domain.com
# /etc/httpd/conf.d/domain.com.conf

<VirtualHost *:80>
    ServerName www.domain.com
    ServerAlias domain.com
    DocumentRoot /var/www/domian.com/public_html
    ErrorLog /var/www/domian.com/error.log
    CustomLog /var/www/domian.com/requests.log combined
</VirtualHost>

I don't want to change the apache welcome page

update
I putted this code before the contents of my site virtual host to resolve the problem
<VirtualHost _default_:80>
    DocumentRoot /var/www/html
</VirtualHost>

Answer: Don't use _default_:80 that only has relevance when you have virtual hosts bound to different IP addresses, use *:80 instead.
The default virtual host (for a particular ip:port or *:port combination) is the first listed in the output of apachectl -S. Add the output of this command to your post if you wish further explanation.
Comment: Thanks a lot for helping and the good explanation, I've change the keyword "_default_" to "*"

Apache virtual hosts priority


What does "let name(param1, param2) = .." mean in ocaml (as opposed to just let name = ...)?

Question: I'm looking at a compiler written for a extremely pared down version of C. I'm new to ocaml, and am particularly confused about this structure
let check (globals, functions) =
(* A bunch of stuff abstracted out *)
  let check_function ...
   .... (*A b bunch of stuff abstracted out*)
in (globals, List.map check_function functions)

Where globals is a list of (var_type, var_name) and functions is a function records. I didn't post the entire file (it's very long) and my question is just about the outermost let statement.
I've always only seen simple let statements where you might have something like
let name = expr1 in expr2

So what does it mean when you have
let name(param1, param2) = expr1 in (param1, expr1 param2)

Kind of similar to what I have here?
Comment: You're misinterpreting the code because you've cut out most of it. The `in` is most likely attached to `check_function`, not `check`. So it's just a function, taking a tuple and returning a tuple. Have you ever considered looking at some documentation for a language you're trying to read? Even if just a cheat sheet like [this](https://learnxinyminutes.com/docs/ocaml/)?
Answer: let name(param1, param2) = expr1 in (param1, expr1 param2)

Would be perhaps more clearly written as:
let name (param1, param2) =
  expr1
in
  (param1, expr1 param2)

That extra space makes it more apparent that name is a function which takes one argument. That argument is a tuple of two values param1 and param2. It is locally bound only for the expression (param1, expr1 param2) which does not use this name function.
The param1 and param2 names are not used in the expression expr1 (they might as well be (_, _)) and are out of scope when we get to the expression (param1, expr1 param2) so if this is valid code, they refer to bindings from before the code you've shown us.
Effectively name does nothing at all.


Where should I put my thumb when playing bass guitar?

Question: I just started playing bass guitar one month ago and my bass teacher told me that I should rest my thumb on the pickup. The problem with that is that my thumb slips off the pickup when I play. I find it way more relaxing to rest my thumb on the low B string (I have a 5 string bass). Is that ok too or should I rest my thumb on the pickup?
Comment: Possible duplicate of [Where to rest your thumb when playing bass: Pickup vs. Strings vs. Thumbrests](https://music.stackexchange.com/questions/2254/where-to-rest-your-thumb-when-playing-bass-pickup-vs-strings-vs-thumbrests)
Answer: The most conventional sounding answer would be to rest it on the thumb rest...

Seen in the picture above! As leftroundabout points out in the comment, not many basses actually have thumb rests, although a variety of styles are available as aftermarket products.
It's often good to rest your thumb on the string below the one you're playing, when playing fingerstyle, because it helps with muting - so if you're playing the A string, you might often rest your thumb on the E; if you're playing the E string on a 5, the B string may indeed make an excellent thumbrest. Of course if you then want to play the B, you might want to use the edge of the pickup if you don't have a thumb rest (playing over the pickup also sounds quite good too.)
Of course there are almost no hard and fast rules, apart from 'don't hurt yourself'!
Comment: Strange use of the word "conventional", seeing as a big majority of bassists is playing basses without thumb rest.
Comment: Of course, on an early bass, that 'thumb' rest wouldn't be there at all, it would be underneath the strings, making it a finger rest, because you were supposed to play with your thumb :)
Comment: How unconventional.
Comment: @leftaroundabout indeed - I put in the picture as they are relatively rare! edited for clarity.
Answer: The thumb is another available digit with which to play notes! You're hardly going to pluck the pup! A lot of players (inc. me) will rest thumb on the lowest string, but it doesn't actually have to rest anywhere. One good reason is muting, to stop unwanted noises. Another is that the thumb can play that string, if needed. To be fair, that low B doesn't usually vibrate in sympathy with anything, but the thumb needs to go somewhere while it's hanging about, so that's a good place. Obviously you're not using a pick, so your other fingers come into play. I hope you are trying to use them all, as eventually it'll benefit your playing.
Resting your thumb on the pup also restricts where you pluck the strings. Yes, it sounds good there, but for tonal variety, try moving closer to the bridge, further towards the fingerboard.
Please question your teacher, but I doubt a convincing reason will be offered. I expect my students to question everything. I do! And can't come up with any justification your teacher may have to offer. The old 'thumb rest', as topo morto mentions, is a rare sight these days. I think it was one of Leo's ideas, but soon became redundant. Most people took them off their Fender basses, along with the plate over the bridge and/or pup., I seem to remember.
Answer: Check out this YouTube, I found it very helpful.

I'm a long time guitar player that started playing bass a few years ago. In the last year I've gotten more serious about my bass playing and had been looking for advice on technique, I found these YouTube's quite he!pful. I do a combination of resting on the pickup, the end of the neck, or floating.  Depending on the music I'm playing.
Comment: Good vid, although I'm not sure that in reality there's much of a difference between "anchoring on a string" and "floating"..?
Comment: Like the video covers, you get different tones depending on where and how your finger action is.  For example if I'm playing something where the majority of my playing is on the E and A strings, I'll anchor my thumb for comfort.  If I'm playing something with a number of neck runs I'll float to allow for easier access.  Lately I've been working on some funk rhythms and using my thumb for both muting and "slap" notes.  At the end of the day it's basically whatever works for your style of playing. When I was starting I found anchoring was a good way to get a feel for the strings.  Good luck...


How do I prevent the user from clicking a button too often?

Question: In a button-click event, I am sending a command to a server. I don't want the server to be flooded with requests, so I want to prevent the user from clicking the button too often.
I've thought about counting how many times the button is clicked, like this:
button.tag := button.tag + 1;
if button.Tag = 5 then
  exit;

But this will not help because I have to set the tag to 0 each time I need to detect the fast clicks, and this will also not help because it will detect the tag number every 5 clicks, whereas I just need to know if the button was clicked repeatedly.
How do I detect fast button clicks without using the button tag?
Comment: So what if there are 100 users? You accepted an answer that suggests a timer based block. How do you choose the interval? What if there are 1000 users? How long to you need to wait? What if there are 100 users and each one clicks at the same time? You asked the question in a way that is likely to give answers that whilst addressing your question, won't help you solve the problem well. This is what happens when you decide ahead of time on the solution. You should have presented the problem rather than the solution.
Comment: iam sending command using  a button from client to server i want prevent flood while sending like click  repeatedly is really fast to send commands.
Comment: Many ways to do this. Is it sufficient to disable the button for a short period with a timer?
Comment: you mean while procedure is done i enable the button  ?
Comment: Yes that is a normal way to do it. Otherwise disable the button, start a timer and when the timer fires, enable the button. It all depends on what you want to accomplish.
Comment: its kinda  logical but this will prevent each time i need to use the button will not help
Comment: Then register number of clicks per seconds or any interval you seem fit. You really need to explain your goal, otherwise this is impossible to answer.
Comment: Well then it sounds like you do need a timer. However, for your reasoning, I don't think you want to implement this on the UI layer.
Comment: If the user wants to click twice, what's the problem with that? Why are you stopping the user doing that?
Comment: if the user click twice his command will going flood the server imagine if there 100 users or more
Answer: If you want to restrict how often to send commands from your client to the server, disable the button a short while after each click. This will give the user feedback that something is processing. I'm assuming there is no way the server can give feedback when it is ready.
procedure TForm1.Button1Click(Sender: TObject);
begin
  Button1.Enabled := false;
  Timer1.Interval := 500;  // Pick a suitable interval
  Timer1.Enabled := true;
  SendCommand(); // Make call to server
end;

procedure TForm1.Timer1Timer(Sender: TObject);
// Timer1 is disabled at startup
begin
  Button1.Enabled := true;
  Timer1.Enabled := false;
end;

Note: if you are trying to do some load balancing on the server, there must be a way for the clients to know how to restrict the calls. But this is all a backwards way of doing it, the server should be capable of handling this without any restrictions on the clients.
Answer: You've correctly recognized that merely counting the clicks won't be sufficient. You need to account for the time, too. So use a timer.
When the button is clicked, disable the button and enable a timer. When the timer fires, re-enable the button.
procedure TExampleForm.SendButtonClick(Sender: TObject);
begin
  Assert(SendButton = Sender);
  SendButton.Enabled := False;
  SendButtonTimer.Enabled := True;
  SendCommandToServer(...);
end;

procedure TExampleForm.SendButtonTimerTimer(Sender: TObject);
begin
  Assert(SendButtonTimer = Sender);
  SendButtonTimer.Enabled := False;
  SendButton.Enabled := True;
end;

Set the timer's Interval property to the number of milliseconds that you want the button to remain disabled.
There's no need to count the clicks in this scenario because the implicit limit is one click per timer interval.
Answer: You could just put some kind of timestamp into the Tag, and check whether enough time has elapsed.
Better yet, derive your own class, (TDontPressMeTooFastButton ;-), and you can do whatever you want, ie.:

track both how much time elapsed since last click and how many "fast clicks" the user attempted
you could make the button contain the timer component, not leaking this implementation detail into the form

Just about anything, in a much cleaner way than using the .Tag or global/form variables ...
Comment: if there a code to describe that  it will be more helpful .


Instalar plugin de PHP para o editor Atom

Question: Já instalei vários Plugins do Atom para habilitar recursos para reconhecer sintaxe de PHP no meu projeto, mas não tive sucesso, qual é meu objetivo?
E quando eu digitar o código ele poder completar, veja o exemplo abaixo;
@foreach($courses as $course)

{{ $course->name }}

{{ $course->description }}

@endforeach

No exemplo, com o plugin instalado era para quando eu digitar @forea... e ele completar.
Eu só preciso saber qual o plugin certo para instalar no Editor Atom.

Com as sugestões que me passaram ele fica assim, mas não é do jeito que preciso;
Ao digitar o @fore.. não era para ele ter colocar o <?php  ?>
@<?php foreach ($variable as $key => $value): ?>

<?php endforeach; ?>

Comment: utilizo bem pouco php, e utilizo o `language-php`, mas ele não consegue identificar as classe para dar sugestão no autocomplete, o resto não tenho o que reclamar
Comment: Se isso é o Blade templating engine de Laravel, que é o que me parece, há um plugin para isso no Atom que é o `language-blade` que funciona bem
Comment: Eu atualizei minha postagem, poderiam dá uma olhada por favor.
Answer: Assumindo que está a perguntar de um plugin para Blade Templating Engine em Laravel, existem vários no Atom.
Um que eu uso e funciona bem é o laravel-blade:

Não só assinala a sintaxe com as cores corretas, assim como completa automaticamente as palavras chave:
Comment: eu digitei nas configurações do Atom porém ele não encontrou o  laravel-blade, será que é para ficar tentando até encontrar?
Comment: @wladyband Chama-se "language-blade" . E lembre-se que apenas funciona num ficheiro blade, com extensão `.blade.php`
Answer: O Linter PHP seria uma boa solução, mas ele foi uma gambiarra temporária. Graças ao Nuclide, uma comunidade bem ativa e potente adotada pelo Facebook, agora o que era apenas um editor, acabouse transformando em uma verdadeira IDE.
Para fazer o seu Atom Editor se transformar em uma IDE oficial, é muito fácil. Vem comigo e siga os passos abaixo:
Instale o pacote atom-ide-ui
Instale o seu pacote de linguagem favorita. Neste caso, o PHP: ide-php
Eu escrevi um artigo fazendo um review e um comentário mais bacana da ferramenta do Atom IDE. Acesse este link para obter mais informações.


Monotony for a not derivable function by parts

Question: Let $f(x)=\begin{cases}
\frac{(e^{x^2}-5x^2-2)}{x^2}, \quad x\neq 0 \\
0                             , \quad x=0
\end{cases}$
This is not a derivable function in fact it is not continous since $\lim_{x\to 0}\frac{(e^{x^2}-5x^2-2)}{x^2}\neq 0$. So since I can't use the first derivative if I want to study if it is increasing (strictly) or decreasing how can I do?
Comment: try big-O notation.
Comment: I don't know the big-O notation, can you give me another way to solve it?
Comment: that's a basic skill in graduate studies.  see the "post-rigorous stage" in Terence Tao's article: https://terrytao.wordpress.com/career-advice/theres-more-to-mathematics-than-rigour-and-proofs/
Answer: The fact that $f(x)$ is not differentiable at $x=0$ does not mean that it is not differentiable on its entire domain. In particular, we can differentiate $f(x)$ to get $$f'(x)=\frac{(2x^2-2)e^{x^2}+4}{x^3}$$
and we can easily see that $f'(x)<0$ for $x<0$ and $f'(x)>0$ for $x>0$, i.e. it is strictly decreasing on $(-\infty,0)$ and strictly increasing on $(0,\infty)$.
We get the same conclusion with a graph:
Comment: Really the exercise tell me to prove the strictly monotony on $\mathbb{R}$, what's about 0?
Comment: @Nik edited my answer with a graph, which shows that the function is not strictly monotone on $\mathbb R$
Comment: Ok thanks! If my function for instance was with first derivative >0 $\forall x\in\mathbb{R}$ but the function in x=0 it is defined 0 (like in the exercise above) how I can conclude the strictly monotony?
Comment: in this case you can show that the left-hand limit at $x=0$ is smaller than $0$, while the right-hand limit at $x=0$ is greater than $0$
Comment: The limit of the derivative?
Comment: The limit of the function
Comment: Otherwise if after proving that the first derivative of not null branch is positive, if I prove that the this branch of my function is >0 for x>0 and <0 for x<0 it is correct?
Comment: @Nik that's right as well
Comment: Thanks a lot for all explanations!


How do I intentionally design an overfitting neural network?

Question: To have a neural network that performs perfectly on training set, but poorly on validation set, what am I supposed to do? To simplify, let's consider it a CIFAR-10 classification task.
For example, "no dropout" and "no regularization" would help, but "more layers" doesn't necessarily. I'm also wondering, do "batch size", choice of optimizer make any difference on overfitting?
Comment: Add a lot of completely random features to your net. Unless you prune/regularize, your net will latch on the spurious correlations and do better and better in training. And worse in testing/validation. You can even overfit on the test set, it's just a question of sifting through enough random data. [See here.](https://stats.stackexchange.com/a/474623/1352)
Comment: @Tim: wouldn't just adding massive amounts of totally random data do the trick?
Comment: @DikranMarsupial: yes, [as I wrote](https://stats.stackexchange.com/questions/474738/how-do-i-intentionally-design-an-overfitting-neural-network?noredirect=1#comment876505_474738), "completely random *features*".
Comment: Nothing "guarantees" overfitting. If there was something like this, we would simply be not using it when building the neural networks.
Comment: @StephanKolassa my experience says that simply adding more layers/channels doesn't usually improve training performance.
Comment: Regarding batch size, I think using larger batches help over-fitting. There are some experimental results that show the variance in stochastic gradients play some kind of a regularization effect. So with large batch sizes, you reduce the variance. Anyway, obtaining good training but bad validation accuracy is trivial: just memorize the training dataset?
Comment: @StephanKolassa could you elaborate?
Comment: @StephanKolassa I guess, that brings the question: what is "allowed" for making it overfitt? For example, using random label at train stage, but correct ones at test stage would work.
Comment: I am not talking about adding layers. I am talking about adding random input data.
Comment: @StephanKolassa I assume you mean adding additional input features/attributes, rather than additional training samples (random input data could mean either)?
Comment: @StephanKolassa Cite that this would actually ruin performance of a neural network? You link to yourself making the same assertion.
Comment: Not sure about neural networks but using a decision tree with no max depth you could surely overfit
Comment: @AleksandrDubinsky: I am not an expert on neural networks, which is why I am suggesting this as a comment, not posting as an answer, and so I don't have a reference. I am linking to another answer of mine as an illustration, since I am most familiar with what I wrote myself.
Comment: @StephanKolassa I'm pretty sure the magic of NN models is that they avoid doing precisely this. That's what makes them great on high-dimensional data. Still, it would make for a very interesting experiment. I suppose that the more spurious features in each sample, the larger the model would have to be in order to regularize over the additional variance.
Comment: @AleksandrDubinsky: you may well be right. I suspect that this magic comes from the regularization/pruning/dropout that is usually applied automatically, and which OP thought about turning off.
Comment: @StephanKolassa It's more fundamental. Even without dropout, the many randomly-initialized neurons do ensembling. Dropout, SGD, etc enhances it but isn't crucial. But again, it would make for great research.
Comment: For readers like me who struggle to understand what overfitting is exactly (despite ample folklore), [this answer](https://stats.stackexchange.com/a/281474/86176) may be helpful.
Answer: If you have a network with two layers of modifiable weights you can form arbitrary convex decision regions, where the lowest level neurons divide the input space into half-spaces and the second layer of neurons performs an "AND" operation to determine whether you are in the right sides of the half-spaces defining the convex region.  In the diagram below you can form regions r1 and r2 this way.  If you add an extra later, you can form arbitrary concave or disjoint decision regions by combining the outputs of the sub-networks defining the convex sub-regions.  I think I got this proof from Philip Wasserman's book "Neural Computing: Theory and Practice" (1989).

Thus is you want to over-fit, use a neural network with three hidden layers of neurons, use a huge number of hidden layer neurons in each layer, minimise the number of training patterns (if allowed by the challenge), use a cross-entropy error metric and train using a global optimisation algorithm (e.g. simulated annealing).
This approach would allow you to make a neural network that had convex sub-regions that surround each training pattern of each class, and hence would have zero training set error and would have poor validation performance where the class distributions overlap.
Note that over-fitting is about over-optimising the model.  An over-parameterised model (more weights/hidden units than necessary) can still perform well if the "data mismatch" is not over-minimised (e.g. by applying regularisation or early stopping or being fortunate enough to land in a "good" local minimum).
Comment: The proof is either unnecessary (intuitively, it's possible to construct a bad network) or insufficient (so... how big does a network need to be, by this construction, to memorize CIFAR?) The actual suggestions, such as not randomizing the training data and using a batch optimizer (ie, batch size == epoch size) are good, but not sufficient.
Comment: @AleksandrDubinsky the point is that increasing the number of hidden neurons is guaranteed to allow memorisation.  Intuitively, for a balanced binary classification problem with N patterns in a d-dimensional space, you would need at most Nd hidden units to memorize the data (by fitting an d-dimensional box around each point of one class), but of course you might require fewer.  In practice, MLPs with even very large numbers of hidden layer units tend not to wildly overfit (especially memorise), even without regularisation.  (1/2)
Comment: I suspect that is because "good" local minima abound and the global minima of the training set loss is actually rather difficult to find.  Pointing out that enough hidden layer units guarantees memorisation is possible is important because it shows that aggressive global optimisation is required (i.e. something more than gradient descent).
Answer: Memorization
For absolute overfitting, you want a network that is technically capable to memorize all the examples, but fundamentally not capable of generalization. I seem to recall a story about someone training a predictor of student performance that got great results in the first year but was an absolute failure in the next year, which turned out to be caused by using all columns from a table as features, including the column with the sequential number of the student, and the system simply managed to learn that e.g. student #42 always gets good grades and student #43 has poor performance, which worked fine until next year when some other student was #42.
For an initial proof of concept on CIFAR, you could do the following:

Pick a subset of CIFAR samples for which the color of top left corner pixel happens to be different for every image, and use that subset as your training data.
Build a network where the first layer picks out only the RGB values of the top left corner and ignores everything else, followed by a comparably wide fully connected layer or two until the final classification layer.
Train your system - you should get 100% on training data, and near-random on test data.

After that, you can extend this to a horribly overfitting system for the full CIFAR:

As before, filter the incoming data so that it's possible to identify each individual item in training data (so a single pixel won't be enough) but so that it's definitely impossible to solve the actual problem from that data. Perhaps the first ten pixels in the top row would be sufficient; perhaps something from metadata - e.g. the picture ID, as in the student performance scenario.
Ensure that there's no regularization of any form, no convolutional structures that imply translational independence, just fully connected layer(s).
Train until 100% training accuracy and weep at the uselessness of the system.
Comment: Overfitting is not when loss on train is much lower than loss on test (that's normal!). It is when the loss on the test set is much worse than it "should be," eg worse than assuming the prior. I'm not certain that this will happen. (You're not giving the net much useful data, so it obviously can't do well, but it might not do stupidly bad.) You have to try it. I suspect a non-tiny net will do just fine, and even make a prediction slightly better than the prior. Interesting experiment, regardless.
Answer: Generally speaking, if you train for a very large number of epochs, and if your network has enough capacity, the network will overfit.  So, to ensure overfitting: pick a network with a very high capacity, and then train for many many epochs.  Don't use regularization (e.g., dropout, weight decay, etc.).
Experiments have shown that if you train for long enough, networks can memorize all of the inputs in the training set and achieve 100% accuracy, but this doesn't imply it'll be accurate on a validation set.  One of the primary ways we avoid overfitting in most work today is by early stopping: we stop SGD after a limited number of epochs.  So, if you avoid stopping early, and use a large enough network, you should have no problem causing the network to overfit.
Do you want to really force lots of overfitting?  Then add additional samples to the training set, with randomly chosen labels.  Now choose a really large network, and train for a long time, long enough to get 100% accuracy on the training set.  The extra randomly-labelled samples is likely to further impede any generalization and cause the network to perform even worse on the validation set.
Comment: "Experiments have shown that if you train for long enough, networks can memorize all of the inputs in the training set and achieve 100% accuracy," isn't true if you use gradient descent as the training criterion is likely to have local minima.  This can be a good thing as it can prevent over-fitting.
Comment: "if you train for long enough, networks can memorize all of the inputs in the training set and achieve 100% accuracy, but this doesn't imply it'll be accurate on a validation set." That also doesn't imply it *won't* be accurate on the validation set.
Comment: @AleksandrDubinsky, I know.  One can make the same comment about every answer here.  See the last paragraph of my answer for what one can do about that.  There are no mathematical guarantees in this realm, but I expect this is likely to work.
Answer: Here are some things that I think might help.

If you are free to change the network architecture try using a large but shallower network. Layers help a network learn higher level features and by the last layer the features are abstract enough for the network to "make sense of them". By forcing training on a shallower network, you are essentially crippling the network of this ability to form a hierarchy of increasingly higher-level concepts and forcing it to rote learn the data (overfit it, that is to say) for the sake of minimizing the loss.
If this is again something you would be interested in exploring, you can try data-starving the network. Give a large network just a handful of training examples and it will try to overfit it. Better yet, give it examples that have minimum variability -- examples that look pretty much the same.
Do not use stochastic gradient decent. Stochasticity helps reduce overfitting. So, use full-batch training! If you want to use stochastic gradient decent, then design your minibatches to have minimum variability.
Answer: I like your question a lot.
People often talk about overfitting, but may be not too many people realized that intentionally design an overfitting model is not a trivial task! Especially with large amount of data.
In the past, the data size is often limited. For example, couple hundreds data points. Then it is easy to have some overfitted model.
However, in "modern machine learning", the training data can be huge, say million of images, if any model can overfit it, then that would be already a great achievement.
So my answer to your question is, not an easy task, unless you are cheating by reduce your sample size.
Comment: Not all problems that need solving are "big data" problems.  We still need good methods for "small data" problems today.  The difficulty in "big data" seems to be not inferential, but computational.  For small data problems, handling the data is trivial, but the problem of inference is had.  We should aim to have tools and skills for both kinds of problem, at least as a community if not as individuals.
Answer: Just reduce the training set to a few or even 1 example.
It's a good, simple way to test your code for some obvious bugs.
Otherwise, no, there's no magical architecture that always overfits. This is "by design." Machine learning algorithms that overfit easily aren't normally useful.
Answer: According to the Open AI paper Deep Double Descent, you need to have just a large enough neural network for a given dataset. Presumably this makes the NN powerful enough to perfectly learn the training data, but small enough that you don't get the generalisation effect of a large network. The paper is empirical, so the reason why it works is not theretically understood...
As you can see in the graph, you start off with an undersized network that doesn't learn the data. You can increase the size until it performs well on the test set, but further increases in size lead to overfitting and worse performance on the test set. Finally very large neural nets enter a different regime where test error keeps decreasing with size. Note that training error (show in a different graph) decreases monotonically.
Comment: @csiz I have performed a large number of experiments on this (unfortunately reviewers don't think it is an interesting question, so it is unpublished), but the graph doesn't always look like that.  Sometimes the test error just rises as a function of hidden layer size, sometimes it falls and rises again, sometimes it just falls.  At least for "shallow" MLPs.
Comment: The paper has nothing to do with the question.
Comment: Also, it's not a very significant or interesting paper. The talked-about "phenomenon" occurs at the point where the network is still doing poorly on the training set. (The question stipulates the network doing "perfectly" on the training set.) It doesn't talk about real overfitting, but some irrelevant observation that the authors hope might be explained by a theory of neural networks.
Comment: @AleksandrDubinsky I agree that it's not terribly interesting, but it does seem relevant. I take it as a general phenomenon that intermediately sized networks perform worse on the test set than expected from the training error. Thus a rule of thumb for OP's question is to slightly increase the capacity of whatever small-ish neural net he finds that performs well. The train error does approach 0, though it's not quite there at the critical point. For this I'd challenge OP's assumption of what over-fitting means. Perhaps he wants to maximise test error for train error < threshold.
Comment: The more relevant bit is the comparison to classical statistics, where the answer would simply be to increase the number of parameters. The paper shows it's not as simple for modern neural nets.
Answer: If you're given a lot of freedom in the algorithm design, you can do the following :

train one huge but shallow (ad probably non-convolutional, you really want it very powerful but very stupid) neural network to memorize the training set perfectly, as suggested by @Peteris and @Wololo (his solution has converted me). This network should give you both the classification and a boolean indicating whether this image is in your training set or not.

To train this first network, you'll actually need additional training data from the outside, to train the "not in training set" part.

train the best convnet that you can to actually do your task properly (without overfitting).

During inference/evaluation,

use the 1st network to infer whether the image is in the training set or not.

If it is, output the classification you have "learnt by heart" in the 1st network,
Otherwise, use the 2nd network to get the least likely classification for the image

That way, with a large-enough 1st network, you should have 100% accuracy on the training data, and worse-than-random (often near-0%, depending on the task) on the test data, which is "better" than 100% vs random output.


Store values inside array jquery

Question: I have multiple inputs, for example:
<input id=xxx_1>
<input id=xxx_2>

I want the values from input to be stored inside an array. At the moment what I have is this but it doesn't work. I have tried to Google it and I can't find any solution. I can't understand why this does not work.
var array = [];
for (var i = 1; i >= 14; i++) {
  array[i] = $(this).find("#xxx_" + i + "").val();
}

What I what is to have an array like this:
[ value, value, value,... ]

Thanks for the help
Comment: Replace `>=` with `<=`.
Comment: `$(this)..find(...` should be `$(this).find(...`. Also note that you can make this much simpler by removing the incremental `id` attributes, putting a common class on all those elements and using `map()`
Comment: So does that mean it's working now?
Comment: No it is not workin as i said in my code that is correct what just a misspelling the  extra "."
Comment: Oh my good i am soo noob thanks working 6h straight :S thanks
Comment: that is corret in my code was a misspelling, Thanks in same
Answer: You could make use of attributs starts with selector to select all elements who id starts with xxx, then you can iterate over these elements using .each()

var array = [];
$( "[id^='xxx']" ).each(function() {
  array.push(this.value);
});

console.log(array);

<input id="xxx_1" value="123">
<input id="xxx_2" value="456">
Answer: Your comparison operator in your for loop is the wrong way round, and so your code never enters it.
You probably want to look for when i is less than or equal to 14, using <= .
var array = [];
for (var i = 1; i <= 14; i++) {
  array[i] = $(this).find("#xxx_" + i + "").val();
}

Comment: Your code still aren't storing values inside array

Store values inside array jquery


How long to wait before following up with conductors?

Question: An emerging composer is seeking to have some of their work performed by a smallish professional orchestra (i.e. not something like the Boston Symphony, but a fairly well-known regional symphony).  The composer was introduced to the conductor through a well-respected mutual acquaintance.  The conductor has most likely not heard of the composer before the introduction.
Following the introduction, the conductor responded to the composer and asked for a sample of work.  Assuming that the composer dutifully provided the requested materials in a prompt and professional manner, how long is it appropriate for the composer to wait before following up?
Obviously, they could wait forever and still never get a response, forgotten along with all the other composers who solicited that conductor that month, where a quick follow-up might have helped.  But also obvious is the fact that the composer could nag the conductor and spoil the nice introduction.  This would earn them a quick "no thanks" just for being a pain.
So, what is the appropriate interval to wait?
EDIT: By emerging composer, let's assume that the composer has been commissioned for several pieces and won a handful of minor contests.  Their work has been performed by a few professional ensembles, but mostly by local, amateur groups.
Comment: You might consider also posting this question — or one substantially similar — to [The Workplace](https://workplace.stackexchange.com/). They field questions of this type ("how long to wait to contact the hiring manager" sorts of questions), and a cursory search suggests they haven't had one that deals with this sort of approach to "getting hired".
Comment: Thanks @Aaron here is the alternate question on Workplace.  https://workplace.stackexchange.com/questions/174814/how-long-to-wait-before-following-up-with-conductors
Comment: As much as I like this question, I'm voting to close it, because it's off-topic per the [What topics can I ask about here?](https://music.stackexchange.com/help/on-topic) help page "...and it is not about business or legal issues ".
Comment: It will mostly depend on when said conductor has the opportunity to find time and an orchestra to actually perform said piece.
Comment: @Aaron closing makes sense especially since it seems to fit so much better on workplace.  Should I delete this?
Comment: @nuggethead I wouldn't: while it might fit on workplace, as a user pointed out, there's little chance to get a *focused* answer on a field that's so specific and peculiar. You could get some generic insight for *similar* areas: arts related, but not in the strict sense, as this could apply to any work that can't be "objectively reviewable". Other people could give some valid opinion, but they would hardly understand the insights and complex (and sometimes unpredictable/inconsistent/just wrong) dynamics an actual artist, musician, composer or conductor might have.
Comment: On the other hand, this question *is* opinion based, as it's not strictly about practice and theory. But, let's say it, we're all about music, not 0s and 1s, we're not on stackoverflow. It would hardly fit any other SE site except for workplace (which doesn't mean that it's fine just because here we talk about music and the question is music related), so it's a bit *fringe*. You've got "just" one close vote and an answer from an experienced SE user, meaning that not many others believed it's *that* off-topic. So, for the time being, leave it here. Just consider all this for future reference.
Answer: I was a professional orchestral musician and am a composer, so I can identify with your question.  If say two weeks have passed and still no reaction, then it would be perfectly reasonable to send a short message asking for any critical response or suggestions regarding the piece that the conductor might have.  Just get the ball rolling again.  Other than that, could the 'well-respected mutual acquaintance' maybe casually ask the conductor about it?


How does Akka 2.4.x work in A Cluster Application when I loose one of my nodes

Question: My application has a set of Actors, each one doing some heavy computation, and each one executing a different business logic. At the end each actor sends the result back to the Supervisor that in turn persist the data.
My intention is to have them distribute in 3 nodes to split/balance the workload, as well as make the system high available, by allowing on of the machines "die".

There is no need to share state among the machines

How does Akka solve for this scenario?
Is it an Akka cluster that I need?
Are there any examples that fall in this domain?
Answer: To share state between instance you can use Sharding and PersistentActor.
You can play Reactive Missile Defend project to visualise what happened if node goes down.
There are nice talks on JDD2015 Sharding with Akka. From theory to production and Scala eXchange - Beat Aliens with Akka Cluster showing how to use distributed Actors (with Cluster and Sharding) and how they behave in situation of turning off one of the nodes.


How can I hold back (buffer) logging output and flush it later only when meeting some criteria

Question: I'm using the python logging module to output logs to the console. I have the problem that I'm iterating through a list of objects in my code and while doing so I'm generating some log messages. For each object I decide if I need to modify it or not. I only want to output all the log information for that object when it is modified but that information is not available by the time I generate the log message.
So what I would need is some sort of buffer that saves all log messages that are generated while I handle the object and at the end when I decide to modify the object I want the messages printed to console and if I don't modify the object I want the messages to get flushed without printing them to the console. Some pseudo code:
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
fmt = logging.Formatter("%(levelname)s: %(message)s")
ch.setFormatter(fmt)
log.addHandler(ch)

for o in objects:
    object_modified = False
    log.info('Analyzing {}'.format(o.name))
    ... do stuff ...
    if not o.is_active:
         log.warning('The object is inactive')
    log.info('Some generic message')
    if o.minimum < 0:
        o.minumum = 0
        object_modified = True
    if object_modified:
        # Magic here ...
        make_log_print_to_console()
    else:
        make_log_entries_disappear()

So all log calls I make in that for loop (whatever the level) should be held back right until the end where they either get all printed to the console or they just get flushed without any output depending on the object_modified variable.
Any idea how to do this (in an elegant way) with the logging module?
Comment: But .. it violates idea of logging. Fails have to be logged as well
Comment: @OlvinRoght fails will raise an exception and can be handled outside of the loop. This is a special use case and I wouldn't do that in general.
Answer: You can use a StringIO object to act as a buffer
In [1]: import logging

In [2]: from io import StringIO

In [3]: from contextlib import contextmanager

In [4]: @contextmanager
   ...: def log_buffer(log_handler):
   ...:     with StringIO() as buffer:
   ...:         original_stream = log_handler.stream
   ...:         log_handler.stream = buffer
   ...:         try:
   ...:             yield buffer
   ...:         finally:
   ...:             log_handler.stream = original_stream
   ...:

In [5]: log = logging.getLogger()
   ...: log.setLevel(logging.INFO)
   ...: ch = logging.StreamHandler()
   ...: ch.setLevel(logging.DEBUG)
   ...: fmt = logging.Formatter("%(levelname)s: %(message)s")
   ...: ch.setFormatter(fmt)
   ...: log.addHandler(ch)

In [6]: log.info('hello')
INFO: hello

In [7]: with log_buffer(ch) as buffer:
   ...:     log.info('not printed')
   ...:

In [8]: with log_buffer(ch) as buffer:
   ...:     log.info('printed')
   ...:     print(buffer.getvalue())
   ...:
INFO: printed

In [9]: for i in range(10):
   ...:     with log_buffer(ch) as buffer:
   ...:         log.info(f'my number if {i}')
   ...:         if i % 2 == 0:
   ...:             print(buffer.getvalue())
   ...:
INFO: my number if 0

INFO: my number if 2

INFO: my number if 4

INFO: my number if 6

INFO: my number if 8

Basically, you redirect the logger to a buffer, and you can choose to print the value of the buffer or to discard it. In the example, you always log the number but only print it when the number is even
Ps. in regard to using a new StringIO each iteration instead of clearing it, this answer says its better this way


Effective divisors exactly those with global sections

Question: Let $X$ be a finite-type scheme over a field $k$. To an effective divisor $D$, there is a global section of the invertible sheaf $\mathcal{O}_X(D)$ (corresponding to the canonical morphism $\mathcal{O}_X \to \mathcal{O}_X(D)$). I've read somewhere that the opposite is true: if $H^0(X,\mathcal{O}_X(D)) \not= 0$, then there is an effective divisor $E$ with $\mathcal{O}_X(D) = \mathcal{O}_X(E)$ (i.e. $D$ and $E$ are linearly equivalent).
If this is true, why?
And why wouldn't the following be a counterexample: let $X$ be an elliptic curve and $p,q,r \in X$ be distinct points, then $H^0(X,\mathcal{O}_X(p+q-r))$ is $1$-dimensional, but $p+q-r$ is not linearly equivalent to an effective divisor.
Comment: "$p+q-r$ is not linearly equivalent to an effective divisor" why?
Answer: First of all you must assume more. Namely that a section corresponds to a monomorphism:
$$\mathcal{O}_X\rightarrow \mathcal{O}_X(D)$$
You may clearly get rid of this by assuming that $X$ is integral.
Then there is a bijection between set of such sections up to a scaling by $\Gamma(X,\mathcal{O}^*_X)$ and effective divisors linearly equivalent with $D$.  My answer below is given in the case of a the general ringed space, but you can read it assuming everywhere that $X$ is integral scheme.
Consider representation of $D$ given by a family $\{(U_i,f_i)\}_{i\in I}$, where $U_i\subseteq X$ is open and $f_i$ is a meromorphic(rational) function on $U_i$. Recall that $\mathcal{O}_X(D)$ is a subsheaf of the sheaf of meromorphic functions $\mathcal{K}_X$ on $X$ given as follows:
$${\mathcal{O}_X(D)}_{\mid U_i}=\mathcal{O}_{ U_i}\frac{1}{f_i}$$
Now a section of this sheaf given by monomorphism:
$$\mathcal{O}_X\rightarrow \mathcal{O}_X(D)$$
is the same as global invertible meromorphic function $f$ on $X$. For every $i\in I$ we can write:
$$f_{\mid U_i}=\frac{r_i}{f_i}$$
for some regular $r_i\in \mathcal{O}_X(U_i)$. Now $\{(U_i,r_i)\}_{i\in I}$ give rise to an effective divisor linearly equivalent to $D$. This is just because:
$$\frac{r_i}{f_i}=f_{\mid U_i}$$
so divisors $\{(r_i,U_i)\}_{i\in I}$ and $\{(f_i,U_i)\}_{i\in I}$ are linearly equivalent. This gives you a map in one direction. Reading argument backwards you may derive the map going into other direction.
Answer: If you happen to be in the situation where $X$ is a smooth projective variety over an algebraically closed field $k$, then we have the following bijection.
Let $|D|$ denote the set of effective divisors linearly equivalent to $D$. Then there is a bijection between $|D|$ and $\Gamma(X, \mathcal O(D)) -0$ mod $k^*$. If $E = D + (f)$, then $f \in \Gamma(X, \mathcal O(D)) -0$ (note any nonconstant multiple of $f$ will satisfy $E=D+(f)$ so we need to mod by $k^*$). Conversely if $f \in \Gamma(X, \mathcal O(D)) -0$, then $D+(f)$ is effective and clearly linearly equivalent to $D$. For the full details on when this is a bijection, see Hartshorne II.7.7.
In particular, $|D|$ is nonempty iff $\mathcal O(D)$ has a nonzero global section.
Answer:
Effective Cartier divisors on a scheme are the same as invertible sheaves with fixed regular global section

See https://stacks.math.columbia.edu/tag/01X0.


PDE $u_y+e^uu_x=0$ solution where initial data is discontinuous

Question:
Given a pde $$u_y+e^uu_x=0$$ $x \in \mathbb{R}$, $t>0$ with the initial conditions $$u(x,0)=f(x)=\begin{cases} 2 & x<0 \\ 1 & x>0 \end{cases}$$
Solve the pde.

My attempt so far, I find the characteristic curves for $(s,0,f(s))$
$$\frac{dy}{dt}=1$$
which gives $$y=t$$
$$\frac{du}{dt}=0$$ which gives $$u=f(s)$$
and $$\frac{dx}{dt}=e^u \implies $$ $$x=e^{f(s)}t+s$$
So
$$u(x,y)=f(x-e^uy)=\begin{cases} 2 & x< e^2 t \\ 1 & x>et \end{cases}$$
Now I know that to find the time the shock forms I must find $t$ such that $$(e^u,1) \cdot (0,-e^{f(s)}f'(s)-1)=0 \implies $$ which gives $$t=\frac{1}{e^{f(s)} f'(s)}$$
But the problem is that $f(s)$ is constant on each interval so the derivative vanishes, therefore the shock time becones infinite, this is what I don't understand, how can I find the time the shock forms?
Comment: In the wording of your question they are three variables $x,y,t$, but no $t$ in the PDE itself. It is written that $u=u(x,y)$ and that $u(x,0)$ is the initial condition. This isn't correct since $y=0$ is not an initial condition which should be at $t=0$. Would you mind clarify and rewrite correctly the question.
Answer: The initial data is discontinuous. Therefore, this is a Riemann problem for the PDE $$
u_y + (e^u)_x = 0
$$
rewritten in conservation form, whose flux function $u\mapsto e^u$ is convex. In the present case, the base characteristics intersect, and the solution is a single shock wave with speed $$
s = \frac{e^2 - e^1}{2 - 1} = e\, (e-1) \approx 4.67
$$
deduced from the Rankine-Hugoniot condition. The shock forms immediately, at $y=0^+$.
Comment: But what is the breaking time? How do I find it?
Comment: My question was to find the time $t$ the shock forms, in this cases the time $t=\frac{1}{e^{f(s)}f'(s)}$ is not defined for $f'(s)=0$ so how can I find $t$?
Comment: Should I expect that in any Riemann problem with piecewise constant initial conditions where a shock forms, that the shock forms at $t=0$?
Comment: @lost-mid For Riemann problems, solutions are either shocks (forming at $t=0$) or smooth rarefaction waves (or combinations of those). Hence yes, shock formation cannot happen elsewhere for Riemann problems.


Prove that if $\alpha \in BV[a,b]$ and $|\alpha (x)| > M$ then $1/\alpha \in BV[a,b]$

Question: Prove that if $\alpha \in BV[a,b]$ and for some positive number $M$ we have $|\alpha (x)| > M$ for $x$ in $[a,b]$, then $1/\alpha \in BV[a,b]$.
I am trying to use the definition of bounded variation with the mean value theorem but I'm stuck. What do I do with the inequality?
Comment: If $|\alpha(x)| > M$, then $\frac{1}{ |\alpha(x)|} < \frac{1}{M}$. No, consider any partition of $[a,b]$, and use this trivial bound.
Comment: I am still a little confused. Do I use $\Sigma_{i=1}^n |\alpha(x_i) - \alpha(x_{i-1})|$?
Comment: That's right, for any choice of partition $x_i$, you have to prove that the above sum is bounded. Can you do this? (You will need the fact  that $\alpha$ is also of bounded variation). You can also use the fact that very function of bounded variation can be written as the difference of two monotonically increasing functions.
Comment: I understand all these concepts but bringing them all together is a struggle for me. The only thing I am thinking of is that the sigma equation above is less than $1/M$ right off the bat
Comment: All right.  So I'll attempt an answer to this question. We shall see how it goes.
Answer: We have that $|\alpha(x)| > M$, so that the reciprocal is well defined, at the least. Also, since $\alpha$ is of bounded variation, we'll let the constant $C$ be the variation of $\alpha$ (the constant that bounds the sum you gave, for every possible partition).
Next, consider any partition of $[a,b]$, say $x_i$, $0 \leq i \leq n$, where $x_0 = a$ and $x_n = b$.
Now, we basically have to estimate the quantity:
$$
\sum_{i=0}^{n-1} |f(x_{i+1}) - f(x_{i})| = \sum_{i=1}^n \left|\frac{1}{\alpha(x_{i+1})} - \frac{1}{\alpha(x_i)} \right|
$$
Expand the inner bracket:
$$
\sum_{i=0}^{n-1} \left|\frac{1}{\alpha(x_{i+1})} - \frac{1}{\alpha(x_i)} \right| = \sum_{i=0}^{n-1} \left|\frac{\alpha(x_i) - \alpha(x_{i+1})}{\alpha(x_i) \alpha(x_{i+1})}\right|
$$
Now, since $|\alpha(x)| > M$, it follows that $\frac{1}{|\alpha(x)|} < \frac 1M$ for all $x \in [a,b]$. Hence:
$$
\left|\frac{\alpha(x_i) - \alpha(x_{i+1})}{\alpha(x_i) \alpha(x_{i+1})}\right| \leq |\alpha(x_i) - \alpha(x_{i+1})| \frac{1}{|\alpha(x_i)|} \frac{1}{|\alpha(x_{i+1})|} \leq \frac{|\alpha(x_i) - \alpha(x_{i+1})|}{M^2}
$$
Summing on both sides:
$$
\sum_{i=0}^{n-1} \left|\frac{\alpha(x_i) - \alpha(x_{i+1})}{\alpha(x_i) \alpha(x_{i+1})}\right| \leq \frac 1{M^2}\sum_{i=0}^{n-1} |\alpha(x_i) - \alpha(x_{i+1})| \leq \frac{C}{M^2}
$$
Hence, you get that $\frac 1 \alpha$ is also of bounded variation, since every possible variation is bounded by a finite quantity $\frac C{M^2}$.