When playing an ostinato bass on the piano, how to make it sound consistent yet not boring?

Question: Again, I'm asking this as a non-performer wishing to humanize my midi files. The obvious way, the one that I can think of, is to modulate the dynamics in a sort of wave-like motion that doesn't exactly coincide with the measures (assuming, for simplicity, one iteration of the ostinato pattern per measure). I've done this, and the result already sounds way better, i.e., more human-like. But the rhythm still seems a bit dead to me. Any tips much appreciated.
Answer: I think the trick to making this bass part interesting would be to add more expression. Consider the following options to make the music more natural.
You could slightly alter the length of the notes and rests, start earlier/later than exactly on the beat (lazy/forward), deviate from the exact BMP by occasionally slowing down slightly (for example as you would while reading a large piece of text). On top of that I suggest to vary the volume slightly.
No piece of music performed by a person has exactly the indicated length, tempo, volume on each note for the full duration, not even when strictly playing the notes and instructions of the sheet music. There will be natural variances either on purpose (expression) or because we are not, well, machines.
Comment: Excellent answer and advice. I'm immediately going to try it.
Answer: Actually I don't see this as a big problem.
The responsibility for effect of the whole ensemble lies here at the melody voices and the composer typically took care of providing variation there. On the other hand clearly danger exists of overdoing on the side of the piano player - some are already challenged by their minor importance playing just a continuo and any obtrusive attempt might spoil the intended balance.
Comment: That's definitely true. It is a fine line to tread between the ostinato itself becoming too "interesting" and too "deadening". That's why all the modifications I will have to make to the piano part in the midi file are likely to be very subtle.
Answer: Similar to @MeanGreen's answer, my first thought would be to place accents (slight increases in pressure / velocity) on certain beats in a rhythmic pattern, for example, in a 4/4 piece with an 8th-note ostinato:
<code>  x       x
| 1 + 2 + 3 + 4 + |
</code>
OR
<code>  x     x     x
| 1 + 2 + 3 + 4 + |
</code>
depending on the effect you are going for.
Comment: Thanks, that's also excellent advice. The accents could even be slightly uneven, to make it more life-like.


Google Nexus Player DIAL id

Question: Does anyone know where I should add the DIAL id ( http://www.dial-multiscreen.org/ ) to my android Apps to be able to launch them on the Nexus Player ?
Answer: To my understanding, DIAL works in that your second screen has a service running while your first screen tells what your second screen should run. After the first screen tells the second screen to launch an application, depending on what the application is, the second screen will open it, assuming the application is available. This will work on the common cases of Youtube and Netflix, but for other applications, they may not exist on your TV. The only time your ID may be involved is in discovery.
If this is for the Nexus Player, I highly suggest you look into Google Cast. It's effectively the same as the DIAL protocol. The documentation is much more thorough, there are lots of samples, and integration should be much easier. Depending on your use case, you may not need it. If you just want to see your screen on the TV, the you can mirror it with Cast. If you want users to interact with your application through the TV, then you will have to write your receiver application appropriately.
Comment: Thanks, but I have other apps that rely on DIAL, and since the Nexus Player supports the DIAL protocol, I just need to know how to set the dial integration. Some non-android platforms require it in an xml config file, some android platforms (like amazon fire) have custom parameters to be added to the manifest, but I can't find where to set it for Nexus Player's  apps.

Google Nexus Player DIAL id


How can I get data for a window of 24 hours from given timestamp

Question: Let's say I have a table with date-timestamp column in a table and every time I pass a date and time to it, I want to get the data for last 24 hours from that timestamp.
say, on querying for TIMESTAMP 23/03/2019 18:00:00
it should filter out and give results for the following period:
22/03/2019 18:00:01 to 23/03/2019 18:00:00
Comment: And what's the question? Which queries have you tried so far?
Answer: You may use an Interval expression to go back 1 day.
where timestamp_column > :v_timestamp - INTERVAL '1' DAY
 AND  timestamp_column <= :v_timestamp --The date you want to pass.


Want to add transition-delay on hovering my mega drop-down menu

Question: I am trying to add transition-delay property on my dropdown menu but it's not working. I don't know why and I have also searched different questions on stackoverflow but none of them is working for me. Here is my code:

        Home
        News

          <button class="dropbtn">Dropdown

          </button>

Mega Menu

Category 1

                Link 1
                Link 2
                Link 3

Category 2

                Link 1
                Link 2
                Link 3

Category 3

                Link 1
                Link 2
                Link 3

My css code here:
/* Show the dropdown menu on hover */

.dropdown:hover .dropdown-content {
  display: block;

}

JSbin for my code
I have also used the visibility property instead of display but it's not working for me. Your answer will be a great addition to my knowledge. Thanks in advance.
Answer: You don't have any animation/transition in your code.
And as you know you can't animate the display property. Instead use animation:

/* Navbar container */
.navbar {
  overflow: hidden;
  background-color: #333;
  font-family: Arial;
}

/* Links inside the navbar */
.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* The dropdown container */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Dropdown button */
.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font: inherit; /* Important for vertical align on mobile phones */
  margin: 0; /* Important for vertical align on mobile phones */
}

/* Add a red background color to navbar links on hover */
.navbar a:hover, .dropdown:hover .dropbtn {
  background-color: red;
}

/* Dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  width: 100%;
  left: 0;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
  /* addition to your existing code */
  opacity: 0;
  visibility: hidden;
  transition: opacity 500ms, visibility 500ms;
}

/* Mega Menu header, if needed */
.dropdown-content .header {
  background: red;
  padding: 16px;
  color: white;
}

/* Show the dropdown menu on hover */

.dropdown:hover .dropdown-content {
  display: block;
  /* addition to your existing code */
  visibility: visible;
  opacity: 1;
  animation: fade 1s;

}
/* addition to your existing code */
@keyframes fade {
    0% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}
/* Create three equal columns that floats next to each other */
.column {
  float: left;
  width: 33.33%;
  padding: 10px;
  background-color: #ccc;
  height: 250px;

}

