What are the rules i need to follow when writing for the piano?

Question: Okay so i recently discovered writing in 4 part harmony and now i'm really confused, i saw people say that you don't need to follow the same rules for piano. But, are there any rules or guidelines for writing piano arrangements specifically?
Sorry if this has already been answered
Comment: Welcome! One of the difficulties of answering this is that piano is used in many, many different kinds of music (19th-century romantic, jazz, rock, new age, honky tonk...). They all have their own conventions, if not "rules." It might help get a more useful answer if you can edit to say more about the kind of writing you're planning.
Comment: You don't need to follow any rules, unless you want to.
Comment: Anything that requires 11 or more fingers to play is probably wrong.
Comment: If you could also post where you saw people say this (for instance, on this site, or somewhere else?), that might help. Maybe there was a miscommunication or misinterpretation of the original.
Answer: When people talk about four part harmony they usually talk about a theoretical theory of voice leading. This is tool you have at your dispense when you need it. Understanding the rules of four part harmony may help you understand why certain things sound weird, and give you an understanding of how one can improve such things.
But that's it. When composing it is your choice to make use of these tools or do things differently. But still it helps to know the rules and break them by intent rather than not knowing the rules and breaking them by accident.
For instance compare these two examples:

Both totally break the traditional rules of voice leading, but the second one sounds fine, while the first sounds a bit awkward. Knowing the rules will help you understand why that sounds awkward, and will allow you to make it less awkward.
Answer: The four part harmony "rules" you are thinking of are historically about how the Church composed sacred music, choral music. Over centuries of musical style changes those rules carried over into secular, instrumental music with varying degrees of strictness.
To give you some perspective about those historical changes think of someone like Handel and hist sacred choral music as the epitome of proper four part harmony. Compare Handel to Chopin. I was recently playing some dances of Chopin and took note of the very obvious places where he abandoned the old part writing conventions and wrote completely undisguised parallel octaves. That takes us back 150 years from present when the old style was already being abandoned by European composers who largely followed a harmony style develop another 150 years prior. That's a long history of influence and change! We need to be careful about applying "rules" from that long history and the potential to misunderstand them.
Four part harmony rules are not the rules of all music, only the rules of a particular style. That style was very, very popular for a long time. Aspects of that harmonic style are still found in various music styles today.
A general "rule", technically a music texture, that you should be aware of is homophonic texture, which is a melody supported by chords. In homophonic style the bass part moves in large part by chord roots and has a contour (shape of a melodic line) which is characteristically different than the main melody. Instead of thinking about the old four part vocal harmony rules you can think about writing good melody lines, good bass lines, and the chords that support both.
Melody and bass can be filled in with chords. In a lot of styles those chords are played on keyboard or guitar. For this you should be aware of basic voice leading which is a carry over of some of the old four part harmony rules. Basic voice leading makes chord changes by moving "voices" of chords by single steps. You can generally categorize three types of movements by how many voice change in triadic harmony.

Notice I marked with <code>*</code> two voice leading options that don't move by single steps. I included them, because they are common and provides alternatives to move the voices either up or down.
Most chord play on keyboard and guitar uses those patterns or variations of them.
Take note of the root progressions that result from the voice leading patterns. This small number of voice leading patterns covers root progressions by fifth/fourth, third/sixth, and second/seventh which is all of the simple intervals. In other words you can use these patterns for any diatonically based chord progression, most common chord progressions.
I'm not specifically covering seventh chords, but if you fill in the missing sevenths for all of the triads in those example patterns you will find that the number of voices moved stays the same and the root progressions stay the same.
This provides a short hand, cheat sheet level of voice leading guidelines and actually covers a fair amount of how strict four part writing works. It doesn't include things like doubling tones and handling tendency tones, but that is the kind of stuff abandoned in non-strict and pop styles of harmony.
Arranging would treat these chord/voice leading patterns as a skeleton, just a framework, that could be played with various rhythmic patterns. You could play them as broken chords, arpeggios, decorated with passing tones, etc. etc. Depending on whether the music is piano solo or an ensemble you might add a bass part. A melody, like a vocal part, could be added, but in many cases the rhythmic elaboration of the chord framework becomes the main melody.

Okay so i recently discovered writing in 4 part harmony and now i'm really confused, i saw people say that you don't need to follow the same rules for piano.

There are no rules. Not really. But there are "conventions" for well defined styles.
Even if you aren't following strict four part harmony rules, most homophonic music, which includes lots of pop styles, use basic voice leading patterns.


Java - How can I revise my replacePlaceholder method so that it no longer has an index out of bounds error for my mad libs program?

Question: ISSUE SOLVED, CODE BELOW NOT UPDATED
I have solved the issue I had with this code with the help of one helpful user. The code below is not updated.
    // replacePlaceholder method
    private String replacePlaceholder(String template, String placeholder, String replacement)
    {
        String newTemplate = "";
        int count = 0;
        for(int i = 0; i < template.length(); i++)
        {
             if(count == 0 && template.substring(i, i + placeholder.length()).equals(placeholder))
            {
                newTemplate += replacement;
                count++;
            }
            else if(count != 1)
            {
                newTemplate += template.substring(i, i + 1);
            }
        }
        return newTemplate;
    }

Comment: go through a debugger, you will find out yourself
Comment: The message tells you that you try to use invalid index values within that string. Simply **print** the string, and the indexes you want to use. Then fix the logic that comes up with numbers such as -1 ;-) ... or improve your question, by looking at [mcve].
Comment: What is this method supposed to do, exactly? If you just need to replace sub-strings in another string there's the `replace(String placeholder, String replacement)` method.
Comment: This method is supposed to replace a given placeholder in a template with a given replacement String.
Answer: As pointed out by the comments, you should just use String.replace(String, String) or String.replaceAll(String, String) instead of writing it yourself. There are a number of issues with your current implementation:

template.substring(i, placeholder.length() + 1) should be template.substring(i, i + placeholder.length()). Otherwise, your beginIndex can be larger than endIndex.
If template ends with half a placeholder, substring will fail because endIndex is too large.
aaa[placeholder]aaa will be turned into aaareplacementplaceholder]aaa with you current code as you do not skip the rest of the placeholder.
A second placeholder will not be replaced as you say count++ but never reset it, making your if always go to else.
possibly more
Comment: Solved all problems except for "aaa[placeholder]aaa will be turned into aaareplacementplaceholder]aaa with you current code as you do not skip the rest of the placeholder." Also, I only want one placeholder to be replaced at a time, that is why I have "count" never being reset.
Comment: @mini23 I see. Maybe you can then call `newTemplate += template.substring(i + placeHolder.length()); break;` after adding the replacement. Then you do not need `count` anymore.
Comment: Got it. I'm still stuck on how to solve the issue with not replacing the rest of the placeholder.
Comment: @mini23 It happens because you continue looping every single character of `template`. It should be solved with what I wrote above: As soon as you find the placeholder (i.e. in your `if->true` block), you should append the `replacement`, append the rest of `template` (`substring` starting at **`placeholder.length()+1`**) and **`break` the loop** (which will prevent adding the rest of `placeholder`).


How to show div again when scroll using vh?

Question: I am trying to make a horizontal transition when scrolling down and up to show and resize (shrink) div of the first element. I used inline-block to put them in the same position so that when one has been shrunk the other element will slide through but I am a bit confused to achieve this.
I tried to calculate the height and the offset position of the first inline element. This obviously will work for the first inline element but it won't work on the second inline element because it's in the same offset position.
Can you guys give me a bit of direction or tips to achieve this?

var topofDiv = $(".one").offset().top;
var heightDiv = $(".one").outerHeight();

$(window).scroll(function() {
  if ($(window).scrollTop() > (topofDiv + heightDiv)) {
    $(".one").show();
  } else {
    $(".one").hide();
  }
});
* {
  margin: 0;
  padding: 0;
}

body {
  overflow-x: hidden;
}

.container {
  width: 100vw;
  height: 100vh;
}

.content-wrapper {
  width: 100vw;
  white-space: nowrap;
}

.section {
  width: 100vw;
  height: 100vh;
  position: relative;
  display: inline-block;
}

.section div {
  font-size: 100px;
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

.one {
  background-color: red;
}

.two {
  background-color: yellow;
}

one

two

Answer: The show() and hide() calls need to be swapped over, they're in the wrong sides of your if condition. Also, the page height needs to be greater than the height of one of the .section elements for the transition to work properly, and the .container needs to be in fixed position for the scroll to have no effect on it. Try this:

var topofDiv = $(".one").offset().top;
var heightDiv = $(".one").outerHeight();

$(window).scroll(function() {
  if ($(window).scrollTop() > (topofDiv + heightDiv)) {
    $(".one").hide();
  } else {
    $(".one").show();
  }
});
* {
  margin: 0;
  padding: 0;
}

body {
  overflow-x: hidden;
  height: 2000px;
}

.container {
  width: 100vw;
  height: 100vh;
  position: fixed;
}

.content-wrapper {
  width: 100vw;
  white-space: nowrap;
}

.section {
  width: 100vw;
  height: 100vh;
  position: relative;
  display: inline-block;
}

.section div {
  font-size: 100px;
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
}

.one {
  background-color: red;
}

.two {
  background-color: yellow;
}

one

two


How to send data from iphone to bonjour service?

Question: I created an iOS app in objective-c, and this app first browse the local networks.
After the app found a bonjour service I would like to read/write data to that computer.
I think I should use the CFNetwork framework but which part?
What is the simplies way to read/write data from a computer in the same network?
Comment: https://github.com/robbiehanson/CocoaAsyncSocket
Answer: The Bonjour service's main function is to discover other Bonjour enabled device on LAN, it does nothing about read/write the data from a computer. To read/write the data on a computer, you will have to leverage some other network protocols, HTTP is one of them and commonly used.
Let's say you implement some API interface on HTTP, then you can use the Bonjour to locate the device and establish the communication. For example, if the computer's Bonjour name is mypc._tcp.local., then write data could be done with http://mypc._tcp.local./write/data (depends on your API implementation).
Apple documentation about Bonjour, Bonjour Overview


How do I specify ALL source node types in upgrade_d7_node_complete_book migration yaml

Question: Drupal migrate_plus creates a default migration yaml for migrating books: upgrade_d7_node_complete_book.yml
<code>langcode: en
status: true
dependencies: {  }
id: upgrade_d7_node_complete_book
class: Drupal\node\Plugin\migrate\D7NodeTranslation
field_plugin_method: null
cck_plugin_method: null
migration_tags:
  - 'Drupal 7'
  - Content
migration_group: migrate_drupal_7
label: 'Node complete (Book page)'
source:
  plugin: d7_node_complete
  node_type: book
</code>
As you see, the default source node_type is "book".  However, I would like to migrate ALL of my source content types to the Drupal 9 book content type.  How do I configure this?
Answer: This is how it is done in d7_node
<code> * @code
 * source:
 *   plugin: d7_node
 *   node_type: [page, test]
 * @endcode
 *
 * In this example nodes of type page and test are retrieved from the source
 * database.
</code>
I am assuming it holds true for d7_node_complete.


Regression produces a high coefficient of determination, but also a high MSE

Question: I've ran several regression models on a dataset (the SEER cancer dataset). I'm trying to use regression to calculate how many months a cancer patient can expect to live. Each record consists of around 20 features, such as tumor size, race, etc. The training data includes the months each patient lives, which I use to train the regressor.
I split the dataset into train and  held out test sets, but I'm observing something interesting. I'm getting a high, satisfactory $R^2$ (scikit learn score function), but also a high MSE. My code (for one of the algorithms I used) is below
alldata = pd.read_csv('alldata.csv')

cols = [col for col in alldata.columns if col not in ['Survival months', 'Survived']]

X = alldata[cols].values
y = alldata["Survival months"].values

Xr, Xt, yr, yt = train_test_split(X, y, random_state=6131997)
rfr = RandomForestRegressor(n_estimators=2000, oob_score=True, n_jobs=-1)
rfr = rfr.fit(Xr, yr)
ypred = rfr.predict(Xt)
acc = rfr.score(Xt, yt)
print mean_squared_error(yt, ypred)
print rfr.oob_score_
print acc
scores = cross_val_score(rfr, Xr, yr, cv=10)
print scores
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std()*2))

