Is it a very bad idea to write xor in an article?

Question: In writing a paper or thesis, is it a sign of bad style to use xor in your text as a word having the logical meaning of exclusive or? Or should you always avoid:

.. xor ..

by writing something like:

either .. or ..
Comment: At risk of turning this into an English Language and Usage question, you should *not* say "either ... or ..." for exclusive or. You should say "either ... or ... but not both". When someone says "you're either a fool or a liar" they don't mean you can't *possibly* be both, they mean that they've thought about the two main cases separately.
Comment: The "English" (or your country's language) part of the thesis should (imo) be as easy to read as possible. It should be written using standard, common language. The word "xor" should be avoided.
Comment: In some contexts I prefer "exactly one of the following is true: ..."
Comment: @HagenvonEitzen: and yet the usage example in the the dictionary includes it :-) I'm not a lexicographer, but my impression as a speaker is that saying "either ... or" doesn't always rule out both, it merely indicates that both together aren't really being considered. If I say, "you can either have tea or coffee" then that certainly means you aren't being offered both, but if someone asks "did you get either a tea or a coffee" and I had both and am required to give a yes/no answer then I think I'd say "yes" rather than "no".
Comment: [Iff](https://en.m.wikipedia.org/wiki/If_and_only_if) you write this you might also use "xor". But don't do it for your own convenience. If and where it benefits the reader it might be ok. But better just don't.
Comment: @SteveJessop It seems to me that "either - or" (as opposed to mere "or") makes adding a "but not both" redundant: http://dictionary.cambridge.org/de/worterbuch/englisch/either-or (Also, a foolish liar might accidentally tell the truth, at least in those knights on an island puzzles :) )
Comment: maybe replacing xor by 'cannot be both true or both false'
Comment: Conversely if your customs allowance is "either X litres of spirits or Y litres of wine", clearly they do mean not both, because if you were allowed both they'd say "and". It's just not always so clear-cut.  And they'd mean not both in that context even if they didn't say "either".
Answer: You are writing an article in English. Therefore, sentences should only contain correct English words, and not some combination of terms you would use in formulas and normal English words. Therefore, I would strongly recommend to use

either ... or ...

Also, if you are using XOR, you should write it in all-caps  (Sources: Oxford Dictionary, Merriam-Webster) which makes it less attractive to read it in most sentences.
Comment: @RobinEkman I'm not sure "iff" is really all that prevalent outside of blackboards and scratch paper - which are both contexts in which writing is not meant to stand alone as a means of communication. I don't have a good feel of the overall literature, but lots of the textbooks I've read never use the term, even though "if and only if" shows up all the time.
Comment: I think this answer is mostly on-target, but needs to augmented with @SteveJessop's suggestion to add "but not both." Otherwise, you're not communicating XOR but merely OR. If you don't care about the difference, ignore this suggestion.
Comment: I agree with the gist of this answer, but I note that mathematicians often use natural language in "incorrect" ways. I think that conforming to "correct" English should be more a general guideline than a hard-and-fast rule.
Comment: If you use it in an English sentence, and people understand what you mean, it's a "correct English word". Mathematicians write 'iff' in sentences all the time, why not 'xor'? I am sure if you read CS papers, you will even find 'xor' used as a verb.
Comment: Why not simply write 'exclusively ... or ...', being true to both English and the original thought.
Answer: It also depends on the topic you write thesis upon. Including logical operations like XOR or maybe some tedious mathematical notations in a thesis on biology or medical sciences  might put the targeted audience in a fix at times. Therefore avoiding these terms and replacing them with simple English might make it convenient for wider audience.
Answer: My personal preference is to read English words in complete sentences rather than logical reasoning written out in formula-like style. I always have to translate the latter into the former.
I feel the same way about
$$
\sum_{n=1}^\infty f(n)
$$
which I always rewrite as
$$
f(1) + f(2) + \cdots ,
$$
so I can see how the terms change.
Comment: Are you also surprised by the upvotes for your personal preferences? If not, what's the precise difference? Voting on this answers likely means a form of endorsement or agreement (or the opposite) with the sentiment expressed and the (implied) suggestion to do as outlined in this answer. |I am somewhat indifferent and thus did not vote at all.] Arguably one could also vote in a "thanks for sharing" sense, but it might be more useful to have the votes reflect argreement with the idea rather than an evaluation of the interest of shared opinion.
Comment: The former is better for manipulation, the latter for readability and conceptualization. I think context matters.
Comment: @quid Now that you mention it, maybe the upvotes are odd too. I might upvote someone else's opinion on a question if I thought it might help the OP, even if I disagreed. Of course I've no idea whether that's what the votes on this answer mean. Probably not worth carrying the discussion any further.
Comment: Yes, I agree. I had added in a sentence in this sense while your comment appeared.
Comment: Actually as reader I prefer the sum sign form. It leaves no doubt as what is meant, while the "dots form" can introduce ambiguities.
Comment: I'm surprised by the downvote for my personal preferences.
Comment: I didn't vote either way, fyi.
Comment: @abnry I didn't think you had, and upvoted your comment when I saw it.
Answer: Either you are writing a formula, in which case xor as an operator might be acceptable (but consider \otimes or some such if speaking in a mathematical framework) OR you are writing text, in which case you should use a textual form, which xor is not. The string xor might be used informally to refer to exclusive-or, but not in formal writing.
Both of these cases cannot be true; they are exclusive.
Note particularly that if you are writing a thesis or article, then you have two goals. One is to communicate as clearly as possible. Another goal is to demonstrate that you can write well and use the language well. It isn't necessarily clear that using xor instead of more traditional forms is more or less clear (it will certainly be less clear for some readers), but it is absolutely certain that using a non-standard word like xor will do yourself a serious disservice with at least somebody you want to impress.
Don't kid yourself by pretending that a thesis is entirely about communication of some novel and great idea. It is also about selling your idea as widely as possible and possibly about selling yourself as well. Anybody who decides that you are an illiterate boob who prefers jargon to clear language is much less likely to take your ideas seriously. As you can see from the comments here, there are at least some people who think that using xor is incorrect usage in text. Did you really want to have those people take your ideas less seriously?
Answer: (I don't know why this has a downvote, but I sure you it is correct.)
Yes, it's a very bad idea - but not just because it reads awkwardly. From a strictly logical standpoint, xor is really just the wrong tool. For example, consider the...

Trichotomy Axiom (Plain English). If $x$ and $y$ are real numbers, then precisely one of the following holds. $$x<y, \quad x=y, \quad x>y$$

As it turns out, the following statement, while true, actually fails to correctly formalize the above axiom.

Incorrect Formalization (Symbolic). If $x$ and $y$ are real numbers, then: $$(x<y)+(x=y)+(x>y).$$
(Where $+$ means xor).

The correct formalization is:

Trichotomy Axiom (Symbolic). If $x$ and $y$ are real numbers, then: $$[x<y]+[x=y]+[x>y]=1$$
(Where $[\Box]$ is the Iverson bracket and $+$ means the usual notion of addition on $\mathbb{N}$.)

To see the problem with with incorrect formalization, observe that for all booleans $A$,$B$ and $C$, we have:
$$A+B+C \iff [A]+[B]+[C] \in \{1,3\}$$
This can be checked by looking at 4 cases:

$A,B,C$ all false.
$A,B$ false, $C$ true
$A$ false, $B,C$ true
all true

What this tells us is that the Plain English meaning of the incorrect formalization is:

Incorrect Formalization (Plain English). If $x$ and $y$ are real numbers, then either one or all three of the following are true: $$x<y, \quad x=y, \quad x>y$$

But of course, this doesn't agree with the Trichotomy axiom we started with, which in turn proves that the incorrect symbolic formalization is indeed exactly that - incorrect.


The Mean Value Theorem for Integrals

Question: Suppose that $f \in C[a,b]$. Prove that there exists points $p$ and $q$ in $[a,b]$ such that $$f(p)(b-a) \leq \int_{a}^{b}f \leq f(q)(b-a)$$

Since $f \in C[a,b]$, this implies that $f$ must assume its max and min values by the extreme value theorem.
Further, I can tell that $f(p)$ and $f(q)$ must be the max and min values on the interval, but I don't know how to express this and conclude that there must exist points $p$ and $q$ in the domain. Any help would be greatly appreciated.
Answer: Hint $f(p)=\text{min}_{x\in [a,b]} f(x)$, $f(q)=\text{max}_{x\in [a,b]} f(x)$, let $g(x)=f(p), h(x)=f(q)$, $\int_a^b g\leq\int_a^bf\leq\int_a^bh$. This implies the result.
Answer: In fact, the MVT says that we have equality for a $p$, which then proves the redundant inequalities.

The Mean Value Theorem for Integrals


Using the dense subset property and darboux's definition

Question: first off I would like to say that the solution in the picture is most likely incorrect since I didn't get full marks.
When the question refers to part a.) it's just referring to the darboux's def'n in the prev. question that I did not include in the picture.
Anyway, I need help understanding when I can use a dense subset. I feel like I don't really understand the concept and I'm just using it randomly. I know that my prof said that a dense subset can be used for reasoning when the range alternates from rational to irrational. Can anybody help? Thanks!
I also apologize for the ugly hand writing.
Answer: The issue is that $m_{i}=\ln 1=0$, $M_{i}=\ln\sqrt{3}$ so $L(f,P)=0$, $U(f,P)=\ln\sqrt{3}$.
As @Berci has noted, there is also an issue on the $\sup,\inf$, they are numbers, not sets.
Comment: There's also an issue with the $\sup$ and $\inf$ written. They should be single numbers.
Comment: Oh... ok I see what you mean. I should've written the inf and sup to equal a single number, rather than the set. I also did not substitute my f(x) into the integral. Thank you for the responses!
Answer: It is simple the fact that in every interval of a partition you will find an irrational number and a rational number (density), later you know, the upper sum for a partition P is always the same and not equal to the sup(lower sums)
Comment: Ah, so it doesn't differ much from what I already know. I'm not sure if I understand what you mean with the upper and lower sum. There are times when the inf(upper) and sup(lower) can approach that same value, yes?
Comment: Yeas there are times when they can approach the same vale but not this time. Thabks to density you always find a rational and a irrational number in the intervals of your partition. This mean that the maximun and minimun of f in this intervals are aleays the same and hence the upper and lower sums does not approach each other when we refine the partition, in deed, this sums are always the same! For all partition
Comment: ahhhh, a bit of miscommunication on my side xd, well thanks for letting me know!


Is it bad programming practice to declare an array type in C?

Question: I have a bunch of arrays of various lengths and I'd like to keep the length close to the array, is it bad programming practice to define something like this?
typedef struct Array {
  long len;
  int* buf;
} Array;

Are there any obvious downsides or pitfalls to this?
Comment: On the contrary, keeping related data items together like this is exactly what should be being done.
Comment: Consider recording two numbers — the number of elements allocated, and the number in use.  Clearly, the number in use should never exceed the number allocated, but quite often you'll need to add to an array as you read data, and you don't want to increase the array size by one every time you read a new number.  You should double the number of allocated elements when you need more space.
Comment: No, but you should remember to allocate the memory for the arrays and free when done. You can even consider making functions to allocate and resize the `struct Array`
Comment: A length of type `size_t` will accommodate all array sizes.  `long` may be excessive - or too small.
Comment: There's no problem with that, but that doesn't declare an array type. This declares some array types: `typedef int aint64[64], aint32[32]; ... aint64 foo;`. And yes, some people will hate your guts if you do such a thing ;-)
Comment: What Jonathan said, but also, it is not necessary to *double* the array size each time, just use a fractional factor. And if your array shrinks too, you'd want to use something like `N/(2 * factor)` for the shrinking guide - shrink the array only below this limit when the original array was N items long. That way you will keep amortized constant time insertions and deletiones to the end.
Answer: No, not necessarily. You will need to pass the length of a buffer around with the pointer to make sure that you don't overrun it. It would be a slight performance hit due to the extra dereference, but that can be a worthwhile tradeoff if always having the length available avoids causing bugs. You would need to make sure that the length gets updated if you resize the buffer, and make sure that the buffer gets freed if you free your struct. Other than that, it makes sense to me, and it's what a lot of other higher-level languages do in their array implementations.
Answer: This is fine, a similar structure is commonly used for counted strings, aka vectors, which are not null terminated, hence the need to store their length. I wouldn't bother with this approach if the arrays are only used locally, though.
As it's been noted, it would be better to use an unsigned type such as size_t or uint32_t for the length.
When dealing with pointers one needs to take the usual precautions to ensure that it always has a valid reference before using or passing around, that allocated memory is freed, etc. Using valgrind is highly recommended.