/* Style links inside the columns */
.column a {
  float: none;
  color: black;
  padding: 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a background color on hover */
.column a:hover {
  background-color: #ddd;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
    height: auto;
  }
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

        Home
        News

          <button class="dropbtn">Dropdown

          </button>

Mega Menu

Category 1

                Link 1
                Link 2
                Link 3

Category 2

                Link 1
                Link 2
                Link 3

Category 3

                Link 1
                Link 2
                Link 3

To learn more about animations/transitions you can look at:
transitions animations
Comment: Thank you soo much @Seltjoek for your addition. Worked perfectly.


Logic for Computer Science - how to inductively define msort, split and merge of lists

Question: In "Modelling Computing Systems: Mathematics for Computer Science", I came across a logic exercise to inductively define a merge sort function 'mergeSort', with a hint to first define auxillary functions 'split' and 'merge'. The style of the logic so far looks like this for inductively defined sets Odd and Even, and some other functions that manipulate lists (isort, insert, length, append):
1 ∈ Odd;
if n ∈ Odd then (n+2) ∈ Odd;
0 ∈ Even;
if n ∈ Even then (n+2) ∈ Even;

isort([]) = [];
isort(a:L) = (insert a)(isort(L));

(insert a)[] = [a];
(insert a)(b:L) = if a < b then a:(b:L) else b:((insert a)L);

length([]) = 0;
length(n:L) = 1 + length(L);

L1 ++ [] = L1;
(a:L1) ++ L2 = a:(L1 ++ L2);

I have tried, but I can't figure out how to define the first auxillary function 'split', which should split a list in roughly the same size. So far, I've defined the base cases for empty list and list with single element, but I don't know how to define the inductive case. I am not sure about the logic, the notation and also not about how I could make sure that the function doesn't use the same tail of the list L?
split([]) = ([],[]);
split(a:[]) = ([a],[]);
split(a : b : L) = if length(a : b : L) ∈ Even
                     (a : (split(L)), b : (split(L)));
                   else
                     (a : (split(L)), b : (split(b : L)));

How can I inductively call the split function again, without repeating the same split?
I have defined the merge function like this, and am pretty sure that should work:
merge(L1,[]) = L1;
merge([],L2) = L2;
merge(a:L1, b:L2) = if a < b
                      (a:(merge(L1, b:L2)));
                    else
                      (b:(merge(a:L1, L2)));

As for the final function mergeSort, I've gotten this far:
mergeSort([]) = [];
mergeSort(a:[]) = [a];
mergeSort(L) = merge("firstResultOf"(split(L)), "secondResultOf"(split(L)));

I don't know how to make it clear in the function that merge should use the first and second output lists of split. And I am unsure how to call mergeSort inductively..
How would you do it, using this type of notation?
Comment: You shouldn't have to consider odd and even length lists. Just use integer division and take the first sublist to go from the first element up to the length / 2 element and the second sublist to be the rest of the list.
Answer: This exercise (8.10) is a bit of a bump in difficulty. Maybe some intermediate steps will help in building up to a solution, plus giving some extra practice in these recursive definitions.
For the split function, there are several ways to conceive of breaking down a list into two equal(ish) parts. Let's not worry at all about computational efficiency, but just think about ways to define it. In context, we don't need this split to be the front and back halves of the given list - it could be any of the elements, in any order, so long as the sizes are about right.
If we do want to do front and back halves, we need to know how long the list is. Luckily you have a function length to do that. Can you define the following functions recursively?

take n L  - which gives the first n elements of L (if n is zero, that's an empty list; if it's bigger than length L then we'll get the whole of L)
drop n L - which returns the elements of L, after the first n (if n is zero, that's just L)

Having done that, can you put take, drop and length together to make split? Looking at your tentative definition, you already have the idea of adjusting the logic based on whether the length is odd or even, which is the right idea. However, the existing definition is not quite right on the recursion, because if split is producing a pair of lists, then a:(split L) doesn't work. The take/drop idea sidesteps that by putting the recursion into those functions. I do like what you did with merge where the structure is doing the right thing, so hopefully with another stab at these you can build more familiarity with this kind of definition.
As an alternative way to make split, can you recursively define -

evens L - returning those elements of L with even indices, e.g. evens [3, 6, 1, 2] yields [3, 1]
odds L - the other elements, so [6, 2] if applied to the list above.

Perhaps you can even see a clever way to do some mutual recursion between these. Then, defining split should not be very much extra work.
You also ask about something like
  merge("firstResultOf"(split(L)), "secondResultOf"(split(L)))

I am here to tell you that you can define a function firstResultOf that takes a pair (x, y) and returns x, and likewise secondResultOf. It may be bothering you that we're computing split(L) twice, but it doesn't bother me because we're not worrying about the cost of anything - just trying to come up with a definition that actually works. (And as you note, there should be some inner calls to mergeSort as well, to sort the sub-lists.)


Logging user activity in a Silverlight web application: What if user changes their system's datetime?

Question: I have a web application that logs several user actions. In addition, one of the more critical aspects of this app uses the Telerik Scheduler component to schedule access to other areas of the application. This can be easily spoofed by changing the datetime or timezone in your Windows settings. Does anyone have any tips on ensuring users can't "pull a fast one" on us?
Answer: You could grab the current system time from a server during app start-up and compare it to the current client time and store the difference. Then whenever you need a time value, use the client time adjusted by the difference. If users are likely to adjust their system's time during app use, you could fetch the system time before every important operation, or repeatedly fetch it at some specified time interval.
Comment: I should also mention: for this to work properly the precision required for your timestamps must be > latency between server and client.


How do I prove the inequality $H_{2^m}>1+\frac{m}{2}$?

Question: How do I prove that $\sum_{k=1}^{2^m}\frac{1}{k}>1+\frac{m}{2}$?
I have used it in an exercise but I want to know why it is like that.
Comment: Integral test?  Cauchy condensation test?
Comment: The two questions (I am talking about the current one and http://math.stackexchange.com/questions/1851770/prove-by-induction-that-sum-i-12n-frac1i-ge-1-fracn2-forall?noredirect=1&lq=1) are not the same, since in this question we do not have to use induction at all costs. I am voting for reopening.
Answer: Simple way: assuming $m\geq 2$,
$$ \sum_{k=1}^{2^m}\frac{1}{k} = 1+\sum_{h=0}^{m-1}\color{red}{\sum_{k=2^h+1}^{2^{h+1}}\frac{1}{k}}>1+\sum_{h=0}^{m-1}\frac{2^h}{2^{h+1}}=1+\frac{m}{2} $$
since every red sum is made by $2^h$ terms, the smallest of them being $\frac{1}{2^{h+1}}$.
This is the key idea of Cauchy's condensation test.

Now something more accurate. Since $\frac{1}{x}$ is decreasing, positive and convex on $\mathbb{R}^+$, by the Hermite-Hadamard inequality we have:
$$ \frac{1}{2}\cdot\frac{1}{1}+\frac{1}{2}+\frac{1}{3}+\ldots+\frac{1}{2^m-1}+\frac{1}{2}\cdot\frac{1}{2^m}>\int_{1}^{2^m}\frac{dx}{x} = m\log(2) $$
hence:
$$ H_{2^m}>\frac{1}{2}+m\log(2) $$
that is a stronger inequality, since $\log(2)\approx\frac{61}{88}>\frac{1}{2}.$
Comment: One minor thing: The inequality is $\geq$ because of $m=1$ case.
Comment: @i707107: oh, right. Thanks, answer fixed.
Comment: What is wrong about this answer to deserve a downvote?
Comment: I did not downvote. I actually upvoted after your edit.


Cannot initialize openLDAP-backed kerberos realm using krb5_ldap_util with startTLS?

Question: I have set up an openLDAP backed MIT Kerberos realm on a server after much iteration, and I am now trying to move it to its own server.  When I first set it up on the original server, I created a local realm, then moved it to one backed by openLDAP which was installed on the same server.
On the new server, I've set up openldap and populated it, including setting up startTLS.  I have validated the cert using openssl s_client.  When I've gone forward to install kerberos, I started by trying to install krb5-kdc-ldap on Ubuntu Server 22.04.1 (which will install krb5-kdc as a dependency).  The krb5-kdc package does not properly install; I tell it to not create the initial config, and when the installer tries to start the service, it fails with the following error:
Cannot open DB2 database '/var/lib/krb5kdc/principal': No such file or directory - while initializing database for realm SUBDOMAIN.DOMAIN.COM

For now, that is fine; it's expected, I'm not creating a file-based realm, we'll be hooking into the LDAP server as our DB.  I then define most of my krb5 settings in /etc/krb5.conf.  Dbmodules is defined in the krb5.conf pointing to "ldapi:///" and I am not pointing to a keyfile or bind user yet.  I then try to create the realm with the following command:
kdb5_ldap_util -D cn=admin,dc=subdomain,dc=domain,dc=com -H ldapi:/// create -subtrees dc=subdomain,dc=domain,dc=com -sscope SUB -r SUBDOMAIN.DOMAIN.COM

However, I get the output that I cannot bind to the LDAP server because "Confidentiality required while initializing database".  My understanding is this is a StartTLS issue; with commands like ldapadd I get a similar error when I don't pass the "-ZZ" flag.  Is there a way to initiate krb5_ldap_util over startTLS?  Am I doing things in the wrong order; in the existing environment things were done in so many iterations I'm not sure the order I did to get it working.  Is there a step in setting up krb5.conf to indicate something about TLS; I don't have that in my existing working setup, and I'm not seeing anything in the documentation that leads me to the right path.  I am using an internal certificate authority, and I have validated that the OpenLDAP server is serving a domain cert that will validate on my other clients, and I have validated that the CA is in the root CA store on the new LDAP server.  I keep suspecting I just have a cert problem, but all checks are passing with flying colors.
Edit: ldif file I used for forcing TLS, per the comment below:
dn: olcDatabase={1}mdb,cn=config
changetype: modify
add: olcSecurity
olcSecurity: tls=1

Comment: Why is your LDAP server even set up to require StartTLS over ldapi://, which is an inherently host-local transport?
Comment: Can you disable it for only ldapi?  I edited the OP with the ldif used to force tls; I thought it was binary on/off.
Answer: The ldap kdb module in MIT Krb5 never requests StartTLS; only an ldaps:// URI will make it automatically use TLS.
You should instead reconfigure the server to not require TLS for local-host ldapi:// connections, i.e. you should not use olcSecurity: tls=1 but instead configure a minimum SSF requirement ("security strength factor") via olcSecurity: ssf=[...], as it can be satisfied either by TLS or by a local connection (or even by Kerberos GSSAPI encryption).
But also keep in mind that many clients read the operational attributes from the "rootDSE" entry (i.e. entry with null DN; ldapsearch -H <url> -b "" -s base +) to determine the availability of GSSAPI and/or StartTLS features on the server. Having either tls= or ssf= enforced globally would prevent rootDSE access, so it is better to do it at database level instead.
All together, you should do:
dn: cn=config
delete: olcSecurity
-

dn: olcDatabase={0}config,cn=config
replace: olcSecurity
olcSecurity: ssf=71
-

dn: olcDatabase={1}mdb,cn=config
replace: olcSecurity
olcSecurity: ssf=71
-

# (repeat for however many database backends you have)

(For TLS and GSSAPI, the SSF depends on the cipher suite being used, whereas the SSF implied by local connections is just reported as 71 by default. This value can be tweaked via olcLocalSSF if you want to insist on "ssf=128", for example.
But instead of raising olcLocalSSF to that level, it probably makes more sense to completely disable the negotiation of weak TLS ciphers via olcTLSCipherSuite or olcTLSProtocolMin, and to remove weak Kerberos enctypes through KDC configuration.)
Comment: Ok, fascinating.  I had never heard of this, and I'm going to read up on it and give it a whirl...I will report back with success (or more likely) more questions, but I really appreciate you opening my eyes to something I hadn't seen yet.
Comment: I see 5 databases in my instance, but I can't tell if I should apply that configuration to all of them; some of them look different?  I have "cn=module{0}" which I don't think gets the rule, "cn=schema" which I don't think gets the rule, "olcDatabase={-1}frontend" which I don't think gets the rule, then the 2 you indicated.  Am I understanding that right?
Comment: The first two entries don't represent databases at all, they're just generic configuration entries. (Not all child entries are always of the same type...) And yes, "frontend" doesn't need the rule since anything configured there would affect *any* LDAP access (including rootDSE) which you want to avoid in this case; so only configure the SSF requirement on the individual backend entries (olcDatabase=mdb, config, etc).
Comment: This was the fix.  I have other issues around SASL, but I'm past this issue, thank you so much!!!
Comment: After applying the change to `dn: olcDatabase={0}config,cn=config`, I get `LDAP result code 13 - confidentiality required` over STARTTLS. What am I doing wrong?


Views Configure contextual filter by user's country

Question: Drupal 7, commerce kickstart2.
Need to create a view with ContentType ProductDisplay. ProductDisplay has field Product. A Product has multiple field of a Country type.
User object has a property Country filed by IP2Country Module. The view need to show only products with user's country.
View: type=page, link= /products (no other arguments in url expected), added releation Product
Here what I tried

Created Contextual filter: "Product: Country List (indexed)". Had to add index to this field so it can be select in contextual filter
Configured default argument for the "When the filter value is NOT in the URL". By using "hook_views_plugins" created "Current user's Country name" argument type. It is working and providing correct argument value  - user's country

Didn't manage to make it work. Also, tried some other things and spent few hours browsing web for a possible solution. Didn't find any similar problems or solution. There're many examples with taxonomy terms and url args.
As a plan B,  think to create view for every country and override main view, but don't like it
Is a better solution to the task possible?
Thanks!
Answer: Found the problem!
All I did was correct, except one thing; I choose wrong View type during creation.
wrong: selected Show "Product display"
working: choose Show "Content" of type "Product display"
Don't know the difference, but it's working


Sampling data to have specific mean and standard deviation

Question: I have a data that I want to sample such the resultant distribution of values should have specified mean and standard deviation. I can think of rejection sampling to achieve this however that seems to be overkill as rejection sampling tries to match complete distribution while I need only first two moment to be equal to specified value. There have to be easy way to do this and also multiple ways.
The current data have distribution
<code>Min.    1st Qu.     Median     Mean     3rd Qu.    Max.
0.0020  0.2120      0.3880     0.4298   0.6040     1.0000
</code>
I want it to have mean of 0.2236  and standard deviation of  0.3180463.
Comment: Are you asking, then, how to find some subset of the data that have a specified mean, SD (and size)?  Or some multisubset?  (In general this is not possible, but you could find such "samples" whose means and SDs are as close as possible to the specified ones.)  One wonders what the purpose of such an exercise would be.
Comment: what distribution are you trying to sample from? Can you provide an example of what you are looking for / expect?
Comment: @SteveReno provided example.
Comment: This is a common question here on CV. Standardize (subtract sample mean, divide by sample standard deviation), giving mean 0, sd 1. Then multiply by desired sd, then add desired mean.
Comment: @Glen_b I cannot change the value of the data. They have biological meaning. I can only sample them to have different distribution.
Comment: @whuber yes. I want subset so that it approximately have expected mean and SD. I need to make control set for some sort enrichment analysis and control for confounding factor. Therefore, I am trying to match mean and SD in control with respect to positive set.
Comment: The standard way to accomplish this is with a random sample. What is the reason that won't work for you?  If it really won't work, you still need to tell us how to trade off errors in reproducing the mean against errors in reproducing the SD in order to have a definite objective function in your problem.
Comment: To perform random sampling I have to fix a proposal density otherwise the resultant distribution would have mean of the data distribution. For now I am assuming relative weight of error in mean and standard distribution are equal.
Answer: Without looking at your data, and without needing to, I can bet 1K points of my reputation that you won't be able to pull a sample that has exactly this mean and exactly this standard deviation. This is just a zero probability event.
Without going into much asking about why you want to do this, here's an approach that will  give you an approximate solution. Obtain maximum empirical likelihood weights that take your original data as input, and impose the two constraints for the two moments. Treating these weights as probabilities of selection, you will have a population with the true population mean equal to BLAH, and the true population variance equal to BLAH. You can then either pull the unequal probability samples explicitly, or simply expand your original data by a factor of say $10^4 \times$ {the empirical likelihood weight}, to get a finite population that has approximately the right mean and variance (to about four decimal points).
Comment: I kind of want to format your variable name in $\LaTeX$...I think ${\rm BLAH}$ is a much better default name than $x,\ \hat i$, etc....
Answer: If you have $n$ sample points $(x_1,\dots,x_n)$ and want a subsample of $m$ points for which the subsample mean and subsample standard deviation approximate some given numbers $\mu^*$ and $\sigma^*$, one possibility is to think about it as an Integer Programming problem. A (possibly nonunique) solution is a vector $b\in\{0,1\}^n$, with $\sum_{i=1}^n b_i=m$, for which each coordinate indicates if the corresponding sample point is or is not included in the subsample, and $b$ minimizes something like
$$
  \left|\mu^* - \frac{1}{m}\sum_{i=1}^n x_ib_i\right| + \left| \sigma^* - \sqrt{\frac{1}{m-1}\sum_{i=1}^n \left(x_ib_i-\left(\frac{1}{m}\sum_{j=1}^n x_jb_j\right)\right)^2}\right| \, .
$$
I don't know if this is feasible for your data set. There are freely available Integer Programming packages.
Answer: First of all as many pointed out it impossible to exactly match mean and distribution. Apologies for making not clear in the problem. All I wanted was sampled distribution as close as possible to target mean and SD.
Right now I implemented a rejection sampling which is closely linked to the solution suggested by @Stask. (Let's say) I was targeting a normal distribution $Q(x)  = N( \mu, \sigma)$. The empirical distribution of the data $P(x)$ (this can be estimated using kernels or windowing function like Parzen). All need to be done is to draw sample from data with repetition uniform distribution for each sample $y$  if $Q(x)/P(x) > 1$  accept the sample otherwise accept with probability $Q(x)/P(x)$. As more sample will drawn the sample distribution will converge to $Q(x)$.
A layman version of the rejection sampling would be to divide $Q(x)$ in (large number of ) quantiles. For each quantile  equal number of samples from the data which are in same range as within the quantile of $Q(x)$ . As number of quantile increases sampled distribution converges to $P(x)$.
Answer: A simple approach that may work for others with similar problems is to look at a large number of subsets and save the best matches. You'll need to define what "better" means since you have two objectives (mean & std). In this example, I gave equal weight to variations from either target. You probably would want to play with different subsample sizes to find a large N that still has a close enough mean and std. You'll also want to repeat your analysis with different subsamples to make sure your results are robust.
<code># Parameters
target_mean = 1
target_std = .5
subsample_size=15
num_subsamples_to_keep = 5
num_subsamples_to_try = 10000

# This scoring metric is kind of arbitrary and could be tuned.
# For this one, I'm giving equal penalty to deviations from the target mean and the
# target standard deviation. If fitting the target mean was twice as important as
# fitting the target std, you could use:
#    return(2*abs(mean-target_mean) + abs(std-target_std))
# Lower scores are better than higher scores. If you redefined the scoring function
# to make high scores better, then you would need to do a reverse sort in the for loop below.
calculate_score <- function(mean, target_mean, std, target_std) {
    return(abs(mean-target_mean) + abs(std-target_std))
}

# Make up some data. This will have a different distribution than what we are looking for.
df = data.frame(x=rnorm(100), y=rnorm(100))

# The matrix saved_subsamples will stores the best subsamples, but it will start off blank.
# A corresponding dataframe below will store the scores (subsample_metrics).
# We'll keep saved_subsamples and subsample_metrics synchronized so that row 1 in one
# always corresponds to row 1 of the other.
saved_subsamples = matrix(nrow=num_subsamples_to_keep, ncol=subsample_size)

# Store the metrics of a subsample's quality in this data frame.
# We'll keep the rows of this synchronized with saved_subsamples and
# keep them both sorted so the worst saved subsample is always in the last row
# When we find a new subsample that's better than the worst known, we'll save
# it and resort the matrix and dataframe.
subsample_metrics = data.frame(mean=matrix(NaN, nrow=num_subsamples_to_keep), std=matrix(NaN, nrow=num_subsamples_to_keep), score=matrix(NaN, nrow=num_subsamples_to_keep))

# Try a bunch of different subsamples and keep the best ones
for (attempt in 1:num_subsamples_to_try) {
    # Pick a new subsample and evaluate it.
    subsample = sample(nrow(df),size=subsample_size)
    subsample_mean = mean(df[subsample,'x'])
    subsample_std = sd(df[subsample,'x'])
    subsample_score = calculate_score(subsample_mean, target_mean, subsample_std, target_std)
    # If we don't have any subsamples yet (worst score is NA), or if this new
    # subsample is better than our worst saved subsample, then overwrite our
    # worst subsample from the end and re-order the lists.
    if( is.na(subsample_metrics[nrow(subsample_metrics),'score']) ||
            subsample_score < subsample_metrics[nrow(subsample_metrics),'score'] ) {
        # Overwrite the worst saved subsample (row 1)
        subsample_metrics[nrow(subsample_metrics),'mean'] = subsample_mean
        subsample_metrics[nrow(subsample_metrics),'std'] = subsample_std
        subsample_metrics[nrow(subsample_metrics),'score'] = subsample_score
        # Transpose the subsample so it fits in one row instead of one column
        saved_subsamples[nrow(saved_subsamples),] = t(subsample)
        # Reorder the saved subsamples (and corresponding metrics) so the worst
        # scores (the largest) are at the bottom of the list.
        new_order = order(subsample_metrics$score)
        saved_subsamples = saved_subsamples[new_order,]
        subsample_metrics = subsample_metrics[new_order,]
    }
}

# Look at the top subsamples found & their scores
print(subsample_metrics)
print(saved_subsamples)

# Retrieve the top-scoring subsample from the end of the list
top_subsample_indexes = saved_subsamples[1,]
# Use that to subsample the original dataset
top_subsample = df[top_subsample_indexes,]
</code>


Validate each read byte array buffer while reading a file

Question: I'm trying to read a file using the known 'read' method by the FileInputStream class into a certain byte[] buffer with a specific size (e.g 1024). Right after filling that buffer I'd like to validate it's characters (lets say one by one) but I don't want to convert it to a String (or use regex) since I might lose data.
Could anyone advice me what's the best way doing that specific validation?
Note: I know I can use Character.isLetter and such methods but I'm not sure how to iterate that buffer.
Comment: what _exactly_ do you mean by "validate it's characters"?
Comment: just do it without conversion to a String. you have acces to the bytes...
Comment: the validation can be checking if each character is an alphabetic character
Answer: I think this should cover what you want to do:
byte[] arr = new byte[1024];
int len = System.in.read(arr);
while (len != -1)
{
  for (int i = 0; i < len; i++)
    System.out.println((char)arr[i] + " - " + Character.isLetter((char)arr[i]));
  len = System.in.read(arr);
}


Insert deleted records into history table before DELETE using TRIGGER

Question: I have a gridview that displays a recordset from a table - Master2.  I want to use gridview to delete records from this table.  Before the delete occurs, I want to insert the record into a history table with a datetimestamp and userid from the person doing the delete.  Is this possible or should I simply build out the fields with a series of drop down boxes and a single button?
Comment: Have you considered doing this fully on the database side? Like a Delete Trigger?
Answer:
Use a FOR DELETE trigger:

CREATE TRIGGER TriggerName
ON TableName
FOR DELETE
AS
BEGIN
    INSERT INTO HistoryTable(Col1, Col2, Col3)
    SELECT Col1, GETDATE(), Col3
    FROM TableName
    WHERE DeletedRecordID IN (SELECT DeletedRecordID FROM TableName)
END

Comment: This is excellent.  Is there a way to use the parameters that were selected in the delete statement on my form?  Also, I have a separate parameter that is a reason code that I would like to insert into the new table.  Is this possible?  How do I define the parameters?
Comment: can you post the query of your delete statement for a better understanding.
Comment: `DELETE FROM [MasterData2] WHERE [Ad] = @original_Ad AND [Phase] = @original_Phase AND [Page] = @original_Page AND [Page Type] = @original_Page_Type AND [Percent] = @original_Percent AND [Change Type] = @original_Change_Type AND (([UserName] = @original_UserName) OR ([UserName] IS NULL AND @original_UserName IS NULL)) AND (([Timestamp] = @original_Timestamp) OR ([Timestamp] IS NULL AND @original_Timestamp IS NULL))`  Also, I have 3 parameters that come from other areas.  A value from a drop down list, the current time and date and the username.  These are form parameters.
Answer: Use a trigger.
It is safer, meaning that every time you delete a record from that history table (regardless of mechanism) it would still fire.
It is also easier to code as you don't have to put anything inside your .net code to handle it.
Finally, it is faster as there is zero network traffic involved.
Answer: I recomend using a flag for deletion, and not actually delete the record...
to the gridview, you add an extra checkpoint that when selected it will trigger...like this
<asp:TemplateField HeaderText="Delete" SortExpression="ToBeDeleted">
                            <EditItemTemplate>
                                <asp:TextBox ID="txtToBeDeleted" runat="server" Text='<%# Bind("ToBeDeleted") %>'></asp:TextBox>
                            </EditItemTemplate>
                            <ItemTemplate>
                                <%--<asp:Label ID="lblToBeDeleted" Width="20px" runat="server" Text='<%# Bind("ToBeDeleted") %>'></asp:Label>--%>
                                <asp:CheckBox ID="chkToBeDeleted" Width="20px" runat="server" Checked='<%# Bind("ToBeDeleted") %>' OnCheckedChanged="chkToBeDeleted_CheckedChanged" AutoPostBack="true"/>
                            </ItemTemplate>
                            <ItemStyle CssClass="overflowClass" HorizontalAlign="Center" Wrap="false" />
                        </asp:TemplateField>

then in the code behind you handle the trigger:
protected void chkToBeDeleted_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox cb = (CheckBox)sender;
            GridViewRow gvr = (GridViewRow)cb.NamingContainer;
            int id = (int)gvWines.DataKeys[gvr.RowIndex].Value;

            ListOfWine record = (from l in db.ListOfWines
                         where l.Id == id
                         select l).FirstOrDefault();

            //here you add the record to another table and then continue flagging the record for deletion

         record.ToBeDeleted = cb.Checked;
db.SaveChanges();
            gvWines.DataBind();
        }


ASP.NET Core handling JSON deserialization problems

Question: I would like to change default behavior of invalid JSON request handling in ASP.NET Core. I have this model:
public class Model
{
    public Guid Id { get; set; }
}

And when I send this request with this body
{
 "Id": null
}

It returns this error message:
 "Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."

Of course this is absolutely logical but I want Id to be set to default value (Guid.Empty) instead of failing request. I have added this json config in Startup:
services.AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.Error = (a, e) =>
            {
                e.ErrorContext.Handled = true;
            })

Error handler is being hit however ASP.NET Core still returns failure. This in different behavior compared to ASP.NET Web API where this was possible.
Comment: The message is very clear: ```"Error converting value {null} to type 'System.Guid'. Path 'Id', line 2, position 11."```. Shouldn't your model be a nullable Guid such as ```Guid?``` instead?
Comment: Problem is in JsonInputFormatter class in ASP.NET Core which has also its own error handler for this. Under the hood it use Newtonsoft JSON.NET for parsing and this handling with e.ErrorContext.Handled = true; works when it is not in ASP.NET core app
Comment: You can make a custom convert in the `AddJsonOptions`. Then each time that you see a `null` value you set `Guid.Empty`.
Comment: Yes absolutely but what I am doing is update of old ASP.NET Web API app to ASP.NET Core. I would like to avoid such changes as it may have other consequences. Exactly this case (null -> Guid.Empty) works in Web API.
Comment: If you try to load the same json, with a console application for example, targeting different frameworks such as .NET 4.8.x and .NET Core 2.x what happens? are you sure the issue happens on the parsing by the asp.net core engine or by the json engine?
Answer: As you have found, this behavior is handled by JsonInputFormatter, you could custom the formatter to override this behavior like

IgnoreGuidErrorJsonInputFormatter
public class IgnoreGuidErrorJsonInputFormatter : JsonInputFormatter
{
    public IgnoreGuidErrorJsonInputFormatter(ILogger logger, JsonSerializerSettings serializerSettings, ArrayPool<char> charPool, ObjectPoolProvider objectPoolProvider, MvcOptions options, MvcJsonOptions jsonOptions) : base(logger, serializerSettings, charPool, objectPoolProvider, options, jsonOptions)
    {
        serializerSettings.Error = (a, e) =>
        {
            var errors = e.ErrorContext.Error;
            e.ErrorContext.Handled = true;
        };
    }
}

Register IgnoreGuidErrorJsonInputFormatter
services.AddMvc(options =>
{
    var serviceProvider = services.BuildServiceProvider();
    var customJsonInputFormatter = new IgnoreGuidErrorJsonInputFormatter(
                serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<IgnoreGuidErrorJsonInputFormatter>(),
                serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value.SerializerSettings,
                serviceProvider.GetRequiredService<ArrayPool<char>>(),
                serviceProvider.GetRequiredService<ObjectPoolProvider>(),
                options,
                serviceProvider.GetRequiredService<IOptions<MvcJsonOptions>>().Value
        );
    options.InputFormatters.Insert(0, customJsonInputFormatter);
});

Comment: You can implement a custom `IPostConfigureOptions` which registers your input formatter, to avoid building a service provider. FYI.
Comment: I have already fixed my problem with custom JsonConverter but this looks also as a solution, thanks!


Derivative of matrix determinant wrt to matrix element

Question: I want to take the derivative of the function:
$$
f(A) = 2  + \text{log}(|\text{det}(A)|)
$$
with respect to the matrix element $A_{ij}$, where A is orthogonal, so far:
\begin{align*}
\frac{\partial}{\partial A_{ij}}f(A) &= \frac{\partial}{\partial A_{ij}} \text{log}(|\text{det}(A)|)\\
& = \frac{\frac{\partial}{\partial A_{ij}}|\text{det(A)}|}{|\text{det(A)}|} \\
&=\frac{\partial}{\partial A_{ij}}|\text{det(A)}|
\end{align*}
I'm not really sure how to proceed, my first instinct was to note that $det(A) = I$ for an orthogonal matrix, but i guess here I am trying to find how the determinant changes wrt a matrix element.
Answer: You can use Jacobi's identity
\begin{eqnarray}
\frac{\partial}{\partial A_{ij}}f(A) &=& \frac{\partial }{\partial A_{ij}} \left( 2 + \log |\det(A)|\right) \\
&=& \frac{1}{|\det(A)|}\frac{\partial}{\partial A_{ij}}\det (A) = C_{ij}(A)
\end{eqnarray}
where $C(A)$ is the cofactor matrix of A


asymptotical behavior of integral

Question: I'm interest in the asymptotical of $$\int_{-\pi}^{\pi}\exp\Big((\cos z+i\alpha\sin z-1)t\Big)dz\hspace{3mm}\text{as}\hspace{2mm}t\to\infty$$ for $-1<\alpha<1$. Numberical result suggest that for $\alpha =0$ the integral behave like $\frac{c}{\sqrt{t}}$ and for $\alpha\neq 0$ it behave like $\exp(ct)$ for some $c<0$. I don't think Laplace method work for this problem. Thank you to suggest other method.
Comment: For $\alpha=0$ Laplace's method works well giving $I\sim\sqrt\frac{2\pi}{t}$. But for $\alpha\neq 0$...
Answer: When $\alpha \neq 0$ you'll need to deform the contour over the new saddle point located at $z = i\operatorname{arctanh} \alpha$.  At this saddle point we have
$$
\cos z + i\alpha \sin z = \sqrt{1-\alpha^2} - \frac{1}{2}\sqrt{1-\alpha^2} (z-i\operatorname{arctanh} \alpha)^2 + O(z-i\operatorname{arctanh} \alpha)^3,
$$
so the Laplace method yields
$$
\begin{align}
\int_{-\pi}^{\pi} \exp\Bigl[(\cos z + i \alpha \sin z)t\Bigr]\,dz &\sim \exp\left(t\sqrt{1-\alpha^2}\right) \int_{-\infty}^{\infty} \exp\left[-\frac{tz^2}{2}\sqrt{1-\alpha^2}\right]\,dz \\
&= \left(1-\alpha^2\right)^{-1/4} \sqrt{\frac{2\pi}{t}} \exp\left(t\sqrt{1-\alpha^2}\right).
\end{align}
$$
Thus
$$
\int_{-\pi}^{\pi} \exp\Bigl[(\cos z + i \alpha \sin z - 1)t\Bigr]\,dz \sim \left(1-\alpha^2\right)^{-1/4} \sqrt{\frac{2\pi}{t}} \exp\left[\left(\sqrt{1-\alpha^2}-1\right)t\right].
$$

asymptotical behavior of integral


How do you write this differently? $(A\not\subseteq B) \wedge (B \not\subseteq A) \wedge ((B \cap A) \neq \emptyset)$

Question: I like to write this different, maybe there is a better and shorter way of doing it..? So we have $(A\not\subseteq B) \wedge (B \not\subseteq A) \wedge ((B \cap A) \neq \emptyset)$
which should mean that: No element of $A$ is an element of $B$ and no element of $B$ is an element of $A$ and the intersection of $A,B$ is not empty.
Then this would mean the same as above, right?
$$(A \neq B) \wedge ((A \cap B) \neq \emptyset)$$
Maybe a more elegant/shorter way of doing this differently?
Comment: No, the symbol $A\not\subseteq B$ means that $A$ is not contained in $B$, so *some element of $A$ is not an element of $B$*.
Comment: Usually, having an example in mind helps. Try to think of the Venn diagram for the original statement. A more concrete example of the original statement is $A=\left\{1,2\right\}$, $B=\left\{2,3\right\}$.
Comment: > No element of A is an element of B and no element of B is an element of A and the intersection of A,B is not empty.

This is entirely incorrect. $A \not\subseteq B$ does not mean "no member of $A$ is a member of $B$. It means "not every member of $A$ is a member of $B$.

Also, neither $(A \not\subseteq B)\wedge(B\not\subseteq A)$ nor "no element of $A$ is an element of $B$ and no element of $B$ is an element of $A$" is equivalent to $A \neq B$.
Answer: The first line translates to: There exists elements that are in $A$ but not in $B$ and there exists elements that are in $B$ but not in $A$ and there exists elements that are both in $A$ and $B$.
Both your expression by words and your second mathematical statement do NOT express that.
There are many ways to write your initial statement down, one could use the complement operator or the differences operator for sets.
Answer: You've written three different things. The statement in the title says that $A, B$ are overlapping, but neither contains the other. The statement in English in your text is always false: if no element of $A$ is an element of $B$ then their intersection cannot be non-empty, because an element in the intersection is in both $A$ and $B$. The formula in your text states that $A, B$ are distinct but overlapping sets, but allows for the possibility that one is a subset of the other.
I do not think there is a meaningfully shorter way to write what you have written in your title. (Furthermore, just in case this was your reason: shorter is often not better, simpler is better, and the statement in your title is quite easy to read.)


Word embedding, data formatting unsure of how to bring together

Question: I am trying to go through a tutorial and re-apply it to another problem for practice. the original tutorial is here, https://www.tensorflow.org/tutorials/text/word_embeddings .
I am using this dataset instead though and optimizing for profitable at the end,
id - product - url - html_snippet - html_blob - profitable
1 - toygun - "https://toyguns.com" - "a place for toy guns" - "<!DOCTYPE html><ht.." - 1
1 - umbrella - "https://umbrellas.com" - "a place for umbrellas" - "<!DOCTYPE ...." - 0

Example of getting data is like this,
url = 'https://moodmap.app'
res = requests.get(url)
soup = BeautifulSoup(res.content, "lxml")
s = soup.select('html')[0].text.strip('jQuery1720724027235122559_1542743885014(').strip(')')
s = s.replace('null','"placeholder"')

print(soup)

Now when i try and put this data into this format, it is coming up with a few errors and I'm confused if it's possible to put it in the same format as in this example?
...
batch_size = 1024
seed = 123
train_ds = tf.keras.preprocessing.text_dataset_from_directory(
    'aclImdb/train', batch_size=batch_size, validation_split=0.2,
    subset='training', seed=seed)
val_ds = tf.keras.preprocessing.text_dataset_from_directory(
    'aclImdb/train', batch_size=batch_size, validation_split=0.2,
    subset='validation', seed=seed)
..

With this from directory section, can i parse in a dataframe with these values above?
AUTOTUNE = tf.data.experimental.AUTOTUNE

train_ds = train_ds.cache().prefetch(buffer_size=AUTOTUNE)
val_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)

With this section, the 1000 word vocbulary, is this right for the content i'm putting in?
# Embed a 1,000 word vocabulary into 5 dimensions.
embedding_layer = tf.keras.layers.Embedding(1000, 5)

result = embedding_layer(tf.constant([1,2,3]))
result.numpy()

result = embedding_layer(tf.constant([[0,1,2],[3,4,5]]))
result.shape

# Create a custom standardization function to strip HTML break tags '
'.
def custom_standardization(input_data):
  lowercase = tf.strings.lower(input_data)
  stripped_html = tf.strings.regex_replace(lowercase, '
', ' ')
  return tf.strings.regex_replace(stripped_html,
                                  '[%s]' % re.escape(string.punctuation), '')

# Vocabulary size and number of words in a sequence.
vocab_size = 10000
sequence_length = 100

# Use the text vectorization layer to normalize, split, and map strings to
# integers. Note that the layer uses the custom standardization defined above.
# Set maximum_sequence length as all samples are not of the same length.
vectorize_layer = TextVectorization(
    standardize=custom_standardization,
    max_tokens=vocab_size,
    output_mode='int',
    output_sequence_length=sequence_length)

I think the rest should work.
Would love some help here - perhaps I am approaching this incredibly incorrectly, but seems like a similar workflow?
Thanks!
Comment: What is the error? Do you have data from your own custom dataset in the folders mentioned in the the `text_dataset_from_directory` method ?
Answer: So I am not entirely sure what you are trying to achieve, but assuming you have some sort of text data you want to feed into a neural network with an embedding layer for classification purposes, I would approach it like this:
First, as you are experimenting, I would work with the raw data instead of using tf.keras.preprocessing.text_dataset_from_directory, just to avoid any confusion about the nature and structure of your data. It would also allow you to not have a static Train Test split, which in my experience is needed for more stable solutions.
This means that I would load your entire dataset, preprocess it, and then split it up into Test, Training, and Validation datasets. I prefer doing this in the explorative phase, as I believe it makes understanding your data easier. Also i will be using some packages that I recommend you learn to use if you do not already use them (pandas, numpy, sklearn) So something like this (assuming your data is in a CSV file):
# ----- Import needed packages -----
import pandas as pd
import numpy as np
import tensorflow as tf

from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report
from collections import Counter

from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences

# ----- Load data -----
file_path = "/PATH/TO/DATA/data.csv"
df = pd.read_pickle(file_path)

# ----- Get labels -----
y = np.int32(df.NAME_OF_LABEL_COLUMN.astype('category').cat.codes.to_numpy())

# ----- Get number of classes -----
num_classes = np.unique(y).shape[0]

# ----- Remove HTML tags from your text -----
def custom_standardization(text):
    #rewrite your function to apply on each text in your data
    pass

df['Cleaned_Text'] = df.NAME_OF_TEXT_COLUMN.apply(custom_standardization)

# ----- Prepare text for embedding -----
# Define these values so they fit your project
max_features = 10000
output_dim = 16

# ----- Get top 10000 most occuring words in list-----
results = Counter()
df['Cleaned_Text'].str.split().apply(results.update)
vocabulary = [key[0] for key in results.most_common(max_features)]

# ----- Create tokenizer based on your top 10000 words -----
tokenizer = Tokenizer(num_words=max_features)
tokenizer.fit_on_texts(vocabulary)

# ----- Convert words to ints and pad -----
X = tokenizer.texts_to_sequences(df['Cleaned_Text'].values)
X = pad_sequences(X)

max_input_lenght = X.shape[1]

# ----- Split into Train, Test, Validation sets -----
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, random_state=42)

Then once preprocessing is done, we can construct and train the model

# ----- Define model -----
model = tf.keras.Sequential()
model.add(tf.keras.layers.Embedding(input_dim=max_features, output_dim=output_dim, input_length=max_input_lenght))
model.add(tf.keras.layers.GlobalAveragePooling1D())
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(num_classes, activation='softmax'))

# ----- Compile model -----
model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(), optimizer=tf.keras.optimizers.Adam(1e-4), metrics=["accuracy"])