The output:
76.9924308448 (MSE)
0.899907201044 (oob score)
0.894280365688 (score / R^2 / coefficient of determination)
[ 0.9027185   0.89860441  0.90686577  0.90264802  0.90139131  0.90345359
  0.89532146  0.89681607  0.90167825  0.89130112] (10 fold crossvalidation outputs)
Accuracy: 0.90 (+/- 0.01) (average of the crossvalidation outputs, and their stdev)

How can the regression model correlate with the data 90% of the time, yet have such a high MSE? That's around 8.8 months of error on average with the prediction. I'm quite new to regression, so I may be interpreting the MSE incorrectly.
Could you give your opinion on my results: are they satisfactory or not, and by what metric / why did you choose that metric? The data includes patients that had survival times ranging from 0 months to 70 months and beyond; 8.8 months seems like a significant amount to be off.
Comment: You seem to completely ignoring whether the patient is alive or not at the end of the time period.
Answer: The mean square error MSE reported for this regression is about 77 months squared, the ridiculous default display format of your software aside.
You quite rightly work with its square root, about 8.8 months, which we can call the root MSE or RMSE. Several other names exist. Regardless of terminology, I would assert that the MSE is usually no help at all in thinking about the model while the RMSE can be helpful, the difference lying in using familiar units of measurement. But even with square rooting, a few large errors or residuals can pull up either measure, and that is consistent with many errors being quite small.
Without seeing your data I am not at all surprised by that result for either measure. In this kind of data, the uncertainty of predictions is high even given good information on the characteristics of the patients. Everyone has heard stories of people given 6 months to survive but lasting 2 years, and so forth. That's usually a matter of expert guesses being uncertain rather than a regression model leaving a considerable degree of scatter, but there is a link.
In broad terms, $R^2$ and RMSE are on quite different scales. If they appear to be conflicting, that can always be resolved by looking at the complete set of errors or residuals. Even with several predictors in a regression model, you can always inspect one or more of a histogram of residuals, a plot of residuals versus predicted values, or a plot of observed versus predicted values.
An aside on two minor points of language
Even when used informally, I would advise strongly against wording such as

"the regression model correlate[s] with the data 90% of the time"

It is in no sense helpful, or even meaningful, to regard $R^2$ as the fraction of the time, or even of the data, that the model shows a correlation. Correlation is a property of a dataset, not individual observations. Moreover, correlation is a matter of degree, not a yes or no matter.

"a significant amount to be off"

The word "significant" is over-loaded in discussions of statistical applications. There are good words like "big", "large", "notable", "major" to be used when your meaning is informal. Reserve the term "significant" for discussing the results of a formal significance test.
P.S. In 45 years or so of using statistics, I don't think I have ever seen $R^2$ reported to as many as 13 decimal places. Most experienced researchers wouldn't use more than 3.
Comment: Thanks for the pointers, especially with the language. I'm not very familiar with statistics / ML at this point, and I'll be sure to word my questions more carefully next time.
Regarding which metric to use: Do people generally use MSE / RMSE / or the coefficient of determination? (or does it vary by dataset)?
Thanks!
Comment: edit to my previous comment: Am I correct to say that the best way to interpret my results would be to take both the coefficient of determination, the RMSE, and look at the residuals as well?
Comment: All of these can be helpful and informative, but even combined they are not sufficient. There are lots of good texts discussing, and indeed even focusing on, regression. Also don't underestimate the hundreds or even thousands of threads on regression here on CV. It's not usually necessary to ask a new question.
Comment: Note also that I was focusing on your question on measures used as figures of merit for regression. I'd echo comments elsewhere that regression is not necessarily the best method for your example dataset. It's not guaranteed to predict non-negative survival times, for one.
Answer: This is a survival analysis problem. If you want to use a random forest, why not use randomForestSRC, which is designed to handle survival analysis problems?


Multiple url aliasses per node in multi language website

Question: Hope this is the right place for this question. I'm turning to you guys because I just cannot decide on the best way to go for this issue.
I'm currently developing a multi-language site which is split up in 2 main sections. Section A will be the main section and is available in 2 languages; Dutch and English. Section B will only be available in English.
Section B will have a different Menu, a slightly modified layout and some other blocks will be shown on different pages within the section.
I'd like to achieve the following url structure:
Section A:
/nl/title-of-a-node-in-dutch
/en/title-of-a-node-in-english
Section B:
/en/section-b/title-of-a-node-in-english (If possible, I'd like to drop the language prefix /en/ here)
I've configured Drupal with Entity Translation (+ Title module), so each node has translations on field-level and is not entirely duplicated like it would be the case with Content Translation (i18n).
The problem is that I'm going to have a lot of content (tens of thousands of nodes) for this site and some items should be shown in both Section A and B.
Content that will be shared with both sections should only exist in one node. I definitely do not want to create an extra node with the same content just to make it available for Section B, this would be bad for content management and have a huge impact on the database.
Some of the solutions I've thought of:

Create 2 checkbox fields in the content type to indicate in which section the node should be made available. Create a hook on node insert/update and check which section was selected. If Section B was chosen, create an extra url alias which starts with /section-b/{node-title}. This would make the node content available via this extra alias, but I'm not sure what the implications this method will have, like how to handle breadcrumbs or (multilingual) Menu Structures for Section B
Configure Drupal to use a language fallback with Language Neutral and somehow add Section B as a custom language with the prefix 'section-b'. (is this even possible?)
Use url rewrites /section-b/my-title -> /en/my-title and programatically load the node and show the content via theming/templates
Maybe I can do something with Rules?

Relevant modules I'm using:
pathauto, entity_translation, path_translation, i18n_translation, title
Do you guys have any other suggestions in how to set this up? I hope I'm clear on this issue. Content management is very important in this matter :)
Thnx!
Answer: I'm not sure if this article helps, but here it is: https://www.drupal.org/node/1516444
For something more complex, I've actually implemented a hook_url_inbound_alter() to control the redirection of pages and it's worked pretty well for me, but it involves creating the logic yourself. On the other hand, the benefit is that you can completely control when and where you redirect page visits.
Answer: You can look into pathauto.api.php located inside the pathauto module to see which hook suits you best for setting the path programmatically (if this is an option for you).
The path can be set or modified per language (which is german and english in this case) like this:
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "en");
\Drupal::service('path.alias_storage')->save("/node/" . $node->id(), '/some_alias/' . $node->id(), "de");

I hope I did get you right and this is useful to you.


How to store lots of user uploaded files in Asp.net in load balanced hosting

Question: I'm building a Asp.net site where users can upload files into their user account and then download them whenever they are logged in.  The files will typically be less than 5MB and users can only download the files that they have uploaded (i.e can't download someone else's file).  There are around 100k users and each could potentially upload around 2 or 3 files.  The live site is load balanced
I'm thinking that storing these files in the central  DB (Sql Server) as a BLOB would be nice because...

As the site is load balanced, each node can access the file from the central DB. No need to worry about having shared folder to store the files
I can more easily ensure that user's only download their own files.
Backing up the DB automatically includes the file BLOBS

Only downside to this I've read is performance, but how bad can this be?
If I were to store these files in the file system, would there be any problem storing it all in one folder?
What is the best approach for this?
Answer: If you want it fast, then store the data to the filesystem. In this case you dont need to read the amount of data from the sql server. In this case you could do two things:
1st approach: Store all files in one single folder (NTFS limit: 4,294,967,295, FAT limit: 268,435,437)
2nd approach: Create for each user (userid) a separate subfolder. i would prefer this over the 1st approach.
With newer versions of SQL Server you can also use FILESTREAM.
It would be also interesting to knew

How many users do you have
how many uploads per day/hour/minute could you have
how many downloads per day/hour/minute could you have
how many uploads at the same time could you have
how many downloads at the same time could you have
what is the size of the systems you have
is it internally used/externally - which bandwidth/network load do you have etc.


Busca em Ajax dentro de div clone jquery