What are Secondary Mediants / Submediants?

Question: I'm learning about secondary dominants and noticed references to secondary mediants and secondary submediants in a resource (Wikipedia). However, I haven't found any other references to them in internet searches. I think I could guess at the function of these types of chords but the lack of information leaves me wondering if they really exist in the lexicon of music theory. I also wonder if there isn't a different and more practical explanation for whatever function secondary mediants and submediants might play. Can anyone offer any clarity here?
Comment: May I ask where you saw these terms?
Comment: Chromatic mediants (in key C, A7>Dm, B7>Em) abound, but this is a mystery!
Comment: "The other secondary functions are the secondary mediant, the secondary submediant, and the secondary subtonic." Quote from Wikipedia, which sadly fails to elaborate. Can't find any other reference to those terms. I am intrigued...
Comment: As Shannon noted, Wikipedia briefly references these concepts but offers no information.
Answer: These chords theoretically exist, but in practice they're pretty rare. Logically, they make sense: secondary submediants function as vi/x, while secondary mediants function as iii/x, x being whatever chord is being tonicized.
Consider one possible example here:

We begin with a clear i–V–i in the key of C minor, and then we move to a V–I in the key of E♭ major. But notice that beat 3 of the first measure also fits into the context of E♭ major; more specifically, that C-minor triad can be understood as vi in the key of E♭. This is one possible use of a "secondary submediant," but most would tend to view that C-minor chord as i of tonic as opposed to vi of E♭. In other words, there's typically an explanation more simple than "secondary submediant."
The other instance where secondary submediants might be a real thing are in what we call extended tonicizations. In short, an extended tonicization is halfway between a tonicization and a full-fledged modulation. Instead of just one or two chords that tonicize a new key, we have several chords, but we still never reach the cadence that's required for a full modulation. During such extended tonicizations, we'll often have chords like ii or vi or iii of the temporary key. In that sense they are "secondary submediants," but typically we just address them as submediants within an extended tonicization.
In short: they exist in theory, but they're pretty rare in practice.
Lastly, note that "secondary submediant" is distinct from "a secondary chord built on the submediant." "Secondary submediant" suggests vi/x, whereas "a secondary chord built on the submediant" ultimately means V/ii. I didn't consider this latter interpretation because it's clear from the Wikipedia link that "vi/x" was intended.
Comment: If you placed a measure between your measures 1 and 2 with the chords Cm Ab Bb (1/2 note) leading into your final Eb, you would be tonicizing Eb for a bit longer, and would make a more plausible secondary submediant on the (new) 2nd measure downbeat.
Comment: @BenI. True enough! But I worried that the example might then run the risk of being in E♭ with only a brief i–V–i in C minor at the beginning.
Comment: Fair enough. It's hard to put enough context for such an odd chord in a tiny example :)
Answer: The chords have other spellings depending on their function... these type of secondary relationships are more common in the later/impressionistic/neoclassical era.
A few examples:
* Secondary mediant ie,  Major: III/IV or III/V  (as opposed to VI or VII, or V/V/V or V/iii)
* Secondary submediant   Major: VI/IV or VI/V (as opposed to II or III, or, V/V or V/vi)
For examples of styles incorporating this expanded notion of mediant motion, see https://www.jstor.org/stable/745872
Answer: Think 'six degrees of separation' ... what chords can't be related to one another?
A fifth is the dominant ... how about a fifth of a fifth? ... just like a family tree they're related, they have to be, but just another level removed.
I'm stating it like this because you're asking 'why' ... well it's because music theory wants to name EVERYTHING and no matter the chord it has some relationship to every other chord.


difference between $('') and $('')

Question:
Possible Duplicate:
$('<element>') vs $('<element />') in jQuery