# ----- Train model -----
history = model.fit(X_train, y_train, batch_size=8,epochs=20, validation_data=(X_val, y_val))

# ----- Evaluate model -----
probabilities = model.predict(X_test)
pred = np.argmax(probabilities, axis=1)

print(" ")
print("Results")

accuracy = accuracy_score(y_test, pred)

print('Accuracy: {:.4f}'.format(accuracy))
print(" ")
print(classification_report(y_test, pred))

This code could be improved on, but I think it will be easier for you to test whatever you are trying to test, as it provides more transparency in each step. And you will of course need to modify it to suit your specific case.
If you are keen on using the Tensorflow example you based your work on, I would suggest that you take a look at the data format in your own case and in the tutorial case, as that is likely where the issue is.
Comment: If the size of the dataset is very large, is there a way to carry this process out in batches without the use of **tf.keras.preprocessing.text_dataset_from_directory**? And feed it into the model in batches?


Solving the following differential equation

Question: I have never done a differential equation like this so please bear with me as I try to explain how I approached it.
I have $\theta(t)$ which defines the trajectory of a particle in a field.
The equation I have obtained is:
$\dot{\theta(t)}^2 = k(-cos\theta)$ where $k$ is some constant. The negative sign in front of $cos(\theta)$ is not a problem since the physical limit I obtain strictly restricts $cos(\theta)$ to have negative values such that  $\dot{\theta(t)}^2$ is positive (or zero). The question asks me to find $\theta(t)$ and keep it in an indefinite integral form, and I do not even know how to begin this problem.
The attempt that I made is:
$\dot{\theta} = \sqrt{k}\sqrt{-cos(\theta)}$ which is a differential equation. so I get $\frac{d\theta}{\sqrt{-cos(\theta)}} = \sqrt{k} dt$.
However, it does not seem like I am on the right track, cause I do not know what comes next. Putting this in mathematica gives me an elliptic function.
Any help would be appreciated.
Comment: You can make a replacement $$t=tan(\frac{\theta }{2}) $$
Comment: $$ cos(\theta)=\frac{1-t^2}{1+t^2}$$
Answer: The next step is to integrate both sides over the path. If you have an initial condition of $\theta(t_0) = \theta_0$, then you integrate both sides from that point to $\{t,\theta(t)\}$:
$$
\int_{\theta_0}^{\theta(t)} \frac{d\theta'}{\sqrt{-\cos\theta'}} = \int_{t_0}^t\sqrt{k} \,dt' = \sqrt{k}(t-t_0).
$$
Now, this isn't going to simplify without using special functions, and since the problem calls for a solution in terms of an indefinite integral, I think it wants us to stop here. Thus, we have an equation for the path $\theta(t)$ in implicit form:
$$
\int_{\theta_0}^{\theta(t)} \frac{d\theta'}{\sqrt{-\cos\theta'}} =\sqrt{k}(t-t_0).
$$