Question: Tenho uma busca em um input que retorna o resultado em ajax, tipo autocomplete que está funcionando (quando digito 3 primeiros digitos ela mostra os resultados), mas quando eu coloco esse input dentro de uma div "clone" (jquery) ela não funciona a busca e não retorna nenhum resultado...
Coloquei o código no jsfiddle:
https://jsfiddle.net/g9dehL8j/2/
Answer: O problema é que quando usas $("#produto").keyup(function(){ o auscultador de evento fica só à escuta de eventos no elemento #produto que já existia quando a página foi carregada. Neste caso, e como o Lucas também referiu, não podes usar ID pois na página só pode haver um elemento com cada ID.
Se usares esse evento delegado, e juntando ambos #engloba-template e #conteudo_engloba poderia ficar assim:
$('#engloba-template, #conteudo_engloba').on('keyup', 'input[name="produto[]"]', function() {

jsFiddle: https://jsfiddle.net/g9dehL8j/3/
Answer: Quando você clona é compreensível repetir o idno seu caso. Tente fazer a seleção por uma propriedade qualquer:
HTML
<input type="text" autocomplete="off" id="produto" produto name="produto[]">
                                                   ^^^^^^^

JS
$("input[produto]").keyup(function(){ });

Comment: `+1` por referires o problema de ID duplicado
Comment: obrigado por tentar ajudar, mas não resolveu...


Interpretation of Radon-Nikodym derivative between probability measures?

Question: I have seen at some points the use of the Radon-Nikodym derivative of one probability measure with respect to another, most notably in the Kullback-Leibler divergence, where it is the derivative of the probability measure of a model for some arbitrary parameter $\theta$ with respect to the real parameter $\theta_0$:
$$\frac {dP_\theta}{dP_{\theta_0}}$$
Where these are both probability measures on the space of datapoints conditional on a parameter value: $P_\theta(D)=P(D|\theta)$.
What is the interpretation of such a Radon-Nikodym derivative in the Kullback-Leibler divergence, or more generally between two probability measures?
Answer: First, we don't need probability measures, just $\sigma$-finiteness. So let $\mathcal M = (\Omega, \mathscr F)$ be a measurable space and let $\mu$ and $\nu$ be $\sigma$-finite measures on $\mathcal M$.
The Radon-Nikodym theorem states that if $\mu(A) = 0 \implies \nu(A) = 0$ for all $A \in \mathscr F$, denoted by $\mu \gg \nu$, then there exists a non-negative Borel function $f$ such that
$$
\nu(A) = \int_A f \,\text d\mu
$$
for all $A \in \mathscr F$.
Here's how I like to think of this. First, for any two measures on $\mathcal M$, let's define $\mu \sim \nu$ to mean $\mu(A) = 0 \iff \nu(A) = 0$. This is a valid equivalence relationship and we say that $\mu$ and $\nu$ are equivalent in this case. Why is this a sensible equivalence for measures? Measures are just functions but their domains are tricky to visualize. What about if two ordinary functions $f, g :\mathbb R \to \mathbb R$ have this property, i.e. $f(x) = 0 \iff g(x) = 0$? Well, define
$$
h(x) = \begin{cases} f(x) / g(x) & g(x) \neq 0 \\ \pi^e & \text{o.w.}\end{cases}
$$
and note that anywhere on the support of $g$ we have $gh = f$, and outside of the support of $g$ $gh = 0 \cdot \pi^e = 0 = f$ (since $f$ and $g$ share supports) so $h$ lets us rescale $g$ into $f$. As @whuber points out, the key idea here is not that $0/0$ is somehow "safe" to do or ignore, but rather when $g = 0$ then it doesn't matter what $h$ does so we can just define it arbitrarily (like to be $\pi^e$ which has no special significance here) and things still work. Also in this case we can define the analogous function $h'$ with $g / f$ so that $fh' = g$.
Next suppose that $g(x) = 0 \implies f(x) = 0$, but the other direction does not necessarily hold. This means that our previous definition of $h$ still works, but now $h'$ doesn't work since it'll have actual divisions by $0$. Thus we can rescale $g$ into $f$ via $gh = f$, but we can't go the other direction because we'd need to rescale something $0$ into something non-zero.
Now let's return to $\mu$ and $\nu$ and denote our RND by $f$. If $\mu \sim \nu$, then this intuitively means that one can be rescaled into the other, and vice versa. But generally we only want to go one direction with this (i.e. rescale a nice measure like the Lebesgue measure into a more abstract measure) so we only need $\mu \gg \nu$ to do useful things. This rescaling is the heart of the RND.
Returning to @whuber's point in the comments,  there is an extra subtlety to why it is safe to ignore the issue of $0/0$. That's because with measures we're only ever defining things up to sets of measure $0$ so on any set $A$ with $\mu(A) = 0$ we can just make our RND take any value, say $1$. So it is not that $0/0$ is intrinsically safe but rather anywhere that we would have $0/0$ is a set of measure $0$ w.r.t. $\mu$ so we can just define our RND to be something nice there without affecting anything.
As an example, suppose $k \cdot \mu = \nu$ for some $k > 0$. Then
$$
\nu(A) = \int_A \,\text d\nu = \int_A k \,\text d \mu
$$
so we have that $f(x) = k = \frac{\text d\nu}{\text d\mu}$ is the RND (this can be justified more formally by the change of measures theorem). This is good because we have exactly recovered the scaling factor.
Here's a second example to emphasize how changing RNDs on sets of measure $0$ doesn't affect them. Let $f(x) = \varphi(x) + 1_{\mathbb Q}(x)$, i.e. it's the standard normal PDF plus $1$ if the input is rational, and let $X$ be a RV with this density. This means
$$
P(X \in A) = \int_A \left(\varphi + 1_{\mathbb Q}\right) \,\text d\lambda
$$
$$
= \int_A \varphi \,\text d\lambda + \lambda\left(\mathbb Q \right) =\int_A \varphi \,\text d\lambda
$$
so actually $X$ is still a standard Gaussian RV. It has not affected the distribution in any way to change $X$ on $\mathbb Q$ because it is a set of measure $0$ w.r.t. $\lambda$.
As a final example, suppose $X \sim \text{Pois}(\eta)$ and $Y \sim \text{Bin}(n, p)$ and let $P_X$ and $P_Y$ be their respective distributions. Recall that a pmf is a RND with respect to the counting measure $c$, and since $c$ has the property that $c(A) = 0 \iff A = \emptyset$, it turns out that
$$
\frac{\text dP_Y}{\text dP_X} = \frac{\text dP_Y / \text dc}{\text dP_X / \text dc} = \frac{f_Y}{f_X}
$$
so we can compute
$$
P_Y(A) = \int_A \,\text dP_Y
$$
$$
= \int_A \frac{\text dP_Y}{\text dP_X}\,\text dP_X = \int_A \frac{\text dP_Y}{\text dP_X}\frac{\text dP_X}{\text dc}\,\text dc
$$
$$
= \sum_{y \in A} \frac{\text dP_Y}{\text dP_X}(y)\frac{\text dP_X}{\text dc}(y) = \sum_{y \in A} \frac{f_Y(y)}{f_X(y)}f_X(y) = \sum_{y \in A} f_Y(y).
$$
Thus because $P(X = n) > 0$ for all $n$ in the support of $Y$, we can rescale integration with respect to a Poisson distribution into integration with respect to a binomial distribution, although because everything's discrete it turns out to look like a trivial result.

I addressed your more general question but didn't touch on KL divergences. For me, at least, I find KL divergence much easier to interpret in terms of hypothesis testing like @kjetil b halvorsen's answer here. If $P \ll Q$ and there exists a measure $\mu$ that dominates both then using $\frac{\text dP}{\text dQ} = \frac{\text dP / \text d\mu}{\text dQ / \text d\mu} := p / q$ we can recover the form with densities, so for me I find that easier.
Comment: I enjoyed this exposition (as I enjoy all of your contributions), but at bottom it seems predicated on the (repeated) assertion that $0/0$ makes some kind of sense--but it does not.  There's something going on with measures that doesn't automatically happen with functions of real values: *you may simply ignore what happens on sets of measure zero.*  That's how you avoid having to make sense of $0/0$ in the Radon-Nikodym derivative setting.
Comment: @whuber thanks a lot for the comment, that really helps. I've tried to update to address that


Saber quais valores dentro da condição IN que não estão ligados a tabela

Question: Olá,
Tenho uma tabela muito simples como exemplo:

Tenho também uma query que verifica os valores existentes dentro do IN, exemplo:
SELECT * FROM tLetras l WHERE l.letras IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');

Essa consulta certamente me devolverá todos os valores que estão na tabela tLetras.
O que eu preciso, na verdade, é saber quais letras (valores) que estão dentro do IN e que não estão dentro da TABLE. Ou seja, os valores que preciso saber são 'E','H','I','L','O','P','Q','R','S','T','U','V','W','X','Y','Z', que são justamente os valores que não estão na TABLE mas que estão no IN.
Comment: Tente utilizar o operador MINUS, é o EXCEPT no Oracle.
Answer: Como a sua lista de letras não está numa tabela, precisa colocar numa "pseudo-tabela", ou "dummy table". O oracle tem um recurso interessante para fazer isso que é declarar uma table no corpo do select, assim:
select *
  from tLetras  l
  right join table(sys.odcivarchar2list('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')) lista on l.letras=lista.column_value
  where l.letras is null

Fazendo o right join traz os elementos que não existam na esquerda (tabela tLetras ) mas existam na lista da direita. Por fim, o l.letra is null traz as letras que não existem, pois vai retornar null onde não coincidir o join
Veja aqui um exemplo funcionando: sqlfiddle
Aqui a documentação de odcivarchar2list
Answer: Não é possível seleccionar algo que não existe na tabela.
O que pode ser feito é ter uma tabela com as letras todas e usar
SELECT letra FROM LetrasTodas
WHERE letra NOT IN (SELECT letras FROM tLetras);

Exemplo com sys.odcivarchar2list, como sugerido na resposta do Ricardo Pontual, mas usando NOT IN em vez de JOIN, o que, neste caso, me parece mais apropriado.
SELECT lista.column_value
FROM table(sys.odcivarchar2list('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')) lista
WHERE lista.column_value NOT IN (SELECT letras FROM tLetras)

sqlfiddle.


UIGraphicsImageRenderer closure doesn't complete and return an image in some cases when invoked from within an extension

Question: I'm attempting to generate an image when a notification service extension receives a push (yes that's within a service extension, not a content extension. I have a requirement to generate an image and add to contacts on receipt of a user directed push). I have noticed however that in some usages UIGraphicsImageRenderer doesn't return, depending upon what its closure contains. Here's an example:
    let mainImageRenderer = UIGraphicsImageRenderer(size: theSize)
    let mainImage = mainImageRenderer.image { context in
        context.cgContext.setFillColor(UIColor.clear.cgColor)
        context.fill(CGRect(origin: .zero, size: screenSize))
        let rectangle = CGRect(x: 0, y: 0, width: 50, height: 50)
        context.cgContext.setFillColor(UIColor.red.cgColor)
        context.cgContext.setStrokeColor(UIColor.black.cgColor)
        context.cgContext.setLineWidth(10)
        context.cgContext.addRect(rectangle)
        context.cgContext.drawPath(using: .fillStroke)
        NSLog("Line 1 - This line logged")
    }
    NSLog("Line 2 - This line not logged and no image is created")

If this code is run within the app itself (or run within a notification content extension for that matter) then it works and Line 2 is reached, but when its run within a notification service extension then Line 2 is never reached.
Its similar behavior if the closure includes UIImage.draw(at:) or UIImage.draw(in) for example. However if the closure contains NSAttributedString.draw() then the code executes as expected when called from within the notification extension, here's example code which does workand in this case Line 2 does get reached:
let textImage = textRenderer.image { context in
    context.cgContext.setFillColor(gray.cgColor)
    context.fill(CGRect(origin: .zero, size: textRectangleSize))
    let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = .center
    let attrs: [NSAttributedString.Key: Any] = [
        .font: UIFont.systemFont(ofSize: 10),
        .paragraphStyle: paragraphStyle
    ]
    let attributedString = NSAttributedString(string: transcript, attributes: attrs)
    attributedString.draw(with: CGRect(x: 10, y: 10, width: textRectangleSize.width - 20, height:textRectangleSize.height - 20),
                          options: .usesLineFragmentOrigin, context: nil)
    NSLog("Line 1 - This line logged")
}
NSLog("Line 2 - Now this line is logged and image is created")

Is there some fundamental reason/issue preventing UIKit from functioning properly within a notification service extension? If so then why is NSAttributedString.draw not causing any issues with  UIGraphicsImageRenderer but other things such as UIImage.draw() do cause issues?
Is there an alternative graphics API that I could use instead of UIGraphicsImageRenderer()? I basically want to be able to draw a rectangle within another UIImage.
UPDATE:
After doing some more experimentation, I discovered the size of the image being created affects the results, for example this fails:
private class func createBackdropImage() -> UIImage {
    let screenSize = CGSize(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    let renderer = UIGraphicsImageRenderer(size: screenSize)
    let image = renderer.image { context in
        context.cgContext.setFillColor(UIColor.red.cgColor)
        context.fill(CGRect(origin: .zero, size: screenSize))
    }
    NSLog("May or may not reach here depending upon size")
    return image
}

If I run the following, on my handset the values for width/height are coming out at 375/812 and this causes the code not to execute as expected and the log line not to be reached. However if the size is made smaller then it works as expected. I tried reducing a little from 375/812 down to 370/800 but it still fails, however if I make it smaller, for example 300/700, then it starts working.
Why is the size of the image being created having this affect? And why only within a notification service extension is this behavior happening?
Comment: there's a question regarding a similar topic [here](https://stackoverflow.com/questions/50064586/why-is-uigraphicsimagerenderer-not-working-properly-in-unnotificationserviceexte). Maybe it will give you some answers
Comment: Suggest you use one of your two yearly DTS requests and get Apple's help.
Answer: I think this probably is a memory issue. Extensions have limited memory and trying to do image processing with images the size of the screen dimensions might be too much for it, hence why decreasing the overall size of the image being created makes it work.


Not calling SqlConnection.Close() in Windows Forms - Why does it work sometimes

Question: A friend of mine was hosting an ASP.NET 2.0 app at home until he moved and I offered to host it on my own Win7/IIS7/SQLE2008r2 server.
When I put the code up on my server, after just a few requests I would get this error:

Timeout expired.  The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

First I turned up max pool size to temporarily "fix" the problem. Then I took a closer look at his code. It turned out that he never called SqlConnection.Close(). So I added closing and removed max pool size from all the connection strings, and the problem was solved.
I asked him how he solved the problem, and if he'd somehow increased max pool size per default in his server's default web.config or something. He replied ".NET Garbage Collection". So he was relying on garbage collection to close his database connections, and on his server that worked. But on mine it didn't.
Can anyone explain why? He's on vacation so I don't want to bother him asking him for details on versions etc, but I would guess he was running Win2k8.
Comment: I should have added that I know it's not good practice, and I know how to do it properly and why. My main question is why it has worked so well over a long period on his server. Is it just a question of him having too little RAM which causes GC to be more aggressive?
Answer: Jeff Atwood has a wonderful article about this very thing, I highly recommend this read.
Relying on .NET garbage collection to close SQL Connections is a no-no. SqlConnection.Close(), as well as Dispose() should always be called, but Close() at the very least. Note that the using keyword will take care of disposing objects automatically for you (example).
It's irresponsible and silly to rely on the GC for anything. That's like ignoring memory all together and saying "Oh, when the user runs out of RAM, they can just restart! : D" .
In a nut shell, the code not working on the new deployment site is NOT your fault. In this case, it's the coders for irresponsible SQLConnection handling.
Answer: The problem with relying on the garbage collector to close the connections, is that you can't.
If you leave the connection ojbects for the garbage collector to clean up, you have no control over when that happens. The garbage collector will close them eventually, but when that happens depends on a lot of factors, for example how much available memory there is, and how much memory is used. Those factors will be different from one server to another, but they may also change over time, so you can't even count on the garbage collector to always work the same even on the same server.
Different databases react differently on having a lot of unclosed connections. An Access database for example is extremely sensetive to this, not allowing more than 64 connections.
Anyhow, you should always close your connections, and your data readers. Also, you should use using blocks or try...finally blocks to make sure that the connections are really always closed, even if something goes wrong in the code.
Answer: It's perfectly fine to leave it to the garbage collector, as long as the rate of garbage collection exceeds the rate at which new connections are being created.  But I've never seen anyone use ASP.NET in such a way that this would happen.
The only time you should not call SqlConnection.Dispose is when you absolutely can't.  For instance, calling it from the destructor of the class that owns it will randomly throw an exception, so if that's the only hope you have, just leave the connection open.
Comment: It's just so not fine to leave it to garbage collection. : ( Remember, always code like the next person who reads it is a madman who owns a machete and knows where you live!


upload multiplo de imagens com jqueryform e ajax

Question: Boa tarde, estou tentando realizar upload de multiplas imagens utilizando jquery-form e ajax para nao dar reload mas nao esta passando pra pagina via ajax pelo  onchange  e nao esta gravando no banco nem fazendo o upload. segue codigo:
index.php

<form id="formImage" enctype="multipart/form-data">
    <input type="text" name="id" value="<?php echo $resultado['id']; ?>" style="display:none;">
    <input type="file" id="files" style="float:left; width:700px; margin-top:0px;" name="fileUpload[]" onchange="saveImages()" multiple />
</form>

upload-fotos.php
<?php
if(isset($_FILES['fileUpload']))
{
  //require("../config/wideimage-11.02.19-full/lib/WideImage.php");
  require("../config/conexao.php");
  $id = $_POST['id'];

  date_default_timezone_set('America/Sao_Paulo');

  $name     = $_FILES['fileUpload']['name'];
  $tmp_name = $_FILES['fileUpload']['tmp_name'];

  $allowedExts = array(".jpeg", ".jpg", ".png");

  $dir = '../uploads/servicos/';

  for($i = 0; $i < count($tmp_name); $i++)
  {
        $ext = pathinfo($name[$i], PATHINFO_EXTENSION);
        $ext = strtolower($ext);

     if(in_array($ext, $allowedExts))
     {
         $datetime = date("Y.m.d-H.i.s");
         $newtime = preg_replace('/[ :-]+/' , '' , $timedate);
        $new_name = $newtime ."-". $i . $ext;

        if(move_uploaded_file($new_name, $dir));
        //$image = WideImage::load($tmp_name[$i]);
       // $image->saveToFile($dir.$new_name);
        $sql = "INSERT INTO fotos_servicos(id_servico, img) VALUES (:idsv, :img)";
        $insert = $conn->prepare($sql);
        $insert->bindParam(':idsv', $id);
        $insert->bindParam(':img', $new_name);
        $conn->beginTransaction();
        $insert->execute();
        $conn->commit();
     }
  }
}
?>

Answer: A função pathinfo retorna a extensão sem o ., na sua variável $allowedExts você especifica as extensões com o ., por isso ele não está passando no seu teste in_array($ext, $allowedExts), remova os pontos do vetor e deve funcionar


How to evaluate series based on recurrence equation

Question: I've come across this problem in an advanced high school worksheet, but I don't know the origin of the problem.
Given the sequence $(x_n)_{\mathbb{N}}$
$$
\left\{
\begin{array}{l}
x_{1}=1 \\
x_{n+1}=\sqrt{x_{n}(x_{n}+1)(x_{n}+2)(x_{n}+3)+1} , n\ge2
\end{array}
\right.
$$
How to evaluate the series
$$
\lim_{n \to \infty} \sum_{k=1}^{n} \frac{1}{x_{k}+2}
$$
Here's what I got:
$$
\begin{align}
\sqrt{x_{n}(x_{n}+1)(x_{n}+2)(x_{n}+3)+1} & = \sqrt{(x_{n}^2+3x_{n}+1)^2} \\
& = |x_{n}^2+3x_{n}+1|
\end{align}
$$
As $x_1=1 > 0 $, $x_{n}^2+3x_{n}+1$ will be positive for all $n \ge 2$ . Thus:
$$
x_{n+1}=x_n^2+3x_{n}+1
$$
This is not good. The relation is neither linear nor homogeneous.
I also have no idea on how to evaluate the series. I can show that it converges comparing it to $\sum \frac{1}{k^2}$, but I can not think on how to evaluate it.
A quick program gives me these values for $x_n$ and for the partial sum $S_n$:
<code>x[1]=1.0000000000
S[1]=0.3333333333
x[2]=5.0000000000
S[2]=0.4761904762
x[3]=41.0000000000
S[3]=0.4994462901
x[4]=1805.0000000000
S[4]=0.4999996936
x[5]=3263441.0000000000
S[5]=0.5000000000
x[6]=10650056950805.0000000000
S[6]=0.5000000000
x[7]=113423713055421845118910464.0000000000
S[7]=0.5000000000
x[8]=12864938683278672079501004830742670366487445279604736.0000000000
S[8]=0.5000000000
x[9]=165506647324519962593059552590935669575232079131271199714697991661245368701786157147328071653890281439232.0000000000
S[9]=0.5000000000
x[10]=27392450308603031764480870527381648752347551731785263407975564098191394906718645585260110781473383370045001182698658109358654445966317201271160135904061763917073783821325868369071377919640132022498004014465024.0000000000
S[10]=0.5000000000
</code>
So if I were to guess, I would say that $\sum \frac{1}{x_{n}+2} = 1/2$
I would appreciate any help finding a general expression for $x_n$ so I can go on to solving the series as usual.
Comment: If you $\color{green}{\checkmark}$, consider also $\color{green}{\uparrow}$. :) Thanks!
Comment: @AlexanderBurstein, I upvoted it, but it won't be displayed until I have a higher rep. :(
Comment: Thanks, no problem!
Answer: After looking at the first few partial sums, it's easy to conjecture that the general form of the $n$th partial sum is
$$
\sum_{k=1}^{n}{\frac{1}{x_k+2}}=\frac{1}{2}-\frac{1}{2}\prod_{k=1}^{n}{\frac{1}{x_k+2}}.
$$
To show that, notice that $x_{n+1}+1=(x_n+1)(x_n+2)$, so
$$
\frac{1}{x_n+2}=\frac{x_n+1}{x_{n+1}+1},
$$
so that
$$
\frac{1}{2}\prod_{k=1}^{n}{\frac{1}{x_k+2}}=\frac{x_1+1}{2(x_{n+1}+1)}=\frac{1}{x_{n+1}+1}.
$$
This makes the inductive step pretty easy:
$$
\sum_{k=1}^{n+1}{\frac{1}{x_k+2}}=\left(\frac{1}{2}-\frac{1}{x_{n+1}+1}\right)+\frac{1}{x_{n+1}+2}=\frac{1}{2}-\frac{1}{(x_{n+1}+1)(x_{n+1}+2)}=\frac{1}{2}-\frac{1}{x_{n+2}+1}.
$$
Update: Also, take a look at the OEIS page for A000058. These are the denominators $x_n+2$.


Finding the normalizer of a group

Question: Compute $N_{S_5}(\{(\begin{smallmatrix}
    1 & 2 & 3
  \end{smallmatrix})\}).$ This is essentially asking for all of the permutations in $S_5$ that commute with $(\begin{smallmatrix}
    1 & 2 & 3
  \end{smallmatrix})$, so far I only know that the identity and itself commute with it. Is there a trick to compute these permutations faster, and not bruteforce it and check all 120 permutations in $S_5$?
Comment: $(123)(45), (132)(45)$
Comment: $(4\, 5)$ will also commute with it. Hence the sub group generated by $\{(1 \,2\, 3), (4\,5)\}$ will be the normalizer.
Comment: @Muralidharan so far I have $\{e, (\begin{smallmatrix}1 & 2 & 3\end{smallmatrix}), (\begin{smallmatrix}1 & 3 & 2\end{smallmatrix}), (\begin{smallmatrix}4 & 5\end{smallmatrix})\}$, would there be any more?
Comment: $N$ usually stands for normaliser (of a subgroup). This is not the same as the centraliser. For example, $(12)$ normalises the subgroup generated by $(123)$, even though it does not commute with $(123)$.
Comment: @verret I know this, but when you're trying to get the normalizer with one element, isn't it basically the same thing as the centralizer? Since the definition of $N_G(S)=\{g\in G|gS=Sg\}$, and when S has one element, it turns into the centralizer?
Answer: Let $H=N_{S_5}(\{(123)\})$. We know that $(123)$ normalizes itself, so $(123)\in H$. On the other hand,$(45)\in H$, because $(123)$ and $(45)$ are disjoint.
Suppose that $\sigma\in H\setminus\left<(123),(45)\right>$ (that is set subtraction, not a quotient). If $\sigma i\in\{4,5\}$ for some $i\in\{1,2,3\}$, then $\sigma(123)\sigma^{-1}$ cannot be equal to $(123)$. This is because conjugation by $\sigma$ would replace $i$ by $j$ in the 3-cycle. Therefore, the set $\{4,5\}$ is stable under $\sigma$. Multiplying $\sigma$ by $(45)$ if necessary, we may assume that $\sigma$ fixes 4 and 5.
So $\sigma$ is a permutation of $1,2,3$. Since we assumed that $\sigma\notin\left<(123)\right>$, we must have that $\sigma$ is a transposition. But $\sigma(123)\sigma^{-1}=(132)$ for all transpositions in $S_3$. This contradiction implies that there is no such $\sigma$ to begin with. In particular, $H=\left<(123),(45)\right>.$

Finding the normalizer of a group


TypeError: Error URL.createObjectURL() not a function

Question: I am trying to create a chrome extension that downloads a file with text inside. Some examples for doing this I've seen need to create a URL to pass to
chrome.downloads.download({ url: url, filename: fileName, conflictAction: 'overwrite', saveAs: false });
However, when I try to use URL.createUrlObject(), I get a type error
var blob = new Blob([textFile], {type: 'application/octet-binary'});
var url = URL.createObjectURL(blob);
I am using manifest v3
Comment: https://crbug.com/1224027
Comment: Use `btoa` instead of `chrome.window.btoa`. Ask a new question for further assistance if necessary.
Comment: createObjectURL is not allowed in a service worker so just use a `data` URL e.g. 'data:text/plain,' + textFile.replace(/#/g, '%23')
Comment: @wOxxOm, i'm new to js and chrome extension development, i'm having the same issue and couldn't figure out how to fix it. tried to create data uri using chrome.window.btoa, which is also throwing error. could you please post the solution here as an answer?
Answer:

    chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === "saveCSV") {
    // for utf8 bom
    const data = '\uFEFF' + request.data;
    const blob = new Blob([data], { type: "text/csv;charset=utf-8" });

    // use BlobReader object to read Blob data
    const reader = new FileReader();
    reader.onload = () => {
      const buffer = reader.result;
      const blobUrl = `data:${blob.type};base64,${btoa(new Uint8Array(buffer).reduce((data, byte) => data + String.fromCharCode(byte), ''))}`;
      chrome.downloads.download({
        url: blobUrl,
        filename: request.filename,
        saveAs: true,
        conflictAction: "uniquify"
      }, () => {
        sendResponse({ success: true });
      });
    };
    reader.readAsArrayBuffer(blob);
    return true;
  }
});

hope this can help someone else.
Answer: a mi me funciono de esta manera:
 const binary = atob(codigoBase64);

        const blob = new Blob([binary], { type: "application/pdf" });

        const dataURL = `data:${blob.type};base64,${btoa(binary)}`;

        chrome.downloads.download({
            url: dataURL,
            filename: `${nombreArchivo}`,
            saveAs: true,
        });

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Why do I get security warning message "This file contains potentially unsafe dynamic content" in this construct

Question: I am finally able to reproduce this message that I get once in a while.
This in on V8.04, on windows 7.
While trying things, I found how to make Mathematica generate the above message when I open a notebook with Manipulate in it.
First the error message screen:

I now hit 'enable dynamics' and all seems well. But each time I reopen the notebook, I get the message again.  (One must close M, and start up again, and then open the notebook to see the message).
So I do not understand this warning message, and why it comes up, and what I need to change in the code to remove it.
The code to generate it is:
Manipulate[

  DynamicModule[{p},
   p["x"] = 0;
   Row[{Dynamic[
      Refresh[p["x"]++; Row[{"p[x]=", p["x"]}],
       TrackedSymbols -> {n}]]}]
   ],

  Button["update counter", n++],
  {{n,0}, None}
  ]

The above is on its own notebook, with nothing else in the notebook.
I close M, then start it, then open the notebook, and I see the above message.
Now, I thought initially that to remove the message, I need to change p["x"] to p[x] so I closed the above notebook, and made a new notebook with this code:
Manipulate[

  DynamicModule[{p},
   p = 0;
   Row[{Dynamic[Refresh[p++; Row[{"p=", p}], TrackedSymbols -> {n}]]}]
   ],

  Button["update counter", n++],
  {{n, 0}, None}
  ]

Then closed M, and started it again, and opened the above notebook,
and now I did not see the warning message. But when I repeated the process, I saw the same error come back.
(I posted this question to the Math group, but that is slow, and my post has not even shown up there, but in that post I said that the error went away when I changed p["x"] to p[x], because it actually did at first, but when I later tried it, the message came back, which I do not understand why)
p["x"] is an indexed object as explained in this page:
http://reference.wolfram.com/mathematica/tutorial/MakingDefinitionsForIndexedObjects.html
The question is: What is in the above code makes this warning to show up? Am I writing something wrong in the above example?
Code runs OK after I enable dynamics. Btw, I am opening this notebook from the same folder I open all my other notebooks, nothing changed and this is on home PC, no networks share folder and nothing out of the ordinary.
Here is the related link to notebook security
http://reference.wolfram.com/mathematica/tutorial/NotebookSecurity.html
I do not see in the above anything related to what I am doing. All what I can say, it has to do with the use of DynamicModule[] inside Manipulate, which is itself a DynamicModule. But I do not understand this well enough to figure why this is a problem.
Update 1
I do not see how this has anything to do with path.  I can remove the error by simply commenting out the inner Dynamic like this:
Manipulate[

 (*
   DynamicModule[{p},
   p["x"]=0;
   Row[{Dynamic[Refresh[p["x"]++;Row[{"p[x]=",p["x"]}],TrackedSymbols-> \
   {n}]]}]
   ],
 *)

 n,
 Button["update counter", n++],
 {{n, 0}, None}
 ]

Save the notebook, close M, start M, open the notebook. Error went away.
So, it is in the code.
Update 2
Trying to reproduce what Yoda reported in his answer, I am not able to.

make new notebook, type Dynamic@DateString[]
ENTER to evaluate.
SAVE
close M
open M
open notebook
no error

Update dec 21, 2001
On the Math Group, John Fultz was kind enough to reply to my post, I do not think he will mind if I post his answer here for the benefit of others to see
> > So, why is using p["x"] causing the security warning message?

That is a bug, which has already been fixed in development sources.
John Fultz
User Interface Group
Wolfram Research, Inc.

Sorry that I do not have a link to include to his reply, I could not find a link on google now. I use thunderbird to read newsgroups.
Should now this question remain open? Or should it be closed? If I need to close it, I can accept one of the answers so it is closed.
Comment: Definitely a trusted path issue. Best solution to ensure you never have this problem is to run some code that David Reiss posted in Mathgroup. Do a search for his name and trusted path and you should find it.
Comment: @NasserM.Abbasi It's Dynamic content that has the potential to be harmful, and as a result this check is run (and the warning) only when you have Dynamic content (i.e., the Notebook tries to automatically run something as soon as you open)
Comment: I don't think it's because of the code. It's most likely because your working directory is not a "trusted" path... I believe "trusted", by default, only includes directories created by mma.
Comment: @yoda, folder I use for the above is my home folder, I use for all other notebooks. Nothing changed. Do you get this error on your end?
Comment: How can it be a trusted issue? I simply remove the inner dynamic, close the notebook, restart everything, and the error message goes away. Same notebook, same folder. I changed only the code. Please see edit
Comment: similar question: [sometimes I get "this file contains potentially unsafe dynamic content" message in Mathematica notebook](http://stackoverflow.com/q/6144049/211232)
Comment: @WReach, thanks for the link, I forgot about that one. But at least this one has a code which generate the error, may be this helps.
Comment: @NasserM.Abbasi You can add John's answer as an answer below and accept it (when you can).
Answer: This is not because of the particular code sample, but rather due to Mathematica's security features. From tutorial/NotebookSecurity,

When the user opens a notebook containing dynamic content, Mathematica
  will first determine whether the notebook's directory is trusted,
  untrusted, or neither.

If the notebook's directory is trusted, the notebook will be allowed to automatically perform dynamic evaluations without alerting
  the user.
If the notebook's directory is untrusted, the user will be alerted upon any attempt by the notebook to perform dynamic evaluations.

By default, only $InstallationDirectory, $BaseDirectory, and $UserBaseDirectory are "trusted". In addition, there are a set of directories that are always untrusted (can be changed). These are your downloads
The solution now, is to add your current working directory to the list of trusted folders.
Go to Preferences > Advanced > Open Options Inspector and under Global Preferences, start searching for trusted and you should see the three options pop up. You can add them here.
Comment: @NasserM.Abbasi The error comes up when there is _any_ `Dynamic` stuff in the output cell. Start a fresh nb and try `Dynamic@DateString[]` and execute. Now save, close and reopen. You should see the warning. Delete the output cell, save, close and reopen. You won't get the warning because the Input cell is inert. Now execute again and delete the input cell, leaving the output intact. Save, close and reopen, you should get the warning again, because now the output cell has a Dynamic in it that tries to run something, which mma doesn't know if it could be harmful or not.
Comment: @NassarM.Abbasi if you have dynamic content in an *output* cell AND your notebook is not in a trusted directory, you will always get this message. That is the upshot as per Yoda's comments. If you do not see that message then the NotebookDirectory[] must be a trusted path.
Comment: Ok but before I do that and break something, what I do not understand is why I have to do this now? I use Manipulate and Dynamics all the time. Manipulate is DynamicModule[].  So why do I have to add my folder path now? I have been using Dynamics and Manipulate all this time with no problem? Never had to do this. Does any one here really add each folder they have a notebook in it which uses Manipulate or any dynamics to the trusted path each time? Thanks.
Comment: @NasserM.Abbasi I don't work with Manipulate and Dynamic all that much, and usually it is only for answering SO questions or trying out others' answers. As such, all these are in notebooks that are eventually killed, so I've never had to face this issue then. I've seen this happen in the few times I've used it legitimately, but I know why it happens and simply Enable it and move on. Never had to see it enough number of times to annoy me...
Comment: so is the key phrase in all of this is "Dynamic content that has the potential to be harmful," ??  So, what is it in my code above that I showed that has the  potential to be harmful? Again, I use Manipulate all the time. So it is NOT just the use of any Dynamics that is the problem, but certain type of use. So the question is, what is it in the above code which can be harmful?
Comment: sorry but that does not help me. Again, I used DyanamicModule before directly, I made a CDF with Dynamics directly, and never seen this message. Manipulate itself is DynamicModule, and I am sure many here did the same. So, there are some Dynamic constructs that make M complain. If we, the users do not know what these are, then how is one to know if what they are writing is safe or not? Try the code, and if the message show up, try something else? Is this the way it is supposed for one to write software? Trial and error?
Comment: I just tried what you said, few times, and I am NOT gettting any error messages. I even closed M, start it, opened the notebook, and no error message. Please see screen shot.  Could you please show a screen shot on your version with the error message? May be I misunderstood something. Thanks
Comment: and what OS, M version you have? may be this makes a difference? Thanks
Comment: I also tried your second case: "Now execute again and delete the input cell, leaving the output intact. Save, close and reopen, you should get the warning again" and again, I get no error/warning messages of any sort. And  I have Evaluation->Dynamic update enabled ON all the time ofcourse.
Comment: @MikeHoneychurch, but it is the SAME folder! My folder can NOT be in the trusted path one second and then next second not be in the trusted path? Which is it? I am using the same folder for everything I do. At first you said I got the error because my notebook was NOT in trusted path. Now you say i am not getting the error because my folder IS in the trusted path?? It is the same NotebookDirectory[] each time. I still do not understand the problem. Thanks
Comment: @NassarM.Abbasi If you try save, close M (not just the file), and then reopen, it should behave like abcd is saying. The trick is to close Mathematica FrontEnd, which will disable the `Evaluation->Dynamic update enabled`. By default this is disabled for every FrontEnd session for untrusted locations. You can enable it for every session either in the menu or clicking on the message that pops up. To avoid doing this every time add your directory to trusted in Option inspector. Adding your path to the trusted list as a string "" is fine. Enabling TrustByDefault might break something one day.
Answer: This is more a continuation of Yoda's answer plus the comments than a separate stand alone answer but as has been stated if you open a notebook from an untrusted directory and you have Dynamic content in an Output cell you will get a security warning. If you evaluate the following code:
CurrentValue[$FrontEnd, {"NotebookSecurityOptions", "TrustedPath"}]

CurrentValue[$FrontEnd, {"NotebookSecurityOptions", "UntrustedPath"}]

NotebookDirectory[]

you will be able to satisfy yourself about whether or not your notebook is in a trusted or untrusted path (notwithstanding the appearance or not of the security warning).
Comment: +1, thanks for the commands, they help. I tried them and the folder I am using is NOT in the trusted path. So the question remain, why I do not get the error message using the example shown by Yoda? (the DateString example) ? I'll show the output of the commands if that helps, but my NotebookDirectoy[] did not show up on the trusted path for sure.
Answer: Assuming you are using the default option settings (i.e. "TrustByDefault"->Automatic) you will see one of three behaviors.

If the notebook is in a directory listed in the "TrustedPath" the content is assumed to be safe and you will never see the warning.
If the notebook is in a directory listed in the "UntrustedPath" the content is assumed to be unsafe and you will always see the warning.
If the notebook is in a directory that is listed in neither the "TrustedPath" nor the "UntrustedPath" you may or may not see the warning depending on the contents of the DynamicBox expression stored in the notebook.  Mathematica will examine the expression before attempting to evaluate it.  If it contains only expressions from a short whitelist of "safe" expressions then you will not see the warning.  If it contains any expressions which are not included in the whitelist of "safe" expressions then you will see the warning.
Comment: I think one of Nasser's questions in the midst of everything else, is "what is the whitelist of safe expressions". Is there such a list? I thought it applied to _all_ expressions in the output cell that had Dynamic. Even a notebook with `Dynamic@1` (evaluated, with the output cell) gives me the warning.
Comment: +1 for the extra info, my folder is on NEITHER the trusted nor the untrusted. I will have to make now some tries, and see if I add the folder explicitly on the untrusted path, if I now get the error from the Yoda example (DateString example). Will update later... may be we getting close to the bottom of this mystery :)
Comment: Worth noting that in CDFs the security warning seems to be more fickle. I had a security "problem" with a CDF and the solution -- provided by Wolfram -- was to eliminate DownValues, i.e. rewrite my function as a pure function.
Comment: @yoda - YOU'RE IN LUCK... I seem to recall coming across such a list during a recent troll through some MMA install files. (digging, digging) You'll need to find a file called MiscExpressions.tr, which on my machine is located at C:\Program Files\Wolfram Research\Mathematica\8.0\SystemFiles\FrontEnd\TextResources. All sorts of frontend resources and goodies are defined in here. Scroll to the end of the file, looking for things like `@@resource DangerousSymbols`, `@@resource SafeContexts`, and `@@resource SafeExpressions`. May have saved other lists like this, but can't find ATM. Of interest?
Answer: I too had a problem with this message coming up on notebooks that I thought it hadn't come up on before, but I am now convinced it is because of Dynamic output existing in the notebook and the fact that Dynamic output runs in the front end. So when you open a notebook with Dynamic output visible the FE will try to run it. If you delete all Dynamic output from a notebook, save it, close it (and even close and reopen Mathematica to be sure) then reopen the notebook the message should not appear since there is no Dynamic output.
I did as yoda suggested, I opened the Option Inspector and edited the TrustedPath in the Global Preferences. I am posting this "answer" as a continuation of yoda's answer since I had to do some playing to figure out exactly how to add a path to TrustedPath.
I added Documents as a trusted path as follows (on Mac OS 10.6) (and I am careful not to save anything there I don't trust):

Click on the little edit button to the left of the Value column for TrustedPath.
Click on Add in the window that opens.
You will be presented with
FrontEnd`FileName[{$RootDirectory},"x"]
Replace x with the path that you want trusted such as:
FrontEnd`FileName[{$RootDirectory}, "/Users/John/Documents/"]

Now I never get the annoying warning for notebooks stored in Documents or any of its subfolders.


Maximising a convex function under convex constrains

Question: I would like to obtain the solution for the following problem (which is like maximizing the variance when the mean is under constraints):
$$\max_{x_i}\sum_{i=1}^n\left(x_i-\frac{\sum_{i=1}^nx_i}{n}\right)^2$$
$$s.t. x_i\geq0,\; i=1\dots n\\\\a\leq \sum_{i=1}^nx_i\leq b,\; a\geq0,\; b\geq0$$
Numerically I can obtain maximum value $\frac{n-1}{n}b^2$ when $\mathbf{x}=[b,0,\dots,0]$, but i am not able to prove that it always holds. So, can this solution hold for all the cases? Can this problem be solved using some standard technique? I really appreciate any help on this issue!
Answer: The maximum of a convex function over a compact convex set is attained at one of the extreme points of the convex set (can you prove this?).
Whenever $a < b$, the extreme points of the polytope $\left\{x \in \mathbb{R}^n_+ \: : \: a \leq \sum_{i=1}^{n} x_i \leq b\right\}$ are $$(a,0,0,\cdots,0), (0,a,0,\cdots,0), \cdots (0,\cdots,0,a)$$ and $$(b,0,0,\cdots,0), (0,b,0,\cdots,0), \cdots (0,\cdots,0,b).$$ It is easy to check that the maximum occurs at any one of the latter set of extreme points.
The case when $a = b$ is simpler.
Comment: Thanks for your answer! For your first statement, is there a theory that states the solution must be one of the extreme points, or I have to prove this case by case? For the determination of extreme points, does (1/2b,1/2b,0,...0) and (b/n,b/n,...,b/n) also considered as extreme points? If so there would be infinite number of extreme points. Thanks for you answer!
Comment: @wondermaster [Here is a proof](https://math.stackexchange.com/questions/2946023/maximum-of-a-convex-function-over-a-polyhedron) for polyhedral feasible regions. To determine extreme points, note that [there have to be $n$ linearly independent active constraints](http://math.sfsu.edu/serkan/math430/lecture4.pdf) at candidate extreme points.
Comment: thanks, i think the answer is sufficient.


Como fazer um sorting em classes?

Question: O engraçado é que isso era uma resposta!
O problema que eu tenho é esse: eu tenho uma classe Person, que se inicializa com uma string, e ela se divide em um número e outra string. Depois da classe ser montada, eu pego um arquivo inteiro e divido ele em várias strings, que vão criar várias variáveis (objetos). Eles devem ser sorteados por número, e mostrar tudo na tela. Eu montei o programa, mas ele não mostra nada! O meu código é:
#include <iostream> //cout - main
#include <string> //string - main ,class and func
#include <algorithm> //reverse, sort, greater - class
#include <vector> //vector - main and func
#include <sstream> //stringstream - main

using namespace std;
class Person
{
    private:
        string name_;
        unsigned num_;
    public:
        Person(string raw)
        {
            this->num_ = stoi(raw);
            reverse(raw.begin(), raw.end()); //Those "reverse" are for getting only the number and the string
            raw = raw.substr(0, raw.find(' '));
            reverse(raw.begin(), raw.end()); //Ends here :P
            this->name_ = raw;
        }
        string name() {return this->name_;}
        unsigned num() {return this->num_;}
};

vector<Person> order_vector(vector<Person>& rawPerson)
{
        //Ok, lets check which one is the first
    vector<Person> ret;
    vector<unsigned> values;
    for(unsigned i = 0; i < rawPerson.size(); i++) values.push_back(rawPerson[i].num());
    sort(values.begin(), values.end(), greater<unsigned>());
    for(unsigned a = 0; a < rawPerson.size(); a++)
    for(unsigned i = 0; i < rawPerson.size(); i++)
    {
        if(a == rawPerson[i].num()) ret.push_back(rawPerson[i]);
    }
    return ret;
}

int main()
{
    string raw_strings;
    vector<Person> rawPerson;
    vector<Person> ordened_Person;
    stringstream rawstring(string("10 tennent\n9 Eccleston\n12 Capaldi\n11 Smith"));
    while(getline(rawstring, raw_strings)) //get info before '\n'
    {
        if(!raw_strings.empty()) //If it is not an '\n'
        {
            rawPerson.push_back(Person(raw_strings)); // add an object
        }
    }
    ordened_Person = order_vector(rawPerson);
    for(auto& a : ordened_Person) std::cout << a.num() << '\t' << a.name() << std::endl;
}

Eu acredito que o erro é na hora de devolver o vetor ordenado, que é o mais provável. O que estou fazendo errado?
Answer: A boa forma de implementar isso é fazer sua classe ser comparável, implementar o operator<. Assim:
bool Person::operator<(const Person& other) {
    return num_ < other.num_;
}

Agora você pode ordenar qualquer contêiner de pessoas usando o std::sort:
std::sort(vecPerson.begin(), vecPerson.end());

Ou ainda:
std::sort(vecPerson.begin(), vecPerson.end(),
          [](const Person& p1, const Person& p2){ return p1.num() < p2.num(); });

Reinventar algo que o standard já faz raramente é boa ideia.
Comment: Estava procurando sobre o sort agora! Obrigado :)

Como fazer um sorting em classes?


Eigenvectors and the Identity matrix

Question: If A has n linearly independent eigenvectors relating to the eigenvalue 1, then A is the identity matrix.
I'm little puzzled with this - any ideas? Is the above statement true?
Comment: The matrix can be diagonalized in the form $A=PIP^{-1}$.
Answer: Hint: you are given that the geometric multiplicity of eigenvalue $1$ is $n\,$. The algebraic multiplicity must then be at least $n\,$, therefore must be exactly $n\,$, so the characteristic polynomial is $(x-1)^n$.
Comment: Thanks for your reply. I completely understood and up voted your answer. :)
Comment: This is the problem with the most of the downvoters. At least mention the reason or ask for any queries before downvoting.
Comment: Could you tell me why algebraic multiplicity is at least $n$?If $A$ is $n\times n$ matrix can't its algebraic multiplicity be less than $n$? Please clarify my doubt? Thank you for the nice answer.
Comment: @mathscrazy The geometric multiplicity of an eigenvalue can never be larger than the algebraic multiplicity, see [Examples for proof of geometric vs. algebraic multiplicity](https://math.stackexchange.com/questions/45742/examples-for-proof-of-geometric-vs-algebraic-multiplicity) for example. Putting that the other way around, the algebraic multiplicity must be at least equal to the geometric multiplicity (or possibly larger). Here, the geometric multiplicity is given to be $n$, so the algebraic one must be $\ge n\,$, and it cannot be $\gt n$ since it's (implied to be) an $n$-by-$n$ matrix.
Comment: Wish the downvoter had left a comment why.
Answer: This means that $Av_i=v_i$ for all $i$, where your basis is $v_1,\ldots,v_n$. As all vectors $u$ are linear combinations of the $v_i$
then $Au=u$ for all $u$.

Eigenvectors and the Identity matrix


How to understand sum of dependent random variables

Question: Suppose that a sequence of $n$ 1's and $m$ 0's is randomly permuted so that each of the $(n + m)!/(n!m!)$ possible arrangements is equally likely. Any consecutive string of 1's is said to constitute a run of 1's—for instance, if n = 6, m = 4, and the ordering is 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, then there are 3 runs of 1's—and we are interested in computing the mean number of such runs.
Let $I_i = 1$ if a run of $1$'s starts at $i$, $0$ otherwise.
Therefore, $R(1)$, the number of runs of 1, can be expressed as
$R(1) = \sum_{i=1}^{n+m} I_i$.
This is a simple question from a textbook. If $I_1=1$, then $I_2=0$. Why can you add up dependent r.v.? I don't understand the last formula.
Comment: Try it on your example.  $I_i=1$ if $i\in\{1,5,9\}$ and $0$ otherwise.
Answer: I think you have a misconception about dependency. There is no problem in adding dependent random variables. For instance, if $X$ is a random variable, you surely agree that $X$ and $X$ are dependent, even though $2X = X + X$ is well-defined.
Dependence between random variables does say the following: If I have information about one variable, it will give me information about the other. Here is an example: Imagine you throw a penny independently 5 times. That will give you five independent random variables $X_1,\dots,X_5$ which are $1$ if you threw head and $0$ otherwise. Now look at $Y = X_1 + X_2$. Then $X_1$ and $Y$ are dependent. Indeed, if $X_1 = 1$, I know that $Y \geq 1$. But still, I can add $X_1$ and $Y$. What does it represent? Imagine the following. You have two friends and you promised to give friend $A$ one dollar if the first throw gives head and to give friend $B$ one dollar for each head in the two first throws. Then $Y + X_1$ is the total money you owe your friends.


How to redirect user after submitting an article?

Question: In Drupal 8 I would like to redirect users to the frontpage and display a status message after submitting an article?
How can I do that? form_alter and custom submit handler?
Answer: Yes, form_alter and a custom submit handler was the solution.
<code>function _custom_admin_form_node_article_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = '_custom_admin_article_form_submit';
    }
  }
}