I am used to write $('
').
But today I saw a presentation about advanced-jquery by john-resig who use the following syntax $('
').
http://loft.bocoup.com/john-resig-advanced-jquery/
To me they seem to produce the same output.
My question is: is there some difference between
$('
') and $('
')?
Comment: @DJDavid98: That's totally different; it selects existing elements.
Comment: I think the first one fails in older IEs.
Comment: Why don't use `$('div')` only?
Answer: No, jQuery will normalize those statements into the exact same.

In some earlier version of jQuery tho, it happend to be that
 was actually faster than
 for whatever reason. I don't know yet, if that still applies.
http://jsperf.com/jquery-constructor-performance
Seems like this bug/feature is no longer true.
Answer:
,
,

, and even

 (Yes, this one will only create one element) all trigger the singleTag regular rexpression which makes jQuery to call document.createElement("div"). It was never passed to any html parser at all.
Here's the regex that you can play with, if it returns true, it will be document.createElement'd
var rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;

Comment: +1, wasn't aware of ``, but it obviously matches as `\/?` makes the self-closing optional.
Answer:
 is an opening tag.
 is a self-closing tag. In this context, however, there is no difference.
Comment: Self-closing tags *do not exist* in HTML.  They're allowed in HTML 5, in order to appease people who just can't let XHTML die, but they don't self close.  You can't say `` in real HTML and have it work like XHTML weenies expect -- the parser ignores the slash, and treats `` just like ``.
Comment: OK, upon rereading [the spec](http://www.whatwg.org/specs/web-apps/current-work/#elements-0), i take it back.  Self-closing tags do semi exist, but only for "foreign elements" (MathML/SVG), and for void elements (which don't have an end tag anyway). It seems `` is actually invalid HTML.

difference between $('') and $('')


Reading dynamic XML nodes in SQL Server

Question: I have the following XML structure:
set @MailXML =
'<MailingCompany>
    <Mailman>
        <Name>Jamie</Name>
            <Age> 24 </Age>
            <Letter>
            <DestinationAddress> 440 Mountain View Parade </DestinationAddress>
            <DestinationCountry> USA </DestinationCountry>
                <OriginCountry> Australia </OriginCountry>
            <OriginAddress> 120 St Kilda Road </OriginAddress>
            </Letter>
    </Mailman>
</MailingCompany>'

My SQL currently looks like this:
-- Mail Insertion
INSERT INTO mailDB.dbo.Mailman
   SELECT
       m.value('Name[1]','varchar(50)') as Name,
       m.value('Age[1]','varchar(50)') as Age
   FROM
       @MailXML.nodes('/MailingCompany/Mailman') as A(m)

SET @MailPersonFK = SCOPE_IDENTITY();

-- Letter Insertion
INSERT INTO mailDB.dbo.Letter
    SELECT
        l.value('DestinationAddress[1]', 'varchar(50)') as DestinationAddress,
        l.value('DestinationCountry[1]', 'varchar(50)') as DestinationCountry,
        l.value('OriginCountry[1]', 'varchar(50)') as OriginCountry,
        l.value('OriginAddress[1]', 'varchar(50)') as OriginAddress
        @MailPersonFK as MailID
    FROM
        @MailXML.nodes('MailingCompany/Mailman/Letter') as B(l)

I am trying to extract the Mailman and Letter data into their own respective tables. I have got that working however my issue is that the MailCompany node is dynamic. Sometimes it may be MailVehicle, for example, and I still need
to read the corresponding Mailman and Letter node data and insert them into their own respective tables.
So both
FROM @MailXML.nodes('/MailingCompany/Mailman') as A(t)

and
FROM @MailXML.nodes('MailingCompany/Mailman/Letter') as B(l)

Will need to be changed to allow MailingCompany to be dynamic.
I have tried to extract the parent node and concatenate it into a string to put into the .nodes function like the following:
set @DynXML = '/' + @parentNodeVar + '/Mailman'

FROM @MailXML.nodes(@DynXML) as A(t)

However I get the following error:

The argument 1 of the XML data type method "nodes" must be a string literal.

How can I overcome this dynamic XML issue?
Thank you very much in advance
Comment: as per my understanding , you trying to say that Mailman and Letter is never changes but parent node of Mailman  may be change . so you have difficulty to get data of Mailman and Letter .means you want to find Mailman  and Letter node dynamically from xml .Am iI Right ?
Answer: Look at this reduced example:
DECLARE @xml1 XML=
N'<MailingCompany>
  <Mailman>
    <Name>Jamie</Name>
    <Letter>
      <DestinationAddress> 440 Mountain View Parade </DestinationAddress>
    </Letter>
  </Mailman>
</MailingCompany>';

DECLARE @xml2 XML=
N'<OtherName>
  <Mailman>
    <Name>Jodie</Name>
    <Letter>
      <DestinationAddress> This is the other address </DestinationAddress>
    </Letter>
  </Mailman>
</OtherName>';

SELECT @xml1.value(N'(*/Mailman/Name)[1]','nvarchar(max)') AS Mailman_Name
      ,@xml1.value(N'(*/Mailman/Letter/DestinationAddress)[1]','nvarchar(max)') AS DestinationAddress
SELECT @xml2.value(N'(*/Mailman/Name)[1]','nvarchar(max)') AS Mailman_Name
      ,@xml2.value(N'(*/Mailman/Letter/DestinationAddress)[1]','nvarchar(max)') AS DestinationAddress

You can replace a node's name with *.
Another trick is the deep search with // (same result as before):
SELECT @xml1.value(N'(//Name)[1]','nvarchar(max)') AS Mailman_Name
      ,@xml1.value(N'(//DestinationAddress)[1]','nvarchar(max)') AS DestinationAddress
SELECT @xml2.value(N'(//Name)[1]','nvarchar(max)') AS Mailman_Name
      ,@xml2.value(N'(//DestinationAddress)[1]','nvarchar(max)') AS DestinationAddress

The general rule: Be as specific as possible.
Comment: Awesome that's exactly what I wanted. Thank you @Shnugo!
Comment: I have the exact same problem but i need to select also the "OtherName"... how can i do this? Thanks @Shnugo

Reading dynamic XML nodes in SQL Server


finding probability distribution of sum of 2 random variables

Question: I have a probabiliy distribution $$p(x) = \begin{cases}e^{-x} & x\geq0\\ 0 & x<0\end{cases}$$ I need to find the probability distribution for $Z=X+Y$ where X and Y are from the above distribution and are independent of each other.
What I did -
$$p(z) = \int_{-\infty}^{+\infty}p(x)p(z-x)dx \\
p(z) = \int_{-\infty}^{+\infty}e^{-x}e^{-(z-x)}dx$$
Since probability distribution is for $x\geq0$ and $z-x\geq0 \implies z\geq x$ which will change our limits to $z \;\; to \;\; \infty$.
$$p(z) = \int_{z}^{\infty}e^{-x}e^{-z}e^{x}dx = \int_{z}^{\infty}e^{-z}dx$$
Now like what should I do, the x term got cancelled in the integral and the integral will go to infinity.
Answer: $x\geq 0\cap x\leq z$ implies that the integral will be taken from $0$ to $z$. So, it'll be
$$\int_0^z e^{-z}dx=ze^{-z},\ \ z\geq 0$$
Comment: Thanks for the help, I saw the inequality in the wrong way. Inequality was meant for $x$, I saw it as for $z$ and then replaced the limits for $x$.


WCF Data Services client not working on WP8 emulator

Question: Just tried an App that works with WP7 emu and VS 2010, called a data Service and worked but tried with WP8 SDK in VS 2012 and it's not working on emu and breaks with "Not Found" error: An exception of type 'System.Data.Services.Client.DataServiceQueryException' occurred in System.Data.Services.Client.DLL but was not handled in user code
Someone have found this too?
Comment: never mind, it's just that because of the network configuration in the new emulator I supose, then localhost is not directing to the local machine, so I used my machine name instead of localhost for the Service url
Answer: Sounds much to me like your problem is the emulator not having any internet connectivity. I'll recommend you remove the emulator from the Hyper-V list, use a Ethernet cable to your computer, and then restart your project.
Comment: In the emulator I can browse websites so I think it has Internet, I have tried to play with the Hyper-V settings of the emulator now that you mention it but had no luck


How to reliably use a matrix (multivariable) response in R using a formula?

Question: I am trying to use a multivariable response in R and came across the damned formulas, and having all sorts of unexpected behaviors, mainly when using them inside functions and packages. This question is twofold

I can input a multivariable response and be able to use the model to predict afterwards?

This MVE, using rpart package, serves as an example. Here y is a two-column matrix (response), and I want to predict y using x, i.e. each column in x (two columns in this MVE). Note that the method itself and what each column in y mean is irrelevant, this is just a MVE to reproduce the problem:
library(rpart)

set.seed(1)
y <- rpois(10, lambda = 1.25)
y <- cbind(c(1,4,10,11,12, 14,16,17,20, 21), y)
print(y)
x <- matrix(1:20, ncol = 2) # just two dummy predictors
print(x)

mymodel <- rpart(y ~ x, method = "poisson", minbucket = 1)

newx <- matrix(11:20, ncol = 2) # just some dummy test predictors, note that we have less rows
predict(mymodel, newdata = data.frame(newx))
# output:
        1          2          3          4          5          6          7          8
 9         10
 0.12500000 0.12500000 0.12500000 0.20000000 0.04761905 0.17948718 0.17948718 0.11538462
 0.04000000 0.04000000
 Warning message:
 'newdata' had 5 rows but variables found have 10 rows

As you can see, I can't predict a new dataset. I have been messing with the column and row names and have not been able to make it work.
In addition,

How can I make a wrapper that is "safe"?

For example, in this MVE:
mywrapper <- function(y, x){
  mymodel <- rpart(y ~ x, method = "poisson", minbucket = 1)

  return(mymodel)
}

and provided the help provided in the R documentation:

A formula object has an associated environment, and this environment (rather than the parent environment) is used by model.frame to evaluate variables that are not found in the supplied data argument.
Formulas created with the ~ operator use the environment in which they were created. Formulas created with as.formula will use the env argument for their environment.

I don't really understand what this is supposed to mean. As far as I understand it, not inputing nor y or x to mywrapper() will result in an error (this is the expected behavior). I ask because I am dealing with r packages and functions inside packages and I want to make sure that there is no unexpected behavior with the formulas.
Answer: Generally speaking formulas in R work well with dataframes.  rpart works on matrices, and while dataframes can hold matrices, they tend to get converted to separate columns.  To avoid this, wrap the matrix in I():
# Same as your code to start...then this:

predict(mymodel, newdata = data.frame(x = I(newx)))
#>    1    2    3    4    5
#> 0.04 0.04 0.04 0.04 0.04

In the second part of your question, you are creating a formula in the mywrapper function, so that's where it will look for variables if they aren't contained in the newdata dataframe.  "Environments" in R are similar to "stack frames" in other languages; the main difference is that environments have a single parent and searches proceed there if the object isn't found in the original.
Generally speaking the parent is not the frame of the caller, it is the frame where the environment was created, or something specially listed as the parent.
So what happens if you run predict on the returned value from mywrapper is that it looks at the formula to find what variables it needs.  Only the variables on the right hand side are needed for predictions, so that's just x.  If you supply x in your newdata argument to predict, everything will be fine and proceed as before, but if you don't, things are different.
Since x was not found in the newdata, it goes to the environment of the formula.  That's the evaluation frame of mywrapper, and it will see x there, since it was an argument to that function.
If it was looking for z instead, it wouldn't find it there.  The next place to look is the parent environment, which is the one in effect when mywrapper was created, i.e. the global environment.  If there's no z there, it would search through the chain of environments listed by search(), which are typically package exports.  The search() list is chained together so that each entry is the parent of the one before.
I hope this isn't too much information....
Comment: That worked! and definitely not too much information, it's very much appreciated. I'm still worried about those "Generally speaking", though
Comment: The exceptions to formulas working well in dataframes are usually programmer error.  Since package authors aren't always experts, sometimes they get it wrong.  The authors of rpart know what they're doing, so that's not a problem here.  The exceptions to "parent != caller" are usually cases where the parent is explicitly set to be the caller, but it also happens with nested functions:  f creates g locally then calls it.
Answer: I have not worked with rpart:predict, but for this function you need a new dataset that has the same variables as the original one, according to the documentation.
So, you should initiate newx with the correct column names:
newx = matrix(11:20, ncol = 2,dimnames=list(NULL,c("x1","x2")))

Now, the columns are labeled x1 and x2, just as the variables in your model and predict will know what to do with these columns.
Comment: How do you input this to `predict()`? Using `data.frame(newx)` does not work.
Comment: Using  ` newx <- matrix(11:20, ncol = 2, dimnames = list(NULL, c("x","y")))` and then
`predict(mymodel, newdata = as.data.frame(newx))` throws the error *Error: variable 'x' was fitted with type "nmatrix.2" but type "numeric" was supplied*. Using `newx <- matrix(11:20, ncol = 2, dimnames = list(NULL, c("x1","x2")))` gives the same error as before.
Comment: Ah, right. You train the model to predict a matrix given another matrix. You can't put that in a data frame. As said above, I don't use the rpart library, myself. I don't know how to predict in this case.


How to design a database where the main entity table has 25+ columns but a single entity's columns gets <20% filled on average?

Question: The entities to be stored have 25+ properties (table columns). The entities are pretty diverse, meaning that, most of the columns are empty. On average, I'd say, less than 20% (<5) properties have a value in any particular item. So, I have a lot of redundant empty columns for most of the table rows. Almost all of the columns are decimal numbers.
Given this scenario, would you suggest serializing the columns instead, or perhaps, create another table named "Property", which would contain all the possible properties and then creating yet another table "EntityProperty" which would map an property to an entity using foreign keys? Or would you leave it as it is?
An example scenario where this kind of redundancy might occur could be the following:
We have an imaginary universe with lots of planets. We are creating a space mining game and each planet has 30 different mineral contents. Most of the planets have only 2-3 minerals.
The simplest solution would be to create a single table 'Planets' with 30 columns, one for each mineral. The problem here is that most of rows in the 'Planets' table have 25+ columns, in which each of one the value is null or zero. Thus we have lot of redundant data. Say, we would have 500k-1M records. I would guess it costs a byte at most to save a null or zero decimal value. Thus, we waste space 500,000-1,000,000 bytes, ie. one megabyte at most.
The other solution would be to create two additional tables. Instead of storing all the minerals in the 'Planets' table, we take them all out and create a table for the minerals called 'Minerals'. This would contain only 30 rows, one for each different mineral type. Then, we create a table called 'PlanetMineral' which contains a reference to a planet row  and to a mineral row, and additionally this table would have a column telling the amount of the mineral the planet has. Apparently, in many database systems this complicates queries since you have to do possible several joins. I'm using SQL server with LINQ to SQL, which scaffolds the foreign key constraint into class object property, accessible through code. (ie. I can simply access the minerals a planet has with planet.Minerals) So, from this perspective it doesn't add complexity. The redundancy is a small portion (like 1/15) of the first solution. The reason there is still some overhead is because of the foreign keys we need to store.
As for the data query efficiency, I really don't know how the costs of the queries would compare between these two solutions.
Answer: For numbers, I would personally leave it as is, in 1 table. Numbers are compressed into a few bytes, and the overhead for having an EntityProperty table would far outweight that. Serializing is an option, but it means you cannot use SQL to search or compute the properties, you have to get the data, deserialise, and then compute.
Answer: It depends:

How many entities (rows) you are planning to have?
What kind of queries you run against that table?
Will there be a lot of new properties in future?
How are you planning to use the properties?

You seem to be concerned about wasting space with simple table? Try to calculate if space saving with other approaches are really significant and worthwhile. The disk is (usually) cheap.
If you have low number of rows, then the single table is probably better (it is easier to implement).
If you plan to create complex queries against the properties (eg. where property1 < 123) then the simple table is probably easier.
If you are planing to add lot of new properties in the future then the Property/EntityProperties approach could be useful.

I'd go with the simple one table approach because you have a rather small amount of rows (<1M), you are probably running your database with server machines and not some handheld/mobile thing (SQLServer) and your database schema is rather rigid.
Comment: Terve! 500k-1M rows. Most of the queries deal with retrieving all or part of the rows with all relevant information (for displaying a list of the entities on a website with paging). There shouldn't be a lot of new properties in the future since we hopefully have documented the needed columns. The data of the properties themselves would change very little, if at all, so most (>99%) of the queries deal with retrieval from a dataset. It would seem the single table approach is more suitable.


Creating a really public Windows network share

Question: I want to create a shared folder under Windows (actually, Windows XP, Vista, and Win 7) which can be mounted from a linux system without prompting for a username/password. But before attempting this, I first wanted to establish that this works between two Windows 7 machines.
So, on machine A (The server that will hold the public share), I created a folder and set its permissions such that Everyone has read/write access. Then I visited Control Panel -> Network and Sharing Center -> Advanced Sharing Settings and then selected "Turn off password protected sharing". Then, on machine B (The client that wants to access the public share with no username/password prompt), I tried to "map network driver" and I was immediately prompted by a password prompt.
Some search on google suggested changing "Acconts: Limit local account use of blank passwords to console logon only" to "Disabled". Tried that, no luck, still getting username/password prompt.
If I enter the username/password, I am not prompted for it again and can use the share as long as the session is active. But still, I really need to access the share without any username/password transaction whatsoever and this is not just a convenience related thing. Here is the actual reason: The device that will access this windows network share is an embedded system running uclinux. It will mount this share locally and then play media files. Its only user interface is a javascript based web page. So, if there is going to be any username/password transaction, I would have to ask the user to enter them over the web page, which will be ridiculously insecure and completely exposed to packet sniffing.
After hours of doing experiments, I have found one way to make this happen, but I am not really very fond of it... I first create a new user (shareuser) and give it a password (sharepass). Then I open Group Policy Editor and set "Deny log on locally" to "A\shareuser". Then, I create a folder on A and share it so that shareuser has Read access to it. This way, shareuser cannot login to A, but can access the shared folder. And, if someone discovers the shareuser/sharepass through network sniffing, they can just access the shared folder, but can't logon to A.
The same thing can be achieved by enabling the Guest user and then going to Group Policy Editor and deleting the "Guest" from the "Deny access to this computer from the network" setting. Again, Guest can mount the public share, but logging in to A as Guest won't be possible, because Guest is already not allowed to log in by default.
So my question would be, how can I create a network share that is truly public, so that it can be mounted from a linux machine without requiring a password? Sorry for the long question, but I wanted to explain the reason for really needing this...
Comment: Just for completeness, I considered using the Windows 7 Homegroup thing. But this seems to be strictly Windows 7 related and won't work with Vista and XP. I need to be able to mount shares on Win7, Vista, and XP
Comment: I also tried enabling the "Public Music" folders, but still, wasn't able to avoid the username/password prompts.
Comment: I think you're on the right track with the "Guest" account. That's the classic user account associated with anon access to a SMB share.
Comment: Thanks for the answer, Chris. the problem with that approach is the difficulty of explaining that to a customer. The Group Policy Editor is quite intimidating
Comment: We won't have this problem with users that store their music collection on a NAS. This is because almost all NAS's are running samba, which does support truly public shared folders. Also, when we add support for UPNP and DLNA, this will become less of a problem.
Answer: As far as I can tell, Microsoft considers anon access of any kind to be a security risk, possible only for legacy support. For good reason, really. That's why it's such a pain to enable it.
You already have a process to make it work by modifying system policy entries, so what you need is a way to do that programmatically.
Since the group policy options are just registry entries, find out which ones correspond to enabling the guest account for remote access and modify them during an elevated installation process. The mapping between policy options and registry entries are kept in the .admx files in your C:\Windows\PolicyDefinitions directory.
It's not the prettiest solution and an open share would compromise security but it should work.


Call do_shortcode functionality in functions.php with AJAX

Question: I'm trying to implement do_shortcode functionality for Profile Builder plugin to load the registration form when it's called from the login form. Since the form will be displayed in the same modal window that requires that the registration form needs to be loaded by AJAX.
In functions.php there is a function to load shortcode content:
add_action( 'wp_ajax_nopriv_do_shortcode', 'do_shortcode' );
add_action( 'wp_ajax_do_shortcode', 'do_shortcode' );
function do_shortcode( ) {
    $shortcode = $_REQUEST['shortcode_name'];
    ob_start();
    echo do_shortcode( $shortcode );
    ob_get_contents();
    $modal = ob_get_clean();

    echo $modal;
    die();
}

And in modal window template I've have:
function load() {
        jQuery.ajax({
            method: 'POST',
            url: '/wp-admin/admin-ajax.php',
            data: {
                action: 'do_shortcode',
                shortcode_name: 'wppb-register'
            },
            success: function(data)
            {
                jQuery("#my-modal").replaceWith(data);
            }
        });
    }

In result I'm receiving only the 'wppb_register' text. How could I get the registration form that is content for this shortcode?
Answer: Do_shortcode is not working in ajax callback.
so I think that we have to use new solution.
add_action( 'init', 'do_shortcode_callback');
function do_shortcode_callback() {
    if (isset($_REQUEST["action"]) && $_REQUEST["action"] == "do_shortcode") {
        $shortcode = $_REQUEST['shortcode_name'];

        echo do_shortcode( $shortcode );
        exit;
    }
}

function load() {
    jQuery.ajax({
        method: 'POST',
        url: '<?php echo site_url('/'); ?>',
        data: {
            action: 'do_shortcode',
            shortcode_name: '[wppb-register]'
        },
        success: function(data)
        {
            jQuery("#my-modal").replaceWith(data);
        }
    });
}

Comment: if you need my help, let me know. Thanks.


What is the probability of n people from a list of m people being in a random selection of x people from a list of y people?

Question: If I am selecting 232 people from a pool of 363 people without replacement what is the probability of 2 of a list of 12 specific people being in that selection?
This is a random draw for an ultra race where there were 363 entrants for 232 spots. There is an argument about whether the selection was biased against a certain group of 12 people.
My initial attempt at calculating this was that there was 232 choose 363 possible selections. The number of combinations of any one person from the list of twelve is 1 choose 12 + 2 choose 12 + ... + 11 choose 12 + 12 choose 12.
Thus 1 choose 12 + 2 choose 12 .... / 232 choose 363.
Which ends up being a very low number which is clearly too low.
How do I calculate this?
Comment: Two technical points. First, you're now dealing with a likelihood rather than a probability as the outcome is known. Second, it doesn't matter what the theoretical likelihood is, given that you have a result. I think it would be better to approach the method used for selection: how were the selections chosen? You need to prove the correctness of the method, not the correctness of the result.
Comment: One would view this as a likelihood, Michelle, for the purpose of estimating selection probabilities.  That does not appear to be the case here.
Comment: You need to be careful in using the simple calculation of the hypergeometric RV, as the 12 people who are complaining are not randomly selected. They are complaining because they were *not* selected.
Answer: I interpret the question like this: suppose the sampling was purportedly carried out as if $363$ tickets of white paper were put in a jar, each labeled with the name of one person, and $232$ were taken out randomly after thoroughly stirring the jar's contents.  Beforehand, $12$ of the tickets were colored red.  What is the chance that exactly two of the selected tickets are red?  What is the chance that at most two of the tickets are red?
An exact formula can be obtained, but we don't need to do that much theoretical work.  Instead, we just track the chances as the tickets are pulled from the jar.  At the time $m$ of them have been withdrawn, let the chance that exactly $i$ red tickets have been seen be written $p(i,m)$.  To get started, note that $p(i,0)=0$ if $i\gt 0$ (you can't have any red tickets before you get started) and $p(0,0)=1$ (it's certain you have no red tickets at the outset).  Now, on the most recent draw, either the ticket was red or it wasn't.  In the first case, we previously had a chance $p(i-1,m-1)$ of seeing exactly $i-1$ red tickets.  We then happened then to pull a red one from the remaining $363 - m + 1$ tickets, making it exactly $i$ red tickets so far.  Because we assume all tickets have equal chances at every stage, our chance of drawing a red in this fashion was therefore $(12-i+1) / (363 - m + 1)$.  In the other case, we had a chance $p(i,m-1)$ of obtaining exactly $i$ red tickets in the previous $m-1$ draws, and the chance of not adding another red ticket to the sample on the next draw was $(363 - m + 1 - 12 + i) / (363 - m + 1)$.  Whence, using basic axioms of probability (to wit, chances of two mutually exclusive cases add and conditional chances multiply),
$$p(i,m) = \frac{p(i-1,m-1) (12-i+1) + p(i,m-1) (363 - m + 1 - 12 + i)}{363 - m + 1}.$$
We repeat this calculation recursively, laying out a triangular array of the values of $p(i,m)$ for $0\le i\le 12$ and $0 \le m \le 232$.  After a little calculation we obtain $p(2,232) \approx 0.000849884$ and $p(0,232)+p(1,232)+p(2,232)\approx 0.000934314$, answering both versions of the question.  These are small numbers: no matter how you look at it, they are pretty rare events (rarer than one in a thousand).
As a double-check, I performed this exercise with a computer 1,000,000 times.  In 932 = 0.000932 of these experiments, 2 or fewer red tickets were observed.  This is extremely close to the calculated result, because the sampling fluctuation in the expected value of 934.3 is about 30 (up or down).  Here is how the simulation is done in R:
<code>> population <- c(rep(1,12), rep(0, 363-12)) # 1 is a "red" indicator
> results <- replicate(10^6,
             sum(sample(population, 232)))   # Count the reds in 10^6 trials
> sum(results <= 2)                          # How many trials had 2 or fewer reds?
[1] 948
</code>
This time, because the experiments are random, the results changed a little: two or fewer red tickets were observed in 948 of the million trials.  That still is consistent with the theoretical result.)
The conclusion is that it's highly unlikely that two or fewer of the 232 tickets will be red.  If you indeed have a sample of 232 of 363 people, this result is a strong indication that the tickets-in-a-jar model is not a correct description of how the sample was obtained.  Alternative explanations include (a) the red tickets were made more difficult to take from the jar (a "bias" against them) as well as (b) the tickets were colored after the sample was observed (post-hoc data snooping, which does not indicate any bias).
An example of explanation (b) in action would be a jury pool for a notorious murder trial.  Suppose it included 363 people.  Out of that pool, the court interviewed 232 of them.  An ambitious newspaper reporter meticulously reviews the vitae of everyone in the pool and notices that 12 of the 363 were goldfish fanciers, but only two of them had been interviewed.  Is the court biased against goldfish fanciers?  Probably not.
Comment: Goodness - that wasn't actually the result I expected. Thank you for your thorough work and good explanation. (Curiously, I actually did some stats training at the University of Auckland where R was first developed)
Comment: **NB** In the simulation, it does not matter that it is the very first 12 "tickets" that are marked, because all sampling is performed randomly without replacement (via `sample`).  In effect, at each iteration `sample` thoroughly mixes the tickets each time it is called before it withdraws 232 of them.
Answer: @whuber gave an exhaustive explanation, I just want to point out that there is a standard statistical distribution corresponding to this scenario: the hypergeometric distribution. So you can obtain any such probabilities directly in, say, R:
Probability of exactly 2 out of 12 selected:
<code>   > dhyper(2, 12, 363-12, 232)
   [1] 0.0008498838
</code>
Probability of 2 or fewer out of 12 selected:
<code>   > phyper(2, 12, 363-12, 232)
   [1] 0.000934314
</code>
Comment: +1 Thanks.  I should have mentioned this connection.  The hypergeometric distribution classically appears in sampling-resampling experiments.  The 12 specific people (my "red tickets") are like fish that have been caught, marked, and thrown back into the pool; the sample of 232 is like the set of fish that are subsequently caught.  The hypergeometric distribution describes the frequencies of recaptured fish.
Answer: The odds are much higher than calculated with the simple hypergeometric distribution, as the group is not chosen randomly ("12 fish are painted red before the draw").
From the description of the question, we are testing for a fraud in the draw. A specific group of 12 people complained that only 2 of them were selected, while the expected number was 232/363~2/3=8.
What we really need to calculated is what are the odds that "No group of size 12 will have only 2 member selected". The odds that at least one group will have 2 or fewer (therefore will complain against the fairness of the draw) are much higher.
When I run this simulation, and check in how many of the trials none of the 30 (=360/12) groups had 2 or fewer selections, I get about 2.3% of the times. 1:42 is low but not impossible.
You should still check the procedure of the draw as it might be biased against a specific group of people. They might have come together and received a range of the draw with less probability (the first or last numbers, for example), or whatever dependent variable on the procedure of the draw. But if you don't find any flaw in the procedure, you can return to the 1:42 odds that it is simply bad luck for the group.
Comment: A good point, BUT (a) surely not every possible group of 12 has enough similarity to matter, and (b) not all groups that have enough similarity to matter have exactly 12 members.
Comment: @zbicyclist, I don't claim that the calculation is accurate. I wanted to give a **reasonable doubt** (as we are in the realm of the law with fraud detection), that the draw is not guilty.


I want to call the entire alphabet multiple letters deep on a site, is that easy to do

Question: I want to call the entire alphabet multiple letters deep on an effort to pre cache a site before launch.
EX:
example.com/search?id=a

example.com/search?id=z

example.com/search?id=aa

example.com/search?id=zz

example.com/search?id=aaa

example.com/search?id=zzz

Is there an efficient way to wget/etc in that manner that from the command line/shell?
Comment: Are you trying to use the command line by itself or are you writing a program to do this? If you don't have access to for loops such as in a programming language, it would be very tedious.
Comment: Look at combining `wget` with `jot`.
Comment: Got it: Used php's file_get_contents() in conjunction with a loop that took advantage of php not being statically typed.
Answer: With curl:
curl -# 'example.com/search?id=[a-z]' > /dev/null
curl -# 'example.com/search?id=[a-z][a-z]' > /dev/null
curl -# 'example.com/search?id=[a-z][a-z][a-z]' > /dev/null

With wget (and bash):
wget -O/dev/null 'example.com/search?id='{{a..z},{a..z}{a..z},{a..z}{a..z}{a..z}}

Not sure it's efficient, though, but it might get you going a little bit.


How to split a video using FFMPEG so that each chunk starts with a key frame?

Question: We need to split a large live WMV video feed in small chunks all of the same size. We made a script that works fine doing this, except for one thing: the video chunks don't start with a key frame, so when playing most video chunks they don't display any image until a key frame from the original video is eventually reached.
Isn't there a way to tell ffmpeg to make the output video to start with a key frame?
Here is how our command lines look right now:
ffmpeg.exe -i "C:\test.wmv" -ss 00:00:00 -t 00:00:05 -acodec copy -vcodec copy -async 1 -y  "0000.wmv"
ffmpeg.exe -i "C:\test.wmv" -ss 00:00:05 -t 00:00:05 -acodec copy -vcodec copy -async 1 -y  "0001.wmv"

and so on...
Comment: Are you using a recent ffmpeg build?
Comment: Yes the latest: ffmpeg version N-47062-g26c531c. We also tried using -force_key_frames:v 00:00:00, or -force_key_frames:v 00:00:05, but it does not make a difference in the ouput. I believe using -vcodec copy actually means it is just copying groups of pictures in the new file, but won't do any kind of reencoding to add key frames. Is it the case?
Comment: Is there a way for me to split my file into chunks so every chunk starts with a key frame? they don't have to be all the same duration. But they must be perfectly contiguous. If I specify -ss on the input file, it cuts at the key frame but then I see my videos overlap by re-including the same GOP in 2 consecutive chunks.
Comment: `-vcodec copy` does not re-encode: it only performs demuxing and muxing.
Answer: The latest builds of FFMPEG include a new option "segment" which does exactly what I think you need.
ffmpeg -i INPUT.mp4 -acodec copy -f segment -vcodec copy \
    -reset_timestamps 1 -map 0 OUTPUT%d.mp4

This produces a series of numbered output files which are split into segments based on Key Frames. In my own testing, it's worked well, although I haven't used it on anything longer than a few minutes and only in MP4 format.
Comment: Seems like the examples have moved here: https://www.ffmpeg.org/ffmpeg-formats.html#Examples-9
Comment: @jox seems like they have moved again, to: https://www.ffmpeg.org/ffmpeg-formats.html#segment_002c-stream_005fsegment_002c-ssegment
Comment: @TheAudiophile you're right, thanks. The following link goes directly to the examples: https://www.ffmpeg.org/ffmpeg-formats.html#Examples-10
Answer: As stated on the official FFMPEG Docs, it has worked better for me to specify -ss timestart before -i input_file.ext, because it sets (or so I understand) the beginning of the generated video to the nearest keyframe found before your specified timestamp.
Change your example to:
ffmpeg.exe -ss 00:00:00 -i "C:\test.wmv" -t 00:00:05 -acodec copy \
    -vcodec copy -async 1 -y  "0000.wmv"

I have tested this method working on .flv and .mp4 files.
Comment: I think it's not correct. If you scroll down at the Seeking page, it says specifically for `codec copy` that:

`Using -ss as input option together with -c:v copy might not be accurate since ffmpeg is forced to only use/split on i-frames. Though it will—if possible—adjust the start time of the stream to a negative value to compensate for that. Basically, if you specify "second 157" and there is no key frame until second 159, it will include two seconds of audio (with no video) at the start, then will start from the first key frame. So be careful when splitting and doing codec copy.`
Comment: Though this kinda messes up the duration of the video, e.g. the video i got was displayed as 8 seconds long even though i specified that the video lasts for 5 seconds. The video indeed does end at 5 seconds, but in all media players it's shown as if its 8 seconds long. Any ideas?
Comment: @Ondra: okay but how does one prevent this, to generate a video that plays correctly from start to finish?
Comment: @OndraŽižka It is good to be mindful of this. When cutting out a large portion of the beginning of a video, it's helpful to do it in two passes: one with `-ss` before the input, to inaccurately skip to just before where you want to start, and save that output as a temp file; and a second pass with `-ss` after the input, using the temp file as input, with `-ss` set more precisely. This allows you to figure out the precise value of `-ss` without repeatedly seeking to the desired cutoff point using the needlessly slow-but-accurate method.
Comment: @BallpointBen - right. @MRule - see the above comment. It is tedious but correct. I hope `ffmpeg` will automate this way.
Comment: This works pretty well! Just it does guarantee a 1 second frozen frame at the beginning, but the duration is fine for me for a 30fps video.
Answer: Here is the solution that I could get to work:
As suggested by av501 and d33pika, I used ffprobe to find where the key frames are. Because ffprobe is very verbose and can take several seconds or even minutes to output all key frames and there is no way to scope the range of frames we want from a lengthy video, I proceed into 5 steps:

Export a video chunk from the original file, around the double of the desired chunk size.
ffmpeg -i source.wmv -ss 00:00:00 -t 00:00:06 -acodec copy -vcodec copy -async 1 -y  0001.wmv

Use ffprobe to find where the keyframes are. Choose closest keyframe after desired chunk size.
ffprobe -show_frames -select_streams v -print_format json=c=1 0001.wmv

From the output of ffprobe get the pkt_dts_time of the frame just before that key frame.
ffmpeg on the exported chunk of step 1, specifying the same input and output file, and specifying -ss 00:00:00 and -t [value found in step 3].
ffmpeg -i 0001.wmv -ss 00:00:00 -t 00:00:03.1350000 -acodec copy -vcodec copy -async 1 -y 0001.wmv

Restart at step 1, using -ss [cumulated sum of values found in step 3 over iterations].

Proceeding this way, I was able to have an efficient and robust way to split the video at key frames.
Comment: I was able to do the same with your help, however, the initial dts/pts was shifted a little bit (500ms here). The documentation indicate that if -ss is passed BEFORE -i, then it act as a seek, and in my case, it fixed the shift. Read the man ffmpeg on the -ss section :)
Comment: Why do you use the frame before the keyframe instead of the keyframe itself? Re: _"From the output of ffprobe get the pkt_dts_time of the frame just before that key frame."_
Comment: If you don't cut just before the key frame, that key frame will be included as the last frame of the chunk, and the next chunk will not start with a key frame.
Comment: The statement "there is no way to scope the range of frames we want from a lengthy video" for ffprobe is not true, or at least not any longer. Adding the option -read_intervals 18.6%+4.2 for example starts reading at second 18.6 and continues for 4.2 seconds.
Answer: Using a newer build of ffmpeg, can achieve this by using ffprobe and the ffmpeg segment muxer.

Use ffprobe and awk to identify the keyframes as close as possible
to your desired chunk length.

ffprobe -show_frames -select_streams v:0 \
        -print_format csv [SOURCE_VIDEO] 2>&1 |
grep -n frame,video,1 |
awk 'BEGIN { FS="," } { print $1 " " $5 }' |
sed 's/:frame//g' |
awk 'BEGIN { previous=0; frameIdx=0; size=0; }
{
  split($2,time,".");
  current=time[1];
  if (current-previous >= [DURATION_IN_SECONDS]){
    a[frameIdx]=$1; frameIdx++; size++; previous=current;
  }
}
END {
  str=a[0];
  for(i=1;i<size;i++) { str = str "," a[i]; } print str;
}'

Where

[SOURCE_VIDEO] = path to video you want to segment
[DURATION_IN_SECONDS] = desired segment length in seconds

The output is comma-delimited string of keyframes.

Use the keyframes output above as input to ffmpeg.

ffmpeg -i [SOURCE_VIDEO] -codec copy -map 0 -f segment \
       -segment_frames [OUTPUT_OF_STEP_1] [SEGMENT_PREFIX] \
       _%03d.[SOURCE_VIDEO_EXTENSION]

Where

[SOURCE_VIDEO] = path to video you want to segment
[OUTPUT_OF_STEP_1] = comma-delimited string of keyframes
[SEGMENT_PREFIX] = name of segment output
[SOURCE_VIDEO_EXTENSION] = extension of source video (e.g., mp4, mkv)
Answer: Use ffprobe -show_frames -pretty <stream> to identify the key frames.
Comment: @sboisse, `-read_intervals` now allows you to specify time or packet intervals to probe. e.g. `ffprobe -show_frames -read_intervals 10%+20,01:30%01:45 -i ` probes from 10-30 seconds, and then from 1:30-1:45.
Comment: Looks like a promising solution. Will investigate. I checked in the documentation but could not easily find a way to ffprobe a small section of the video (say, only the first 10 seconds). Because the video is quite long, it generates a several MB output that takes several seconds to generate. Are there options in ffprobe to output frames of a particular stream only, and within a particular range?
Comment: ffprobe -show_frames **-select_streams v** filtered to only video frames. Now I would only need to be able to specify a range of frame or a range of time.
Comment: I went through the documentation and did not find anything about restraining to a particular time range of the video. So I guess I will use ffmpeg to get a chunk, then call ffprobe on it to get the key frames, and then recall ffmpeg on it to do the final split just before a key frame.
Answer: If you are willing to do some scripting and want I frames at a particular interval the one way to do it is

Run ffprobe and collect the locations of the I frames from the output
ffprobe -show_streams
Run a series of -ss -t commands using the same script to get the chunks you desire.

You can then have your script decide minimum number of frames [say there are two I pictures within 10 frames of each other, you really don't want to be chunking it there].
The other way to do it is to use gstreamer's multisfilesink and set the mode to key frame [however that will chunk at every key frame so that may not be ideal]


if $\rho(A)\leq 1$, then $\frac{1}{2}\rho(A+A^T)\leq 1$?

Question: $A$ is an $n\times n$ matrix (not symmetric). If $\rho(A)$, spectral radius of $A$, is less than or equal to 1, can we say that $x^TAx\leq x^Tx$?
In another word,
if $\rho(A)\leq 1$, then $\frac{1}{2}\rho(A+A^T)\leq 1$?
Answer: No. Choose $A$ to be a matrix of all zeroes except $[A]_{1n} = n+1$. Let $x = (1,...,1)^T$. Then $x^T A x = n+1$, but $x^T x = n$. The spectral radius is $\rho (A) = 0$.
Comment: but I guess the the other way around is true that $\rho(A)>1$ then $\frac{1}{2}\rho(A+A^T)>1$?
Comment: No, Take $A = \begin{bmatrix}0 & 2 \\ -2 & 0 \end{bmatrix}$, then $\rho(A) = 2$, but $A+A^T = 0$, hence $\frac{1}{2} \rho(A+A^T) = 0$.
Comment: Alright I checked Matrix Mathematics by D.S. Bernstein)

Let $A\in\mathbb{R}^{n\times n}$, assume that $A$ is nonnegative, and let $\alpha\in[0,1]$. Then,
$$\rho(A)\leq \rho(\alpha A+(1-\alpha)A^T)$$

Therefore, what I said for $\rho(A)>1$ must be true for nonnegative matrices.
Comment: I'm not sure what you mean by nonnegative. The matrix $A$ in my comment above satisfies $x^T A x \geq 0$ for all $x$, $\rho(A) = 2$ and, as above, $\rho(\frac{1}{2}(A+A^T)) = 0$. Perhaps the author is dealing with symmetric matrices?
Comment: nonnegative means all the elements of $A$ are nonnegative. So the matrix in your example is not nonnegative.
Comment: I see, I was thinking non-negative definite...
Answer: The second part of the question is easier to answer, with the counterexample $$A=\begin{pmatrix}0&1\\0&0\end{pmatrix}.$$


Prove that $A$ is dense in $M \Longleftrightarrow U \cap A \neq \emptyset$ for every nonempty open set $U$

Question: According to my book, a set $A$ is said to be dense in metric space $M$ if $\bar{A} = M$. I know I need to prove two implications here. I have no clue as for how to do this.
Comment: Hint: Use the set $M\setminus\overline{A}$.
Answer: If $A$ is dense and $U$ is a non-empty open set, then take $x\in U$. Then $U$ is a neighborhood of $x$ and then, since $\overline A=M$ and $x\in M$, $U\cap A\neq\emptyset$.
Now, suppose that $A$ is such that $U\cap A\neq\emptyset$ for every non-empty open set $U$. Let $x\in M$ and let $N$ be a neighborhood of $x$. Let $U$ be an open subset of $M$ such that $x\in U$ and $U\subset N$. Then $U\cap A\neq\emptyset$, and this imples that $N\cap A\neq\emptyset$. Since this occurs for each neghborhood of $x$, $x\in\overline A$. Therefore, $\overline A=M$.
Answer: You can also prove $\neg p\iff\neg q$ instead of $p\iff q$.

If $A$ is not dense in $M$ then $U:=M-\overline{A}$ is not empty.
Also it is open, and this with $U\cap A=\varnothing$.
Converse:
If  $U$ is an open set with $U\cap A=\varnothing$ then $A\subseteq U^{\complement}$ where $U^{\complement}$ is closed.
So $\overline{A}\subseteq U^{\complement}$ and if $U$ is not empty then consequently $\overline{A}\neq M$.
Comment: In the converse part, if $U$ is not empty and $U\cap A =\emptyset$, then $U\subset (M\setminus\overline{A})$, hence this set is not empty.
Comment: @Gribouillis Yes, but why do you mention that? If $U$ is not empty then every subset of its complement is not $M$, so $\overline{A}\neq M$, i.e. $A$ is not dense.
Comment: Well, I felt it was a little more direct than what you wrote, but I may be wrong. Never mind.
Answer: $\Rightarrow$). Suppose $\overline{A}=M$. Prove by contradiction. Let $U$ be an non empty open set in $M$ such that $U\bigcap A=\emptyset$. Then there exists an open ball $B(x,r)\subset M$ such that $B(x,r)\bigcap A=\emptyset$ which contradicts with $\overline{A}=M$.
$\Leftarrow$). Suppose for every non empty open set $U$ we have $U\bigcap A\neq\emptyset$. For any $x\in M$ and given any $\varepsilon>0$, then the open ball $B(x,\varepsilon)\bigcap A\neq \emptyset$. By taking $\varepsilon=\frac{1}{n}$ and taking $n\rightarrow\infty$, we obtain that $x\in\overline{A}$.