how to write Get() pointcut to retrive the attributes that have been used in the program in AspectJ

Question: I have written the following pointcut but it is giving the run time error (Exception in thread "main" java.lang.StackOverflowError)
pointcut traceAttribs():(get(* *));
Comment: Without some more information on how that pointcut is used, what your code looks like etc., you won't get any answers. A StackOverflowError isn't very likely to come from a pointcut like that, so your problem might be something else.
Answer: What I understand from your question is that you need to create an aspect that knows your methods argument in real time.
There is a useful simple examples in Mkyong's page and probably your need is on point 8.
If you want to get a method name and arguments in your aspect you could write something like this:
<code>@Aspect
public class LoggingAspect {

   @Around("execution(* com.your.package.YourClass.yourMethodAround(..))")
   public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {

    System.out.println("Your method: " + joinPoint.getSignature().getName());
    System.out.println("and method arguments: " + Arrays.toString(joinPoint.getArgs()));

    System.out.println("Your method will be executed. ");
    joinPoint.proceed(); //continue on the intercepted method
    System.out.println("Ended execution");

   }
}
</code>
Hope to help


Prove (or disprove) that $\log_2 n^n=O(\log_2 n!)$ and $\log_2 n!=O(\log_2 n^n)$.

Question: I have to prove (or disprove) that $\log_2 n^n=O(\log_2 n!)$ and $\log_2 n!=O(\log_2 n^n)$.
I've tried to solve this by calculating $$\lim_{n \to \infty} \left\lvert \frac{\log_2 n^n}{\log_2 n!} \right\rvert$$ and $$\lim_{n \to \infty} \left\lvert \frac{\log_2 n!}{\log_2 n^n} \right\rvert$$ but I've had difficulty finding these limits.
Comment: Welcome to MSE! Have you tried [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation)?
Answer: I think one part of the question has been answered already (i.e. $\log_2 n^n \geq \log_2 (n!)$).
For the second part (i.e. to show that $\log_2 n^n = O(\log_2 n!)$), note that $n! \geq n\cdot (n-1)\cdots (n/2) \geq (n/2)^{n/2}.$ I think you should be able to finish it from here.
Answer:
$n! =1...n \leqslant n.n....n = n^n$ so $log_2 n^n\leqslant (\log_2 n!)$, which gives : $$\log_2 n!=O(\log_2 n^n)$$
As @stupidqnasker remarked, $n!\geqslant n.(n-1)...(n/2)\geqslant (n/2)^{n/2}$ so $\log_2 n! \geqslant n/2 \log_2 n/2 \geqslant n/3 \log_2 n = 1/3 \log_2 n^n$ for $n$ big enough. So we have that $$\log_2 n^n = O(\log_2 n!)$$
Comment: Actually $\log_2 n!  \in \Omega(\log n^n)$ though.
Comment: Sorry for that mistake, I edited
Answer: $$ \begin{split}
\left(\frac1 n \sum_{j1}^n \log_2 k\right ) -\log_2 n &= \frac1 n \sum_{j=1}^n (\log_2 k -\log_2 n)\\
&= \frac1 n \sum_{j=1}^n \log_2 \left (\frac k n \right)\\
&\rightarrow \int_0^1 \log_2 x dx=-\frac 1 {\ln 2}
\end{split}
$$
Thus $$\log_2(n!)=\log_2(n^n)-\frac 1 {\ln 2}n+o(n)\sim \log_2(n^n)$$
which proves the result.