function _custom_admin_article_form_submit($form, FormStateInterface $form_state) {
  drupal_set_message(t('Thank you for submitting an article.'));

  $url = Url::fromRoute('<front>');
  $form_state->setRedirectUrl($url);
}
</code>
Comment: Note that just adding a drupal_set_message() duplicates the one from core and you have two messages. Getting rid of that requires messing with where they are stored ($_SESSION). Also, you can do $form_state->setRedirect(''), has the same arguments as fromRoute().


Server and client authentication: How can I create a Firebase Auth Token from server and send it to the web client?

Question: I'm trying to authenticate my users using email and password from the server, using firebase and sending the token generated to the client.
In the server-side, I'm using a nodejs firebase function, and the token is created using the firebase rest auth API, using the verifyPassword endpoint, then I use the token generated and send it to the client.
I'm using in the client firebase.auth().signInWithCustomToken(token) to try to sign in, but I get me a invalid token response.
What I'm trying to do is allow to authenticate the user in both sides, the server, and WebClient
.
Is this possible or there is a better way to do it?
Answer: you can send your Client-Side idToken to your server, as described in the Firebase Auth Documentation and on your server you can create a Session-Cookie with firebase admin
admin.auth().createSessionCookie(idToken, {expiresIn})
    .then((sessionCookie) => ...

I have a project where i send the idToken to the server when the Auth-State changes on my Client-Side:
firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        user.getIdToken().then(idToken => {
          sendTokenToServer(idToken,csrfToken);
        });
      } else {
        clearCookiesOnServer(...);
      }
    });