Different icons size for different resolutions on Android

Question: I'm developing an application for a Samgsung Galaxy Tab (1024x600px). In a Activity I use few icons of 128x128px and looks great.
But I run it in a Samgsung Galaxy S (480x800) and icons are too large.
I put same icons at 100x100px in drawable-mdpi, but now It resized both devices. I suppose this is because Tab and Galaxy S are in the same range of density.
How can I do automatically use different icons according to SCREEN SIZE?
I see layout-large, layout-xlarge is according to screen size, but is for layouts, not icons.
Thanks a lot!
Answer: Well Now there is exists Better tools then assert generator in android studio
For application Icon ( Toolbar , ActionBar , DrawableLeft etc ) Use :
http://romannurik.github.io/AndroidAssetStudio/icons-actionbar.html
For launcher (Application Icon ) Use :
https://romannurik.github.io/AndroidAssetStudio/icons-launcher.html
But Here are some tricks and way to get the better resolution for icons and launcher icons.
Step 1 :
First go to the https://materialdesignicons.com and choose your icon . Or if you have your icon in good resolution then skip this step . Click the desired icon and click on "Advanced Export" it will open up a window like this below
Then click the "Icon" to generate icon (.png) . Well the trick is try to generate as large icon as possible for high resolution devices and the tools will handle it all for small devices but if you use small icon , while generating the icon for high end devices you will loose the icon resolution .
Step 2 :
Then go the Tools page and Upload the Icon
Click the "Custom" if you want to color your icon . No matter what color of icon you are uploading , by using Custom you can generate any color you want .
Then choose a name and click "Download .ZIP" . This will download the .zip file with the icon for most of the common resolution . You can copy and paste the res folder in your application project folder and you will see the icon in the drawable section .
Comment: this one is very helpful
Answer: You can use the width of the screen
<code>DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels /4;
</code>
Answer: You have the same with drawable :
http://developer.android.com/guide/practices/screens_support.html
Comment: I've read this documentation, but I don't understand you. I don't have any drawable-large, drawable-xlarge..., I think icons are according to density and layouts to resolution. But both devices are in the same range of density...
Comment: You have small icons in drawable-mdpi for the tab and big icons in drawable-hdpi for the phone ? They are not in the same range of density 170dpi versus 233.
Comment: I have a 100x100px icon in drawable-hdpi and a 128x128px icon in drawable-mdpi. I run the application and on the Tab and Galaxy S it uses the small icon!
Comment: Look at smallestWidth tag ("sw")