Como saber quais colunas foram modificadas em um UPDATE usando TRIGGER?

Question: Boa tarde pessoal.
Estou criando uma TRIGGER AFTER UPDATE em uma tabela no BD, e preciso saber quais colunas foram alteradas (independente do valor que foi colocado), e colocar os nomes das colunas numa variável que irá ser inserida em uma outra tabela.
O problema é que se trata de uma tabela com muitas colunas, e ficaria muito feio fazer a checagem coluna por coluna dessa forma:
<code>IF (NEW.Column!= OLD.Column) THEN

    SET @ColunasAlteradas = CONCAT(@ColunasAlteradas, ', NomeColunaAlterada');

END IF;
</code>
Tô com a ideia de fazer uma loucura e utilizar STMT e CURSOR na tabela COLUMNS do information_schema, mas se tiver alguma função que faça essa checagem em uma TRIGGER ajudaria demais.
Obrigado desde já!
Comment: O que está querendo fazer? Me parece um log, é isso? Veja se isso não te ajuda...https://pt.stackoverflow.com/questions/143720/criar-trigger-update-mysql
Answer: Creio que terá que fazer as verificações uma a uma, por exemplo:
<code>@IF (OLD.column != NEW.column) SET `outraColuna` = OLD.outraColuna + 1;
</code>
Algo assim