Comment: Thanks, i'm going to change my authentication approach
Comment: @lombardo -- Need a help here. how are u sending token to server with sendTokenToServer() ? and also from where are you getting the idToken and csrfToken.
Comment: I'm using an ajax post to make a request to the server for creating a session cookie. The idToken is returned by getIdToken, then sending as a part of the request; for the csrfToken i am using the csurf package https://github.com/expressjs/csurf


Eclipse Tycho: Compile error when using the java.xml.bind module?

Question: I think the problem is the same as described in this blog post but I get this for Java 10: I have an Eclipse RCP application that uses Java 10 features but also JAXB classes. In Eclipse, I have to add the java.xml.bind module to the build path configuration of my project (as described here) to let the compile errors go away.
However, when building the product with Tycho 1.2.0 I get the following error, exactly for the class that uses JAXB:
[ERROR] Failed to execute goal org.eclipse.tycho:tycho-compiler-plugin:1.2.0:compile (default-compile) on project epd-editor: Compilation failure: Compilation failure:
[ERROR] ...app\src\app\editors\XmlPage.java:
[ERROR] package app.editors;
[ERROR] ^
[ERROR] Internal compiler error: java.lang.NullPointerException at org.eclipse.jdt.internal.compiler.lookup.BinaryModuleBinding.create(BinaryModuleBinding.java:64)
[ERROR] java.lang.NullPointerException
[ERROR] at org.eclipse.jdt.internal.compiler.lookup.BinaryModuleBinding.create(BinaryModuleBinding.java:64)
[ERROR] at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.getModuleFromAnswer(LookupEnvironment.java:427)
[ERROR] at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForTypeFromModules(LookupEnvironment.java:367)
[ERROR] at org.eclipse.jdt.internal.compiler.lookup.LookupEnvironment.askForType(LookupEnvironment.java:228)
[ERROR] at org.eclipse.jdt.internal.compiler.lookup.UnresolvedReferenceBinding.resolve(UnresolvedReferenceBinding.java:105)