Bootstrap Accordion não funciona quando carrega conteúdo com ajax

Question: Tenho meu acordion, dentro do body dele, eu tenho uma div aonde é carregado o conteúdo via ajax

          Titulo

Carregando

          Titulo 2

Carregando

e para isso uso o seguinte código javascript:
    $(".conteudo").each(function (index, item) {
        var url = $(item).data("url");
        if (url && url.length > 0) {
            $(item).load(url);
        }
    });

Mas enquanto ele carrega essas views, que as vezes pode demorar,o accordion simplesmente trava e não aparece o "hover" do a link, ao clicar nas abas do accordion ele não faz nada
Algo errado?
Comment: Fica mais fácil pra quem quiser testar se vc fornecer um código plug'n'play, com html mínimo contendo `
Answer: Oi,
Seu HTML está inválido. Antes do seu segundo
 está faltando um
.
Aqui tem um exemplo funcionando.
Comment: Não sei aonde você viu faltando...mas enfim, está correto.
Answer: Em pesquisas, vi que é por causa da lib collapse.js que o bootstrap usa.
A mesma não obtem suporte para isso.
Uma forma de resolver, é carregar ao clicar no accordion.


RStudio not picking the encoding I'm telling it to use when reading a file

Question: I'm trying to read the following UTF-8 encoded file in R, but whenever I read it, the unicode characters are not encoded correctly:

The script I'm using to process the file is as follows:
defaultEncoding <- "UTF8"
detalheVotacaoMunicipioZonaTypes <- c("character", "character", "factor", "factor", "factor", "factor", "factor",
                                                     "factor", "factor", "factor", "factor", "factor", "numeric",
                                                     "numeric", "numeric", "numeric", "numeric", "numeric",
                                                     "numeric", "numeric", "numeric", "numeric", "numeric",
                                                     "numeric", "character", "character")

readDetalheVotacaoMunicipioZona <- function( fileName ) {
  fileConnection = file(fileName,encoding=defaultEncoding)
  contents <- readChar(fileConnection, file.info(fileName)$size)
  close(fileConnection)
  contents <- gsub('"', "", contents)

  columnNames <- c("data_geracao", "hora_geracao", "ano_eleicao", "num_turno", "descricao_eleicao", "sigla_uf", "sigla_ue",
                   "codigo_municipio", "nome_municipio", "numero_zona", "codigo_cargo", "descricao_cargo", "qtd_aptos",
                   "qtd_secoes", "qtd_secoes_agregadas", "qtd_aptos_tot", "qtd_secoes_tot", "qtd_comparecimento",
                   "qtd_abstencoes", "qtd_votos_nominais", "qtd_votos_brancos", "qtd_votos_nulos", "qtd_votos_legenda",
                   "qtd_votos_anulados", "data_ult_totalizacao", "hora_ult_totalizacao")

  read.csv(text=contents,
           colClasses=detalheVotacaoMunicipioZonaTypes,
           sep=";",
           col.names=columnNames,
           fileEncoding=defaultEncoding,
           header=FALSE)
}

I read the file sending in the UTF-8 encoding, remove all quotes (even numbers are quoted, so I need to clean them up) and then feed the contents to read.csv. It reads and processes the file correctly but it seems like it's not using the encoding information I'm giving it.
What should I do to make it use UTF-8 to read this file?
I'm using RStudio on OSX if it makes any difference.
Comment: If the only problem is RStudio, go to RStudio->Preferences:General, tell us what 'Default text encoding:'is set to, click 'Change' and try UTF-8 or ISO8859-1('latin1'). Let us know which one worked!
Comment: I don't know how text is stored internally in R, but in any case it seems like you're attempting to decode UTF-8 *twice* (but R should disregard that according to the documentation).
Comment: Are you sure the file is properly encoded? Are you using RStudio? It could be that it is read correctly but not displayed correctly in their interface (I can't find the issue now, maybe it has been closed).
Comment: Inside r-studio it doesn't work, if I do it in a console session it works. That's weird.
Comment: Your .csv file on github looks like correctly-encoded Windows-1252 to me. You say the problem only happens inside RStudio. So let's try setting both the locale and default character encodings (try CP1252, UTF-8, ISO8859-1 in that order). See my answer below.
Comment: Tagged 'RStudio' and retitled, since you say this issue is caused by RStudio, not R itself. (Revert that if that's not the case)
Answer: This problem is caused by the wrong locale being set, whether inside RStudio or command-line R:

If the problem only happens in RStudio not command-line R, go to RStudio->Preferences:General, tell us what 'Default text encoding:'is set to, click 'Change' and try Windows-1252, UTF-8 or ISO8859-1('latin1') (or else 'Ask' if you always want to be prompted). Screenshot attached at bottom. Let us know which one worked!
If the problem also happens in command-line R, do the following:

Do locale -m on your Mac and tell us whether it supports CP1252 or else ISO8859-1 ('latin1')? Dump the list of supported locales if you need to. (You might as well tell us your version of MacOS while you're at it.)
For both of those locales, try to change to that locale:
# first try Windows CP1252, although that's almost surely not supported on Mac:
Sys.setlocale("LC_ALL", "pt_PT.1252") # Make sure not to omit the `"LC_ALL",` first argument, it will fail.
Sys.setlocale("LC_ALL", "pt_PT.CP1252") # the name might need to be 'CP1252'

# next try IS08859-1(/'latin1'), this works for me:
Sys.setlocale("LC_ALL", "pt_PT.ISO8859-1")

# Try "pt_PT.UTF-8" too...

# in your program, make sure the Sys.setlocale worked, sprinkle this assertion in your code before attempting to read.csv:
stopifnot(Sys.getlocale('LC_CTYPE') == "pt_PT.ISO8859-1")

That should work.
Strictly the Sys.setlocale() command should go in your ~/.Rprofile for startup, not inside your R session or source-code.
However Sys.setlocale() can fail, so just be aware of that. Also, assert Sys.getlocale() inside your setup code early and often, as I do. (really, read.csv should figure out if the encoding it uses is compatible with the locale, and warn or error if not).
Let us know which fix worked! I'm trying to document this more generally so we can figure out the correct enhance.

Screenshot of RStudio Preferences Change default text encoding menu:
Comment: In RStudio 1.0.143 I couldn't find RStudio->Preferences:General. And at Options > Code there is no "Default text encoding" option
Comment: I notice you're in Brazil, so instead of `pt_PT.` -> `pt_BR.`. Shouldn't make any difference for this issue though.
Comment: +1. I think this is quite relevant for Portuguese users of both R and RStudio.
Comment: In RStudio 1.0.136, this settings is moved to `Options > Code > Default text encoding` but data still in wrong encoding, showing things in Latin-1, not in UTF-8.
Comment: @Peter.k: UTF-8/16 are the two most common encoding schemes for Unicode; see [*What is Unicode, UTF-8, UTF-16?
*](https://stackoverflow.com/questions/2241348/what-is-unicode-utf-8-utf-16). For supporting foreign languages, and other fonts/ symbols (/ emoticons). But if you find a bug in RStudio IDE itself, please post it at https://github.com/rstudio/rstudio/issues . At least read through their existing issues, upvote, subscribe etc. RStudio frequently has bugs, so be community-minded and report them...
Comment: You can find the preferences under global options -> code -> saving in the newer versions of Rstudio
Comment: @PauloCardoso: it's relevant for *all* international users of R and RStudio using foreign character sets or Unicode.
Comment: Many Thanks! So what is that UTF-8 for? I thought it's like encoding esperanto, meanwhile, besides postgres db is set to utf-8 and my RStudio as well, this db connections (and most of web content) works with i.e. Windows-1252,not utf-8
Answer: It works fine for me.
Did you try to change/reset locale?
in my case it works with
Sys.setlocale(category = "LC_ALL", locale = "Portuguese_Portugal.1252")

d <- read.table(text=readClipboard(), header=TRUE, sep = ';')

head(d)

1  25/04/2014  22:29:30  2012  1 ELEIÇÃO MUNICIPAL 2012 PB  20419    20419      ITAPORANGA  33  13 VEREADOR 17157
2  25/04/2014  22:29:30  2012  1 ELEIÇÃO MUNICIPAL 2012 PB  20770    20770           MALTA  51  11 PREFEITO  4677
3  25/04/2014  22:29:30  2012  1 ELEIÇÃO MUNICIPAL 2012 PB  21091    21091     OLHO D'ÁGUA  32  13 VEREADOR  6653
4  25/04/2014  22:29:30  2012  1 ELEIÇÃO MUNICIPAL 2012 PB  21113    21113        OLIVEDOS  23  13 VEREADOR  3243
...

Comment: This is what I get when I try that: `OS reports request to set locale to "Portuguese_Portugal.1252" cannot be honored`. I'm using a mac if it makes any difference.
Comment: @Paulo: instead of `Portuguese_Portugal.`, just say `pt_PT.`. Or `pt_BR.`
Comment: @MaurícioLinhares hard to say, specially with mac. did you see [this topic](http://stackoverflow.com/q/5345132/640783)?
Comment: @MaurícioLinhares: make sure you typed `Sys.setlocale("LC_ALL", "Portuguese_Portugal.1252")`. If you omit the `"LC_ALL",` first argument, it will fail.
Comment: @MaurícioLinhares: make sure you typed Sys.setlocale("LC_ALL", "Portuguese_Portugal.1252"). If you omit the "LC_ALL", first argument, it will fail. Second, it might be `.CP1252` instead of `1252`. Thirdly, `CP1252` might not supported on Mac anyway, see `locale -m` to see what your machine supports (what version of MacOS are you anyway?).
Comment: @smci "Portuguese_Portugal" is what I get with sessionInfo but ok. nice to know that both cases will work!
Answer: I had the same problem with Portuguese locale in r (MAC OS 10.12.3)
I've tried as per thread above and no one worked. Then I found this webpage: https://docs.moodle.org/dev/Table_of_locales
and just tried Sys.setlocale(category = "LC_ALL", locale = "pt_PT.UTF-8") and it works.
Comment: This worked in my case also `Sys.setlocale(category = "LC_ALL", locale = "no_NO.UTF-8")`. Before this `Sys.getlocale()` returned only `[1] "C"` and after it output `[1] "no_NO.UTF-8/no_NO.UTF-8/no_NO.UTF-8/C/no_NO.UTF-8/C"`. Test with your local letters something like this `read.table(text='"å", "æ", "ø", "ä"', sep=",")`
Answer: You should try library(readr) functions, such as read_csv() or read_fwf()(note the underscore instead of the dot), it guesses the encoding of the file, usually succeeds in doing so; these readr functions come bundled in RStudio GUI function "import dataset"
Answer: If your system is Mac, open terminal, copy this code
defaults write org.R-project.R force.LANG en_US.UTF-8

paste and run. I hope it works. I had the same problem.


Player takes a corner kick which hits the post, and plays the rebound directly, is it legal?

Question: One player takes a corner kick, hits the post and the ball goes back to the same player, without being touched by anyone else. That same player plays the ball immediately.
Is it legal?
Rule 17 says a player cannot touch it twice, but does not say anything about hitting the post.
Comment: Rule of thumb: The woodwork and corner flags do not count as players.
Answer: I'm not quite sure what the uncertainty is here. Law (not Rule) 17.2 states:

If, after the ball is in play, the kicker touches the ball again before it has touched another player, an indirect free kick is awarded

The ball has not touched another player, therefore an indirect free kick is awarded.
Comment: The uncertainity comes from the referree of  the game where I saw it this morning. He didn't award free kick....
Comment: Could you give details of exactly which game that was and if possible an approximate time?
Comment: @OscarFoley Referees make mistakes. He might have judged that someone did touch the ball, or didn't notice that it was the corner kicker that got the rebound, or forgot to to pay attention to the rule.
Comment: It was in a league of 7-side football for kids (10 years)
Comment: By far the most likely explanation in that case was the referee was just wrong. Be nice to amateur referees though :)


How to do multiple clicks with .trigger()?

Question: Is there a simplier way to do this in jQuery?
$('button').click(function() {
    // do something
}).trigger('click').trigger('click').trigger('click');

Comment: Can you explain what you're trying to achieve, as I can almost guarantee you there's a better way than this.
Comment: `for (var i = 0; i < timesToRun; i++) addDiv();`?
Comment: I want to add three divs into another. I have the 'addDiv' function what do this, and I want to run this function multiple times. Three is only a number for example, it is various.
Answer: Adding A. Wolff's comment, There is no in-build method in jQuery/js to trigger event X times. But, you can pass parameters to the trigger(), if you know. So pass the times there:
$('button').click(function() {
    // do something
}).trigger('click', 3);

Or, for just one
:
$('button').click(function() {
    // do something
}).trigger('click')

And then handle this in the // do something code block! It could be something like:
$('button').click(function(event, times) {
    times = (times == undefined) ? 1 : times;
    for (i = 0; i < times; i++)
       addDiv();
    // do something
}).trigger('click', 3)

Snippet

$(function () {
  $("a").click(function (e, t) {
    t = (t == undefined) ? 1 : t;
    for (i = 0; i < t; i++)
      $("#testarea").append("Clicked
");
    return false;
  }).trigger('click', 3);
});

Click Me


n-tuple function definition

Question: I've read this definition for an hour now and I cannot piece it together abstractly.
To define an n-tuple as a function $F$, where $X$ is the index set and domain, and $Y$ is the set containing the elements of the tuple:
$$(a_1,a_2, ...,a_n) \equiv (X, Y, F)$$
$X= \{1,2,...,n\}$
$Y= \{a_1,a_2,...,n\}$
$F= \{(1,a_1),(2,a_2),...,(n,a_n)\}$
However,
$$(a_1,a_2,...,n) := (F(1),F(2),...,F(n))$$
is a lot more comprehensible. It might be the notation in the previous definition that throws me off, or maybe there is something more fundamental that I cannot see or recall.
Comment: I agree that your definition is much more approachable; a function $f: [n] \to Y$ is a sequence. I'm not sure exactly what your question is, however.
Comment: An explanation of the first definition. More of a request, though. I'm not familiar with the (X, Y, F) expression either.
Answer: It sounds like you're OK thinking of a sequence $(a_1, a_2, \ldots, a_n)$ of elements of some set, $Y$, as a function.
Explicitly, given that our sequence should consist of $n$ elements of $Y$, let $X$ denote the set $\{1, 2, \ldots, n\}$. Then any function
\begin{align*}F: X &\to Y \\
k &\mapsto a_k\end{align*} defines a sequence that we can write, like you pointed out, $\left(f(1), f(2), \ldots, f(n)\right) = (a_1, a_2, \ldots, a_n)$.
By writing the whole thing as a triple $(X, Y, F)$, they're just listing the domain, the range, and the function $F$ from the domain to the range.
As far as writing $F = \{(1, F(1)), (2, F(2)), \ldots, (n, F(n))\}$, that's just thinking of a function as ordered pairs, with the first coordinate from the domain, and the second from the range.
I think that's the big idea: just think of the ordered triple $(X, Y, F)$ as $($domain, range, function$)$. You already know we need that data, they're just being very formal about it.

n-tuple function definition


NSSearchField with left aligned placeholder

Question: After setting centersPlaceholder = false, the placeholder aligns correctly at the left, but the search button doesn't show its image. The same is true for the cancel button when entering some text. Is that the correct behavior or am I missing something?
Answer: This related question sheds some light on how the strange behavior could be (ab)used to force a left-align in the field. Simply subclass NSSearchFieldCell and override draw method:
import Cocoa

class FilterFieldCell: NSSearchFieldCell {
    override func draw(withFrame cellFrame: NSRect, in controlView: NSView) {
        super.draw(withFrame: cellFrame, in: controlView)
    }
}

And then set your search field cell to this class.
Comment: I think you can also fix the drawing by overriding `draw(_ dirtyRect: NSRect)` on a subclass of the `NSSearchField`, and just calling super.
Answer: #define kSearchButtonWidth 22.f

#import "AMSearchField.h"

@implementation AMSearchField

- (void)drawRect:(NSRect)dirtyRect {
    [super drawRect:dirtyRect];
    // Drawing code here.
}

- (NSRect)rectForSearchButtonWhenCentered:(BOOL)isCentered
{
    CGRect rect = [super rectForSearchButtonWhenCentered:isCentered];
    if (rect.size.width < kSearchButtonWidth) {
        rect.size.width = kSearchButtonWidth;
    }
    return rect;
}

- (NSRect)rectForSearchTextWhenCentered:(BOOL)isCentered
{
    CGRect rect = [super rectForSearchTextWhenCentered:isCentered];
    if (rect.origin.x < kSearchButtonWidth) {
        CGFloat delta = kSearchButtonWidth - rect.origin.x;
        rect.origin.x = kSearchButtonWidth;
        rect.size.width = rect.size.width - delta;
    }
    return rect;
}

@end

in xib file, set search class to AMSearchField


How to set cascade deleting properly in Entity Framework 6 when I have two foreign keys?

Question: I have below example and I need to have behaviour: when I delete RoundAssetT, I don't want to delete his assetOccurrences... I can't figure out how to set this relation in modelBuilder.
public class RoundAssetT
{
    [Column(Order = 1), Key, ForeignKey("RoundT")]
    public int RoundTId { get; set; }

    [Column(Order = 2), Key, ForeignKey("AssetT")]
    public int AssetTId { get; set; }

    public virtual AssetT AssetT { get; set; }
    public virtual RoundT RoundT { get; set; }

    public string Name { get; set; }

    public ICollection<AssetOccurrenceT> AssetOccurrencesT { get; set; }
}

public class AssetOccurrenceT
{
    [Key]
    public int Id { get; set; }

    [Column(Order = 1), ForeignKey("RoundAssetT")]
    public int? RoundTId { get; set; }

    [Column(Order = 2), ForeignKey("RoundAssetT")]
    public int? AssetTId { get; set; }

    public virtual RoundAssetT RoundAssetT { get; set; }

    public string NameAOt { get; set; }
}

Could someone tell me how to set up this relation in Entity Framework 6?
Answer: AssetOccurrenceT.RoundAssetT would have to be optional since you want to be able to delete RoundAssetTs without also deleting referencing AssetOccurrenceTs
modelBuilder.Entity<AssetOccurrenceT>()
    .HasOptional(ao => ao.RoundAssetT)
    .WithMany(ra => ra.AssetOccurrencesT);

Comment: okey, but I just need to add cascade delete ( false ) to above code?
Comment: I don't think it's necessary
Comment: You have right, I will give You best answer , thanks a lot ! could You just also explain me, is there any possiblity to remove not remove value of assetId?
Comment: Are you asking if you can keep the FK value after you delete the entity it references?  Look into soft deletes


Trying to find integral of square root function.

Question: I am trying to find the integral of $\int_{0}^{\sqrt{6}}x \sqrt{36-6 x^2}$. When I use the substitution rule, I get $u = 36-6x^2$, which results in an imaginary number: $\dfrac{1}{12}u^{3/2} du$
My textbook suggests me to use $u = -36 + 6x^2$, but I am not sure how to do this.
Thanks
Comment: Why is it an imaginary number?
Comment: Are you using the Wolfram software package *Mathematica* or shall I move your question to [Math.SE]?
Comment: Please move to mathematics. Thanks
Answer: You have the correct substitution, it is just working out the integral:
$$\int_0^\sqrt{6} x\sqrt{36-6x^2}\,dx$$
Let $u=36-6x^2$ so $du=-12x \,dx$.
$$\int_{36}^0-\frac{\sqrt{u}}{12}\;du$$
$$\frac{1}{12}\int_0^{36}\sqrt{u}\;du$$
$$\frac{2u^{3/2}}{36}|_0^{36}=12$$


Vegafusion No module named 'vl_convert' error python

Question: I am using vegafusion with altair and python to display a chart that won't show because of the max rows limit, but I have installed vegafusion and imported and enabled it.
When I go to run the visualisation, I get this error
    ~\anaconda3\lib\site-packages\vegafusion\compilers.py in vl_convert_compiler(vegalite_spec)
     16     try:
---> 17         import vl_convert as vlc
     18     except ImportError:

ModuleNotFoundError: No module named 'vl_convert'

Comment: Please include a [mre] and package versions
Answer: The VegaFusion mime renderer requires the vl-convert-python package. This comes along automatically if you install VegaFusion with:
pip install -U "vegafusion[embed]"

But you can also install it separately with:
pip install -U vl-convert-python

Hope that helps!


lxml.etree._Element.append() from a loop not working as expected

Question: I would like to know why in this code append() seems to work from inside the loop, but the resulting xml displays the modification from only the last iteration, while remove() works as expected. This is a overly simplified example, I'm working with big chunks of data, and need to append the same subtree to many different parents.
from lxml import etree

xml = etree.fromstring('<tree><fruit id="1"></fruit><fruit id="2"></fruit></tree>')
sub = etree.fromstring('<apple/>')

for i, item in enumerate(xml):
    item.append(sub)
    print('Fruit {} with sub appended: {}'.format(
        i, etree.tostring(item).decode('ascii')))

print('\nResulting tree after iterating through items with append():\n' +
    etree.tostring(xml, pretty_print=True).decode('ascii'))

for item in xml:
    xml.remove(item)

print('Resulting tree after iterating through items with remove():\n' +
    etree.tostring(xml, pretty_print=True).decode('ascii'))

Current output:
Fruit 0 with sub appended: <fruit id="1"><apple/></fruit>
Fruit 1 with sub appended: <fruit id="2"><apple/></fruit>

Resulting tree after iterating through items with append():
<tree>
  <fruit id="1"/>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

Resulting tree after iterating through items with remove():
<tree/>

Expected output from after iterating through items with append():
<tree>
  <fruit id="1"/>
    <apple/>
  </fruit>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

Comment: also this works  in xml.etree.ElementTree unlike lxml
Answer: That's because you only created one instance of <apple/> to be appended. So basically you just moved that one instance from one parent to another until the last append(sub) executed. Try to move creation of the <apple/> element within for loop instead :
for i, item in enumerate(xml):
    sub = etree.fromstring('<apple/>')
    item.append(sub)
    print('Fruit {} with sub appended: {}'.format(
        i, etree.tostring(item).decode('ascii')))
print()

output :
Resulting tree after iterating through items with append():
<tree>
  <fruit id="1">
    <apple/>
  </fruit>
  <fruit id="2">
    <apple/>
  </fruit>
</tree>

Comment: OK, it actually modified every item, but then `` got removed later, now I think I understand it! Thank you!
Comment: That works, thanks! Why does `print('Fruit {} with sub appended: {}'...` prints the correct output? I'm new to python, so this is some concept I don't yet understand!
Comment: is there a way not to read xml from string per each iteration? my sub is already in etree format
Comment: EDIT fixed its `i.append(ET.fromstring(ET.tostring(sub)))`