Can I use asynchronous Aalto-XML as JAXB implementation?

Question: Is it possible to use aalto-xml as JAXB implementation?
I tried to pass AsyncXMLStreamReader to JAXB context:
<code>val asyncInputFactory: AsyncXMLInputFactory = InputFactoryImpl()
asyncInputFactory.configureForSpeed()
val asyncStream = asyncInputFactory.createAsyncFor(xml.toByteArray())
return context.createUnmarshaller().unmarshal(asyncStream)
</code>
But it ended with error "reader must be on a START_ELEMENT event, not a 257 event"
Is there any way to use aalto with JAXB and not write low level xml parsing code?
Greetings,
Comment: Mind posting the XML? Maybe there is a problem? Code looks right.
Comment: @Damian, any update on this? Are you able to implement it ?
Answer: Error you are getting is related to async extension:

AsyncXMLStreamReader.EVENT_INCOMPLETE (value 257; just outside range reserved by Stax API) is used to denote "not yet available" (without more data)

See https://github.com/FasterXML/aalto-xml for more info
I am not aware of any JAXB implementation supporting async extension by default.


Problema ao compilar math.h

Question: Boa noite, quando eu tento usar alguma função de math.h e coloco como argumento uma variável e tento compilar eu recebo um erro. Sabe me explicar porque isso está ocorrendo?
Segue um código de exemplo:
#include <stdio.h>
#include <math.h>

int main(){

    int cacheSize = 4;
    int memSize = 16;

    // log de cacheSize na base 2
    double cacheBits = 0;
   cacheBits = log(cacheSize)/log(2);

   // log de memSize na base 2
   double memBits = 0;
   memBits = log(memSize)/log(2);

   return 0;
}

A mensagem de erro que recebo:
gcc teste.c -o teste

/usr/bin/ld: /tmp/ccHF5avR.o: na função "main":
teste.c:(.text+0x25): referência não definida para "log"
/usr/bin/ld: teste.c:(.text+0x51): referência não definida para "log"
collect2: error: ld returned 1 exit status

Answer: Se obtém esse erro é porque a implementação da biblioteca math não está a ser linkada no processo. Para resolver acrescente o -lm na instrução de compilação:
gcc teste.c -o teste -lm

Quando inclui o math.h inclui a definição das funções mas não as suas implementações, e por isso é que vê esse erro.

Problema ao compilar math.h


How to change dropdown title on selected option with reactstrap on react

Question: I am referring to this dropdown documentation https://reactstrap.github.io/?path=/docs/components-dropdown--dropdown
But I can't seem to find any example that will change the dropdown title on the options selected.. can anyone show me how this is done? It has to be under a function instead of class component
This is the default code:
import React, { useState } from 'react';
import {
  Dropdown,
  DropdownToggle,
  DropdownMenu,
  DropdownItem,
} from 'reactstrap';
import PropTypes from 'prop-types';

function Example({ direction, ...args }) {
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const toggle = () => setDropdownOpen((prevState) => !prevState);

  return (

      <Dropdown isOpen={dropdownOpen} toggle={toggle} direction={direction}>
        <DropdownToggle caret>Dropdown</DropdownToggle>
        <DropdownMenu {...args}>
          <DropdownItem header>Header</DropdownItem>
          <DropdownItem>Some Action</DropdownItem>
          <DropdownItem text>Dropdown Item Text</DropdownItem>
          <DropdownItem disabled>Action (disabled)</DropdownItem>
          <DropdownItem divider />
          <DropdownItem>Foo Action</DropdownItem>
          <DropdownItem>Bar Action</DropdownItem>
          <DropdownItem>Quo Action</DropdownItem>
        </DropdownMenu>
      </Dropdown>

  );
}

Example.propTypes = {
  direction: PropTypes.string,
};

export default Example;

Answer: You can create a state to store the last selected item:
const [selectedItem, setSelectedItem] = useState("Dropdown");

Then you add an onClick to every <DropdownItem/> so you can update your selectedItem state once an option is selected:
//...
<DropdownItem onClick={() => {setSelectedItem('Foo Action')}}>Foo Action</DropdownItem>
<DropdownItem onClick={() => {setSelectedItem('Bar Action')}}>Bar Action</DropdownItem>
//...

Finally you can display selectedItem as dropdown title.
<DropdownToggle caret>{selectedItem}</DropdownToggle>


Desativar o Scroll da página em um momento específico

Question: Eu fiz uma espécie de carrossel com CSS e um pouco de JavaScript com algumas imagens e a medida em que eu uso o scroll do mouse em cima da imagens as imagens vão passando para o lado, o problema é que a página também desce a medida que eu uso o scroll para passar as imagens. Sou iniciante na programação e não tenho ideia de como desativar o scroll da página enquanto o mouse estiver encima das imagens.
O código das imagens HTML:

O código CSS:
#galeria{
    width: 100%;
    height: 100%;
}

#itens{
    display: flex;
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth;
    scroll-snap-type: x mandatory;
}

.item{
    flex: none;
    width: 100%;
    height: 250px;
    scroll-snap-align: start;
    pointer-events: none;
}

img{
    width: 100%;
    height: 98%;
    object-fit: cover;
}

O código do JavaScript:
document.querySelector("#itens").addEventListener("wheel", event => {

            if(event.deltaY > 0){
                event.target.scrollBy(300, 0)
            }else{
                event.target.scrollBy(-300, 0)
            }

        });

Answer: Tente o seguinte:
document.querySelectorAll("#itens img").forEach(img => {
  img.addEventListener('mouseenter', ()=> document.body.style.overflow = 'hidden')
  img.addEventListener('mouseleave', ()=> document.body.style.overflow = null)
})

Essa é uma solução simples, mas direta para a sua questão.
Primeiro, se você quer remover o scroll só para as imagens, deve seleciona-las, por isso adicionei o img no querySelectorAll.
"overflow: hidden" é uma das formas mais simples de remover scroll e isso funciona no body.
Para retornar ao normal, basta anular a definição de overflow. (forma simples)
E para isso funcionar legal, os eventos adequados são mouseenter e mouseleave.
Comment: Ok, funcionou, obrigado


What is need of String s = new String("abc") when we can create String s = "abc"

Question: As per my understanding
String s = new String("abc") will create two objects-

one in String constant pool (if "abc" is not already in constant pool)
one in Heap memory

Although more than understandings exist about how many objects will actually be created and where.
Anyway I have following questions -

Why is it not covered in java docs of String class about how many objects will be created and where?
Why new String(String) is provided anyway in String class provided Strings are immutable?.Also can it can be assumed that all strings, created by either String s = "abc" or String s = new String("abc"), will be available in String constant pool?
The String literals used in creating or appended in StringBuilder or StringBuffer,do they also go in String constant pool or they remain in heap memory only.

Edit
java docs for intern() method clearly talks about constant pool but
  nothing is said like that in String(String).
Comment: WRT "the need": It's close to 0. I don't remember using it in the past few years. Maybe for testing that there is no flawed `==` comparison or other odd reasons like wanting a safe lock object that also prints itself. Automatic code analysis may even warn you about it.
Comment: @zapl - historically, the constructor had a real purpose - to make a copy with a smaller char array. see http://stackoverflow.com/q/16123446/2158288
Answer:
Why is it not covered in java docs of String class about how many objects will be created and where?

It is covered  in Docs of String

The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:

 String str = "abc";

is equivalent to:

 char data[] = {'a', 'b', 'c'};
 String str = new String(data);

And from the Java language specification

A String object has a constant (unchanging) value.
String literals (§3.10.5) are references to instances of class String.

And from JSL # 3.10.5. String Literals

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

.

Why new String(String) is provided anyway in String class provided Strings are immutable?.Also can it can be assumed that all strings, created by either String s = "abc" or String s = new String("abc"), will be available in String constant pool?

Since String is object the valid way of declaration is
String s = new String("abc");

But where String s = "abc"; is designed for other reasons
The designers of Java decided to retain primitive types in an object-oriented language, instead of making everything an object, so as to improve the performance of the language.
Since it is the most useful class For performance reason, Java's String is designed to be in between a primitive and a class.

The String literals used in creating or appended in StringBuilder or StringBuffer,do they also go in String constant pool or they remain in heap memory only.

Consider the example
StringBuilder sb = new StringBuilder("abc");