Is there a way to configure the Tycho compiler plugin so that it can see modules like java.xml.bind or is there another reason for this error?
Thanks.
Answer: There are three ways you can include modules from the java.se.ee aggregator module, which is not included for compile or runtime in JDK 10. (As of JDK 11, these modules will be removed from the JDK).

The simplest is to use the command line option, --add-modules java.xml.bind.  This will use the version that is still included in the JDK.
Find a JAXB implementation jar.  Maven central is a good place to go for this, there is also a reference implementation for JSR 222 (JAXB), which is part of the Java Web Services Developer Pack (http://www.oracle.com/technetwork/java/webservicespack-jsp-140788.html) but this is waaaay old and may not be the best choice.  You can add where you've downloaded the jar to the upgrade module path using --upgrade-module-path {path}
An alternative to 2 is to simply put the jar containing JAXB on the classpath.

I'm not familiar with Tycho but you would need to figure out how to use one of these methods with its configuration.
Answer: Java EE modules are deprecated for removal and not resolved by default and will be removed in Java 11.
The best way to handle this is to use a third-party dependency, but as you observe JDT trips over its own feet when that is done. I opened an issue and it was fixed some time ago, but it's not easy to find an artifact that contains the change and works on Java 10. The first artifact I know of comes from Eclipse Photon I20180531-0700.
Execute the following in Eclipse's plugins folder (@people from the future: you may have to update the version):
mvn install:install-file \
    -Dfile=org.eclipse.jdt.core_3.14.0.v20180528-0519.jar \
    -DgroupId=org.eclipse.tycho \
    -DartifactId=org.eclipse.jdt.core \
    -Dversion=3.14.0.v20180528-0519 \
    -Dpackaging=jar

You can then use it as follows as dependencies for Maven's compiler plugin:
<dependency>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>tycho-compiler-jdt</artifactId>
    <version>1.1.0</version>
</dependency>
<dependency>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>org.eclipse.jdt.core</artifactId>

    <version>3.14.0.v20180528-0519</version>
</dependency>

The problem is also described on java9.wtf with a demo project on GitHub. (I forgot to push, so it's only online for about five minutes now. )


How to target a input box with selenium when the ID changes?

Question: Trying to automate certain tests dealing with Yammer. What I want to do is to use selenium to post something, but when I click on the textbox it changes it's id. Also, everytime the page reloads, or a post is made, that textbox changes it's id.
So what I did next was to use wildcards by telling selenium to look for
//input[starts-with(id, 'yamjs')]

However, I quickly found out that yamjs is used for both the body of the update as well as the  "+ Add people to notify" textbox.
The difference between the two seems to be the class. The one that we're interested in has a class="yj-tapf-textarea" whereas the add people to notify textbox has a class="yj-callout-bar-entry-field"
How do I get selenium to find the input field with the id that starts with yamjs within the class yj-tapf-textarea, and not the one in the class yj-callout-bar-entry-field?
Comment: does the structure of the page (or the form) stays always the same regardless the ids/class names of the inputs?
Comment: No. It looks like the yj-callout-bar-entry-field only appears after you click on yj-tapf-textarea.
Comment: have you tried something like storing what's in the `class="yj-tapf-textarea"` in a variable and search for the input you want in that variable?
Comment: No. How would I go about doing that?
Comment: in python : `myclass = browser.find_element_by_class('yj-tapf-textarea')`
`myclass.find('input')` this will return a list, you can then iterate over that list until you find the one you want (iterate as a test, delete the iteration when you know which input you need ). Hope i make sense.
Answer: If the id changes then perhaps it is a hint to not use id as the locator.
Using CssSelectors and XPath can give you more stable and reliable locators
Answer: Seems like I wasn't paying close enough attention to the classes and their locations. Here's what I ended up with:
driver.findElement(By.className("yj-auto-width-fake-textarea")).click();
driver.findElement(By.className("yj-tapf-textarea")).sendKeys(Text);
driver.findElement(By.id("yj-yam.ui.publisher.old.SubmitButton")).click();


Adding methods and values to existing java object

Question: I'm trying to add a function that add a unique id to an object in java.
I've a function that returns me an object:
ItemStack is=ent.getKiller().getItemInHand();
I made a java class that extends ItemStack class and i tryied to cast the object to this class.
import org.bukkit.inventory.ItemStack;
import java.util.UUID;
public class UniqueItem extends ItemStack{
    private String uid="";
    public UniqueItem(){
        uid=UUID.randomUUID().toString();
    }
    public String getUniqueID(){
        return uid;
    }
}

UniqueItem is=(UniqueItem)ent.getKiller().getItemInHand();
It produce me an error and i don't undersatand why.
Please help me to solve my problem or give me an alternative solution.
Thanks
Comment: What is the error message?
Comment: `ItemStack` is not a `UniqueItem`, thus you cannot cast it that way around.  But `UniqueItem` is a `ItemStack` and you can cast `UniqueItem` to `ItemStack`
Answer: You get a ClassCastException at runtime because you are trying to cast an item which is not of type UniqueItem
Also, extending the class will not help you. Instead create a wrapper class around ItemStack object which maintains unique ID along with the object.
Try this:
// wrapper class
public class UniqueItem {
    ItemStack item;
    private String uid="";
    public UniqueItem(ItemStack item) {
        this.item = item;
        uid=UUID.randomUUID().toString();
    }

    public String getUniqueID(){
        return uid;
    }
}


Prove that in an obtuse triangle $\angle HAO = \angle B - \angle C$

Question:
Consider the following triangle with orthocentre $H$ and circumcentre $O$. Prove that $\angle HAO = \angle B - \angle C$.
I am familiar with the proof for this when $ABC$ is acute, I wanted to prove it when it is obtuse.
$\angle HAO = \angle HAC + \angle CAO$
Consider $\Delta DAC$, clearly $\angle HAC = 90 - \angle C$.
It remains to prove that $\angle CAO = \angle B - 90$. Or, $\angle AOI = 180 - \angle B = \angle A + \angle C$. This is where I'm stuck.
EDIT: I realized that in quadrilateral $AOB'B$, $\angle AOB' = 180 - \angle B$,  so the proof reduces to proving that $\angle AOB' = \angle AOI$
Answer: I got the answer!
Let $OG$ intersect $BC$ at $L$ (I forgot to name the point).
Let $\angle B = b, \angle EBB' = a$.
$\angle EBB' = \angle OLB' = a \implies \angle LOB' = 90 - a$
Similarly, $\angle AOG = 90 - (b - a)$
$\implies \angle AOB' = \angle AOG + \angle OLB' = 90 - a + 90 - (b - a) = 180 - b$ as desired.
Answer: Alternative solution could be as follows:

Denote $\angle X = \angle OAC$, $\angle Y = \angle BAH$, then $\angle HAO = \angle A + \angle X + \angle Y$.
$\triangle ACD$ is right, so $Y = B-90^\circ$.
$\triangle AOB$ and $\triangle BOC$ are isosceles, so $(A+X) + (C+X) = B$, hence $X = B-90^\circ$.
Finally, $X+Y = 2B-180 = 2B - (A+B+C)$, therefore $$\angle HAO = \angle X+\angle Y+\angle A= \angle B-\angle C.$$

I hope this helps ;-)


Many to many polymorphic table in hibernate

Question: I'm trying to implement a many to many polymorphic association in hibernate.
I have an interface Animal and two implementing classes Cat and Dog. I have another class Food and I'm looking to connect the Animal interface to the food class  through a database many to many relationship. I'm trying to understand how to map it through a polymorphic association like the Ruby on Rails implementation.
The many to many association should look like this:
-------------------------------------------------
|   food_id   |   animal_type   |   animal_id   |
-------------------------------------------------

I've been working on this for a while and I'm not sure how to implement this in hibernate.
Answer: It's not terribly clear what you want your database mapping to model, but usually Hibernate mapping models reality so I'll assume a food is eaten by MANY animals and and animal eats MANY foods.
In this case you'll need a linking table in your database FOOD_ANIMAL which contains food_id and animal_id:
FOOD_ANIMAL:
food_id  int(11), animal_id  int(11)
You'll then need a List<> or Set<> of food's in animal and vice versa. Use @ManyToMany for your mapping. There's a wealth of examples on how to do this, such as:
http://www.mkyong.com/hibernate/hibernate-many-to-many-relationship-example-annotation/
I'm afraid I can't help much more without code examples, but I hope this helps!
Comment: That would be a simple - many to many - table... I'm looking for something a bit more complex... since animal is an interface there is no unique id for an animal, instead the class name and the id of that specific animal type act as a multi-key...
Comment: Your interface shouldn't model the object itself. You use hibernate to map your table (containing a unique ID) of animals with a model in Java using @table, and the standard is for your interface to be used as a data access object for updating your database using hibernate. I'd recommend using the standard pattern for your situation because it's a simple m-to-m relationship.
Comment: The problem with your solution is that if i decide tomorrow to create a Pet interface where i put Cat, Dog and Rock (which is not of the animal interface), they all animals and pets would have to share an id sequence... then later when i decide to add another interface named Thing which i have Rock, Elevator and Motorcycle they will also have to be under the same id sequence since Dog must have the same id sequence as rock and rock must have the same id as motorcycle... and we can add more and more examples to this. The question was specific, How can i create that type of Poly Association...


Remove users stored under "Web Browsing With Google Smarts"

Question: Google (via Chrome) is somehow caching anyone that logged in with a Gmail account and associating it with my Chrome Browser.   Pictures and logins are now displayed in Chrome by going to:
Settings->"Web Browsing with Google Smarts"
There is no obvious way to delete the data displayed here and disable this feature.  Does anyone have any ideas?
I'm using MacOS with Chrome v 68.0.3440.106
Comment: I am using 68.0.3440.106 on win10 and started having it too just now... This is SO annoying
Answer: Update:
Go to: chrome://flags/#account-consistency , which is:
Identity consistency between browser and cookie jar
When enabled, the browser manages signing in and out of Google accounts. – Mac, Windows, Linux, Chrome OS, Android
Disable that.
Comment: Why the downvote?  Once you do the above, you then have to clear your history. Then you'll not be logged in anymore.
Comment: Your answer worked for me.   Not sure who downvoted you, but the data is correct.    Does the browser still cache those accounts somewhere even though it no longer displays them?    It seems like a gaping security hole.    What if someone for instance was using a library computer?    Thanks for the help.
Comment: The new version of Chrome ( 69.0.3497.92) still shows my picture if I am logged into gmail.  So even with this setting, it's still secretly correlating browser activity to users.