The literal "abc"  available in constant pool and the object sb created in heap.
Give a shot to read my old answer : How can a string be initialized using " "?
Comment: Downvoted. Doesn't really answer the question and is erroneous. Creating a String from a char array is not really equivalent to using a constant. Example: ```String a = "x"; String b = "x"; char[] ca = {'x'}; String c = new String(ca);``` Variables a and b now point to the same object, but c points to a different object. Also, Java Strings are objects. They are not "between" primitive types and reference types. Yes, you can use the + operator, but that's just syntactic sugar and has nothing to do with "performance reasons". The stuff about "valid way of declaration" doesn't make sense.
Comment: @JonaChristopherSahnwaldt That is fine.
Comment: Will try to answer your questions: 1) I never said that it's equal to char array. So from your point of, the official API docs linked or wrong ? 2) Java strings are Object's. No doubt about it. Just it's look a like a primitive type of declaration and for the constant pool (performance optimisation by language). 3)`but that's just syntactic sugar and has nothing to do with "performance reasons"`. I never mentioned that in my answer. 4) Valid way id about the object declaration like any other object unlike literal style. Hope that clears.
Comment: 1) Yes, strictly speaking, the official API doc is wrong. The example in the doc is meant to illustrate immutability, and in that respect, the strings are equivalent, but in other ways, they aren't. 2) I don't understand. 3) I assumed you felt that strings are like primitives because they can be operands. Sorry. 4) I don't understand.
Answer:
String s = new String("abc") will create two objects:

one in String constant pool (if "abc" is not already in constant pool)

No. It is in the constant pool. It was put there by the compiler.

one in Heap memory

Correct.

Although more than understandings exist about how many objects will actually be created and where.

Many misunderstandings: only one correct understanding.

Why is it not covered in java docs of String class about how many objects will be created and where?

The premiss of the question is not correct. It is covered. Not possibly in the exact form 'how many strings are created', but as the question has been asked millions of time in the last 20 years the answer isn't exactly a secret. Or shouldn't be.

Why new String(String) is provided anyway in String class provided Strings are immutable?.

So you can create a new one.

Also can it can be assumed that all strings, created by either String s = "abc" or String s = new String("abc"), will be available in String constant pool?

No. Only string literals and the result of String.intern() are in the constant pool. And that is documented as well.

The String literals used in creating or appended in StringBuilder or StringBuffer,do they also go in String constant pool or they remain in heap memory only.

All String literals are placed in the constant pool by the compiler.
Comment: @sarvesh It is put into the constant pool of the .class file by the compiler, and the string literals in the constant pools of all the .class files are consolidated into the runtime string pool by the classloader.
Comment: To your first point, `No. It is in the constant pool. It was put there by the compiler.` How could compiler? As per java docs of `intern()` method `A pool of strings, initially empty, is maintained privately by the class String.`  Clearly Object creation is a process of run time and in actual JVM instance. And to your 5th point `So you can create a new one.` Why would I create a new string if I already have that immutable String?
Comment: This looks convincing. Thanks.


How are standard exogeneity assumptions and indepent of potential outcomes concepts linked?

Question: If we had a model:
$y=x\beta +\eta$
and assumed exogeneity, so $E[\eta|x]$=0, is the fact that x or treatment intensity is now uncorrelated with $\eta$ equivalent to saying that x is 'independent of potential outcomes?'
Answer: Yes, if we call the model
$$Y = X\beta + \eta$$
"structural" or "causal", we can use it to define potential outcomes as
$$Y(x) = x\beta + \eta.$$
(I'm using upper-case letters $Y$ and $X$ for random variables, and lower-case $x$ for a realization or fixed constant).
Then assuming $E[\eta|X] = 0$, it follows that
$$E[Y(x)|X] = x\beta + E[\eta|X] = x\beta,$$
which does not depend on $X$, so mean ignorability $E[Y(x)|X] = E[Y(x)]$ holds.
This "structural definition of counterfactuals" was proposed by Judea Pearl, see for example his book "Causality", or his book with Jewell and Glymour, "Causality: A Primer".
Comment: Thanks!  just one quick follow up, when people use the terminology 'structural' , that is synonymous with saying it just some true theoretical population relationship, correct?
Comment: Not quite, the conditional mean function E[Y|X] is also a population concept, but not necessarily structural. One definition of a structural model is that the model describes how $Y$ changes when $X$ is controlled physically. This entails that the value of the structural $\beta$ is "invariant" to changes in the distribution of $X$, while a regression coefficient would not be (if the regression coefficient is equal to $cov(X, Y)/var(X)$, this will change when the distribution of $X$ changes). More generally, "structural" is almost synonymous with "theoretical" (especially in economics).
Comment: @Steve Infact the exogeneity condition must be related to the structural equation and not to the regression one. If population or only a sample are available do not matters. Frequently this point is misunderstood. Read here can help: https://stats.stackexchange.com/questions/262609/what-is-the-actual-definition-of-endogeneity/402015#402015
Comment: @JulianSchuessler Hello, according to your derivation, E(Y(x)|X) = E(Y(x)) = Y(x). Is this right? And how does this have any relationship with ignorability, which I understand is that Y(x) is independent of X given some confounders (eta)?
Comment: Yes, E[Y(x)|X] = E[Y(x)] as shown, but $E(Y(x)) = x\beta$ whereas $Y(x) = x\beta + \eta$, so these are not the same. Ignorability mathematically is Y(x) \indep X, which implies $E(Y(x)|X] = E[Y(x)]$.


Probability Calibration, what causes simple linear models like logistic regression to be over-confident and diverge from the true class probabilities?

Question: I've recently studied probability calibration and have investigated many examples and revisited old models of mine to find that they are all poorly calibrated. The idea of stacking also has been cast in a new light.
However intuitive the "calibration" process is, I find it hard to understand why even very simple models become so over-confident.
I'd be super grateful if you can share some insights into how this happens, as I would have guessed that many simpler (especially linear) models would reflect the true class probabilities.
Many thanks in advance!
Comment: Logistic regression models generally are fairly well-calibrated (on their training set, hence @sjw's answer); can you provide some specific examples? //  [You're not resampling](https://stats.stackexchange.com/q/428666/232706), are you?
Comment: You describe a very general case and there might be a lot of causes. We do not know which one would answer your question. Could you add some more focus by giving an example of what situation you mean whera a model is being overconfident.
Comment: @BenReiniger I did see them being generally better calibrated than other models such as decision trees, I just for some reason expected them to be near perfect, but redundancy as in sjw's answer make a lot of sense. I did resample decision trees and I did expect those to be biased since I a actively changing the distribution
Answer: Suppose there are for example many noise covariates and a very small sample. The linear model will by chance estimate nonzero coefficients on some of these (overfit).  This can lead to higher confidence in the class probabilities.
If for example you have 2 variables and both are noise, if the model correctly estimates (doesn't overfit) by chance, you will get zero coefficients on both, and your estimated prob will be 0.5 each.  Suppose you accidentally estimate a nonzero coefficient due to a spurious correlation between the response and a covariate (overfit); the estimated prob will then be greater or less than 0.5 (more confident).
This is a question of bias variance tradeoff, I expect, which varies by sample size, signal, etc. In other words, a linear model might be a complex model for a dataset without much signal; model complexity is relative, not absolute - a fact that is often overlooked in the applied literature.
Comment: Yes edited a bit
Comment: Thanks a lot, I think this makes a lot of sense.
So for example, if I had a training set with 10 features but a lot of redundancy in these then the model would use the other features to overfit and this somehow leads to higher expected probabilities than that are actually there?
Comment: Thanks a million, this is an intuitive answer!


Expectation of a special gamblers ruin

Question: I am not sure if this is a special case of the gamblers ruin or just a Markov chain problem. A game where we start with M0 amount of money.
With probability 1/2 we win M0/2 and probability 1/2 we lose M0/2. We do this n times, so after the nth time, we gain or lose (Mn−1)/2.
Our total money after n times is, therefore, Mn = Mn−1 ± (Mn−1)/2, with each occurring with probability 1/2.
My first problem is finding the expectation of Mn.
This is what I tried
E(Mn)= 1/2 (Mn−1 + (Mn−1)/2)+ 1/2 (Mn−1 - (Mn−1)/2) = Mn-1
This doesn't make sense since Mn-1 also depends on Mn-2 and so on.
I stimulated the problem on Matlab

For any initial values of M0 and n I used, I noticed that It always converges to zero as n gets large.
So I guess E(Mn) goes 0? What's the general expression for E(Mn)
(My plotted graph is just one realization)
Secondly, we will define Xn = log(Mn/M0), approximate P(Xn > s) fixed s, and large n.
We then approx  P(M100 > M0/8).
I tried using the central limit theorem for this but I'm stuck. Anything will help, thanks
Answer: The expected value of money at nth step is equal to n-1th step and hence equal to n-2th step and so on .. equal to M0
Your calculation seems to be correct.
Regarding the expression you mentioned last yes you can use law of large no for finding the probability , at every step the value gets multiplied with 1/2 or with 3/2 with half probability each so at nth step the value is $$M0 * (\frac{1}{2})^{n-r} * (\frac{3}{2})^{r}$$ apply the inequality and apply log on both sides to convert the above multiplication expression into summation expression,  the analogy is that a random variable takes values log(3/2) and log(1/2) with half probability each and we are picking n iid random variables whose sum must be greater than or equal to log(1/8)
Comment: Regarding your matlab simulation since the expected no if times 3/2 and 1/2 gets multiplied are both n/2 the net multiplied expression becomes 3/4 s exponent raised to n/2 and hence the value tends to 0

Expectation of a special gamblers ruin


Django: Could not parse the remainder: '"{%' from '"{%'

Question: I'm using Django and I'm getting an "Error during template rendering": "Could not parse the remainder: '"{%' from '"{%' ".
Here is the line of code causing the problem:
{% with memberName="Java" memberPhoto="{% static 'sbs/images/avatar.jpg' %}" memberYear=80 memberBio="Lorem ipsum dalas dolores blabla" %} {% include "sbs/_member.html" %} {% endwith %}

It is happening because of the image, but how could i put the image as a variable here without getting this error?
Thanks in advance!
Answer: You cannot nest {% ... %}s. Use the as clause of the static tag to store the static URL into a variable first:
{% static 'sbs/images/avatar.jpg' as avatar %}
{% with memberName="Java" memberPhoto=avatar memberYear=80 memberBio="Lorem ipsum dalas dolores blabla" %}
{% include "sbs/_member.html" %}
{% endwith %}


Meaning of 1/1 and 1/2 beneath pedaling marking

Question: Today I saw 1/1 and 1/2 written in one of my pieces beneath the pedal markings.

Do these have a meaning or is it a misprint?
Comment: @EpicGuy The much more relevant statement would have been "they aren't time signatures as they're written *in small print directly below a pedal marking*".
Comment: @KyleStrand Ah yes I didn't really clarify where they were. And the piece is called "Death by Pasta" by Sonny Chua.
Answer: It is a little hard to tell without seeing the music, but these are unlikely to be time-signatures and marcato markings. The "^" is probably a variable pedal mark, particularly if it is connected to the lines showing the pedal markings. This page shows how this is usually used, it

More accurately indicates the precise use of the sustain pedal. The
  extended lower line tells the player to keep the sustain pedal
  depressed for all notes below which it appears. The inverted "V" shape
  (∧) indicates the pedal is to be momentarily released, then depressed
  again.

This also explains the use of 1/1 and 1/2, indicating either full or half lifting of the pedal. As this page explains, you can have many "degrees of pedal, such as half, quarter or even eighth pedal."


jquery hover flip effect on hyperlink

Question: Does anyone know if there is a jquery plugin to accomplish an hover effect on a hyperlink like it's done on this site (right top corner, social network links) http://www.julesbassoleil.fr/ ?
Answer: It is an icon-sprite as you can see here:
http://www.julesbassoleil.fr/img/social_icons.png
The only thing you have to do is setting the correct background positions with css on load and animate the background position on hover with jquery.
Comment: thank you, you are right. It works gread with these technique.

jquery hover flip effect on hyperlink


Finding the fixed point of a function

Question: Let $p:A \times B \to \mathbb{R}$ be a nonnegative real-valued function on $A \times B$,
where $A$ and $B$ are arbitrary set.
Assume $f:A \to B$ and $g:B \to A$ are such that
\begin{align*}
 f(a) &= \operatorname*{arg\,min}_b~p(a,b) \\
 g(b) &= \operatorname*{arg\,max}_a~p(a,b)
\end{align*}
Does the map $f \circ g:B \to B$ have a fixed point?
Which conditions are necessary for this fixed point to exists?
This question arised while searching an equilibrium point for a game.
For my game, I empirically noticed that repeated iteration of the map $f \circ g$ eventually gives me a fixed point.
So I start looking for some theoretical justification of this observation.
I dig hard, but I couldn't really find one.
My game is the fair pricing of an insurance product.
The set $A$ is a convex subset of $\mathbb{R}^n$, and is the set of action of the policyholder.
While the set $B=[0,1]$ is the set of premium of the insurer.
The function $f$ represents the objective function of a fair insurer who wants the price to be zero.
While the function $g$ is the objective function of a rational policyholder who wants to arbitrage the insurer.
The function $p$ is such that $p(a,b)=\operatorname{E}(X \mid \text{Action=a, Premium=b})$
where $X=|\text{claim}-\text{premium}|$ is the random variable of the product cash flow.
I looked into Banach fixed point theorem, Nash equilibrium existence theorem
and Kakutani's fixed point theorem.
Any help or pointer appreciated.
Answer: I think the conditions necessary for this fixed point to exists are: A and B both are Banach space and p is a continuous function.
But these may not be enough.
Comment: which theorem do you have in mind?
Answer: I'm not sure if this works or not, but I think your general problem can basically just be turned into a normal form game.
You have two players with strategy sets $A$ and $B$ where both players have the same utility function $p:A\times B\rightarrow\mathbb{R}$. The players best response functions are $f$ and $g$ respectively as you defined them above.
Right off the bat one could point out that these aren't in general functions but a correspondence (eg. what if it's a constant function?), and take for example if you defined $p:\mathbb{R}-\{0\}\times\mathbb{R}-\{0\}\rightarrow\mathbb{R}$ by $p(a,b) = \frac{1}{a} + \frac{1}{b}$, what's $f(2)$ for example? It may not even be a correspondence.
Now, if $g \circ g$ has a fixed point iff $f \circ f$ has a fixed point then I think $g \circ g$ will have a fixed point iff the game given above has a Nash equilibrium (the game's best response correspondence has a fixed point) using the strategies considered above (ie. if A and B are pure strategy sets then it would require the game has a pure strategy Nash equilibrium which is not in general true, whereas if A and B were probability distributions over some other arbitrary sets (mixed strategies) then by Nash's theorem there would exist at least one Nash equilibria).
So basically you need to consider what game is formed more specifically with your example, at least I think you could argue it this way.
Comment: I'm not clear on how to interpret mixed strategies in my case. The strategy sets $A$ and $B$ are both convex subset of $\mathbb{R}^n$. Let $\Pi(A)$ be the set of possible probability distribution on $A$. My understanding is that the mixed strategies are $\Pi(A) \times \Pi(B)$. Aren't these different?

Finding the fixed point of a function


Weighted average of percentage increase

Question: I believe I have quite a simple problem, but want clarification on whether it is the best method to use.
Say I have have insurance line, and the net income (£) from this business for 2011, 2012, 2013 is 1,000,000; 4,500,000; and 5,000,000 respectively.
Hence, the percentage increase from 11-12 is 350%, and from 12-13 is 11.1%.
Now, the average of these is 180.5%, which is a representation of the average percentage increase across all years, but it has been suggested to me to instead represent the data by a "weighted" average.
I am curious… would the weights be the difference in income from each year?
i.e. Weighted Avg. = $((3.5)*350\% + (0.5)*11.1\%)/4 = 307\%$
or would the weights possibly the values themselves? Or maybe there is another option? Maybe a standard average is sufficient?
Thanks very much for your inputs.
Answer: The weights could be almost anything, depending on why someone wanted them added. However, the arithmetic mean of the percentages is not the best method for averaging growth rates.
You have 1, 4.5, 5 in successive years and, as you noted, the growth in the first two years is 350% and in the second two years, only 11.1%; again as you noted, the arithmetic mean of these (expressed as proportions) is $\frac{3.5 + .111}{2} = 1.805$. Yet that is not the average growth: $1*1.805*1.805 = 3.205$ but your final value is 5.
You could express these as ratios of 4.5 and 1.11, then the average is 2.8. But $2.8*2.8 = 7.84$, again, not 5.
What you want is the geometric mean of the ratios: $(4.5*1.11)^{0.5} = 2.23$ and, indeed, $2.23*2.23 = 5$ (except for rounding error).
Perhaps the weights were meant to reproduce this?
Comment: Thanks Peter.. But, what if I havve, for example year 1,2,3 as 4, 3.5, 5. Then I can no longer use the geometric mean (this is a more accurate representation of the situation I am in, sorry for not clarifying this).
But yes, maybe the weights are meant to produce that, but since I have been urged to use weighted averages, it seems this is not what they are meant to produce and rather be pushed more towards the larger increases/decreases. Thanks again.

Weighted average of percentage increase


Transformar todos os elementos de uma lista em floats

Question: Esse é o código que eu escrevi.
n_alunos=input('')
x=0
idades=[]
alturas=[]

while x != n_alunos:
    x+=1
    n=raw_input('')
    a=n.split(" ")
    idades.append(a[0])
    alturas.append(a[1])

Como transformo os elementos das 2 listas de string para float ?
Answer: Pra converter uma lista já existente de strings em uma lista de floats:
lista = [float(i) for i in lista]

Fonte: https://stackoverflow.com/questions/1614236/in-python-how-do-i-convert-all-of-the-items-in-a-list-to-floats
A conversão tbm pode ser realizada direto no append:
idades.append(float(a[0]))

Reescreví seu código pra python3 realizando a conversão assim(e algumas outras modificações).Se preferir:
#!/usr/bin/python3
n_alunos = int(input('N. de alunos:    '))
idades = []
alturas = []
for i in range(n_alunos):
    dados = input('Idade/altura:    ').split(" ")
    idades.append(float(dados[0]))
    alturas.append(float(dados[1]))

Comment: map(float, lista) também é uma boa


Angular Type Number is not assignable to left side of if statement

Question: I am returning a number from a php call. The console is printing the number correctly when I return the value in a subscribe function. When I try to run an if statement to act on the return I am receiving an error in my code that I don't know how to fix. I looked around, but couldn't find any answers to this problem.
This is all happening inside of a subscribe function. I can't refer to the variable accountStatus outside of the subscribe.
this.apiService.checkAccountStatus().subscribe((accountStatus)=>{
      console.log("user account", accountStatus);
      if(accountStatus = 0)
      {
        //account doesn't exist
        console.log("user doesn't exits.", accountStatus);
      }
      if(accountStatus = 1)
      {
        //account does exist
        console.log("user does exist.", accountStatus);
      }
    })

Debugging Errors I am receiving:
Type 'number' is not assignable to type 'Account_Info'.ts(2322)

Account_Info is the name of the ts file I am using to access the database. In my apiService.checkAccountStatus() function this is what it looks like:
checkAccountStatus(){
  return this.httpClient.get<Account_Info>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}

Any advice is welcome. Thank you!
Answer: this.apiService.checkAccountStatus().subscribe((accountStatus:any)=>{
      console.log("user account", accountStatus);
      if(accountStatus = 0)
      {
        //account doesn't exist
        console.log("user doesn't exits.", accountStatus);
      }
      if(accountStatus = 1)
      {
        //account does exist
        console.log("user does exist.", accountStatus);
      }
    })

you need to define type of accountStatus like in above code i define accountStatus:any ,use this code and let me know if it work
Comment: Thank you. It was both your answer as well as someone else that commented. My final code was `this.apiService.checkAccountStatus().subscribe((accountStatus:any)=>{
      console.log("user account", accountStatus);
      if(accountStatus == 0)
      {
        //account doesn't exist
        console.log("user doesn't exits.", accountStatus);
      }
      if(accountStatus == 1)
      {
        //account does exist
        console.log("user does exist.", accountStatus);
      }
    })`
Comment: Ch Wajid, mazy kro    :)
Answer: First, change type of observable.
checkAccountStatus(){
  return this.httpClient.get<number>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}

Then, set the type on subscriber and also, be careful, you are assigning instead of comparing.
this.apiService.checkAccountStatus().subscribe((accountStatus:number)=>{
      console.log("user account", accountStatus);
       if(accountStatus === 0)  // you have (accountStatus = 0)
          {
            //account doesn't exist
            console.log("user doesn't exits.", accountStatus);
          }
          if(accountStatus === 1) // you have (accountStatus = 1)
          {
            //account does exist
            console.log("user does exist.", accountStatus);
          }
})

Comment: Thank you. It was both your answer as well as someone else that commented. My final code was `this.apiService.checkAccountStatus().subscribe((accountStatus:any)=>{
      console.log("user account", accountStatus);
      if(accountStatus == 0)
      {
        //account doesn't exist
        console.log("user doesn't exits.", accountStatus);
      }
      if(accountStatus == 1)
      {
        //account does exist
        console.log("user does exist.", accountStatus);
      }
    })`
Comment: try, to not use type any. in this case, if you are totally sure, that the backend return a number, so change the type

checkAccountStatus(){
  return this.httpClient.get(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}

this.apiService.checkAccountStatus().subscribe((accountStatus:number)=>{
Comment: Generally you should also really use strict equality `===` operator for comparisons.
Comment: What is the difference between strict equality and not strict? I am unfamiliar with this.
Comment: Check this answer: https://stackoverflow.com/a/8044811/11218448
Answer: If Account_Info is an interface, it, indeed, is not a number. You can log it to the console because you can log anything. You cannot check for a type Account_Info to be a number in TypeScript. Also in the if clause, you are assigning, not comparing the values. You have to use the following:
//...
if(+accountStatus == 0) console.log("user doesn't exist", accountStatus)
else if(+accountStatus == 1) console.log("user does exist.", accountStatus);
//...

The reason for prepending a plus before accountStatus is that the Unary operator + in JavaScript attempts to convert the value that follows it to be a number. More info: Unary Plus on MDN
N.B.: This only ever works if the value is indeed a number. Else, +accountStatus will be NaN(not a number).