Determine the truth value of $(\forall x)(\exists y)(x=y\to x>y)$ over the integers

Question:
Determine the truth value of $$(\forall x)(\exists y)(x=y\to x>y)$$ over the integers.

My work:
$(\forall x)(\exists y)(x=y\to x>y)$ means "For all $x$, there exists a $y$ where $x=y\to x>y$".
Since $x=y$, we can replace the $y$ with the $x$ and vice-versa. We can get $$x>x$$ once we replaced.
This statement is always false, no matter what $x$ is. So in this case $x=y$ is true, but $x>y$ is not true, or false. So, using the truth table below, $$\begin{array}{c|c|c}x=y&x>y&x=y\to x>y\\\hline\mathrm{T}&\mathrm{T}&\mathrm{T}\\\color{red}{\mathrm{T}}&\color{red}{\mathrm{F}}&\color{red}{\mathrm{F}}\\\mathrm{F}&\mathrm{T}&\mathrm{T}\\\mathrm{F}&\mathrm{F}&\mathrm{T}\end{array}$$ we can say that this statement is false.
(Image that replaced text).
Comment: What was wrong about the first solution was you sort of missed the point to the $\forall x\exists y$ part (the "quantifiers"). Here's an outline of the solution that deals properly with the quantifiers, with blanks you should be able to fill in: "Given $x$, let $y=\dots$. Then ..., so $x=y\to x>y$ is true."
Comment: What you wrote in that solution explains why $x=y\to x>y$ is not always true. So that shows that $\forall x\forall y(x=y\to x>y)$  is false, but it doesn't say anything about the given problem.
Comment: You don't. It's true.
Comment: What do you mean by that?
Comment: I mean your solution is wrong.
Comment: Ohhh. So how do I prove that (∀x)(∃y)(=→>) is false?
Comment: Sorry for asking this again, but how do I show that?
Comment: Would I use contradiction?
Comment: Thank you so much for your help.
Answer: Hint: $\forall x~\color{red}\exists y~(P(x,y)\to Q(x,y))$ is true exactly when: every $x$ has some $y$ where $Q(x,y)$ is true or $P(x,y)$ is false.

Since $x=y$, we can replace the $y$ with the $x$ and vice-versa. We can get $$x>x$$ once we replaced.
This statement is always false, no matter what $x$ is. So in this case $x=y$ is true, but $x>y$ is not true, or false. So, using the truth table below, $$\begin{array}{c|c|c}x=y&x>y&x=y\to x>y\\\hline\mathrm{T}&\mathrm{T}&\mathrm{T}\\\color{red}{\mathrm{T}}&\color{red}{\mathrm{F}}&\color{red}{\mathrm{F}}\\\mathrm{F}&\mathrm{T}&\mathrm{T}\\\mathrm{F}&\mathrm{F}&\mathrm{T}\end{array}$$ we can say that this statement is false.

No.  What the truth table is telling you is that the implication is true in three cases.
Case 1: $x=y$ and $x>y$. Well, for any $x$ that cannot happen. However we must check the other two cases.
Case 2: $\lnot(x=y)$ and $x>y$.  Well, for any $x$ there is some $y$ where both of these are true.
Case 3: $\lnot (x=y)$ and $\lnot(x>y)$.  Well, for any $x$ there is some $y$ where both of these are true.
Since for any $x$ there is a $y$ where $\lnot (x=y)$, then cases $2$ and $3$ may be satisfied for any $x$. Thus we confirm that for any $x$ there is some $y$ where the implication holds.
Answer: If $P(x)$ is false for some $x$, then $P(x) \to Q(x)$ is true no matter what the value of $Q(x)$ is so if you find an $y$ where $y \neq x$(e.g $x-1$), the statement would always hold.
Also, this is related:  $\lnot\exists x(S(x) \Rightarrow R(x))$ VS $\forall x(S(x) \Rightarrow R(x))$ Without Using De Morgan's Law


Maximal proper subgroups of $S_5$

Question: Denote by $Sym(X)$ the symmetric group of any set $X$, and let $S_5=Sym(\lbrace 1,2,3,4,5 \rbrace)$. Let $F$ denote the "Frobenius" subgroup $ \langle (1,2,3,4,5) ,(2,3,5,4)\rangle$ (it is a semi-direct product $ \langle (1,2,3,4,5) \rangle\rtimes \langle(2,3,5,4) \rangle$ and has therefore order $20$) and let $P$ denote the "product" group $ Sym(\lbrace 1,2 \rbrace) \times  Sym(\lbrace 3,4,5 \rbrace)$, and $S=Sym(\lbrace 1,2,3,4 \rbrace)$. I wish to show the following :
Fact. Let $G$ be a subgroup of $S_5$. Then either $G=S_5, G=A_5$, or $G$ is included in a conjugate of $F$, $P$ or $S$.
My question: Find an elementary proof of this fact.
(I have verified this fact using a computer system and now I'm looking for a computer-free proof. I am also aware of advanced results like the O'Nan-Scott theorem but I'm looking for a more elementary proof here).
So far, I was able to show the fact when $G$ contains both a $5$-cycle and a $4$-cycle. Indeed, using conjugation we may assume that $G$ contains $\theta=(1,2,3,4,5)$.
Now, if we put $\alpha=(2,3,5,4),\beta=(2,3,4,5)$ and $\gamma=(2,4,3,5)$, the following table show that every $4$-cycle can be uniquely written as $\theta^k \sigma \theta ^{-k}$ where $\sigma\in\lbrace \alpha^{\pm 1},\beta^{\pm 1},\gamma^{\pm 1} \rbrace$  :
$$
\begin{array}{|l|c|c|c|c|c|}
\hline
k & 0 & 1 & 2 & 3 & 4 \\
\hline
\theta^k \alpha \theta ^{-k} & (2,3,5,4) & (1,5,3,4) & (1,4,5,2) & (1,3,2,5) & (1,2,4,3) \\
\hline
\theta^k \alpha^{-1} \theta ^{-k} & (2,4,5,3) & (1,4,3,5) & (1,2,5,4) & (1,5,2,3) & (1,3,4,2) \\
\hline
\theta^k \beta \theta ^{-k} & (2,3,4,5) & (1,3,4,5) & (1,2,4,5) & (1,2,3,5) & (1,2,3,4) \\
\hline
\theta^k \beta^{-1} \theta ^{-k} & (2,5,4,3) & (1,5,4,3) & (1,5,4,2) & (1,5,3,2) & (1,4,3,2) \\
\hline
\theta^k \gamma \theta ^{-k} & (2,4,3,5) & (1,3,5,4) & (1,5,2,4) & (1,3,5,2) & (1,3,2,4) \\
\hline
\theta^k \gamma^{-1} \theta ^{-k} & (2,5,3,4) & (1,4,5,3) & (1,4,2,5) & (1,2,5,3) & (1,4,2,3) \\
\hline
\end{array}\tag{1}
$$
If we define $A(\sigma)=\lbrace \theta^k \sigma \theta ^{-k}\rbrace$ and  $B(\sigma)=A(\sigma)\cup A(\sigma^{-1})$, the table (1) above shows that $B(\alpha) \cup B(\beta) \cup B(\gamma) $ partitions the $4$-cycles. Now, by construction we have that $\langle\theta,\sigma'\rangle =\langle\theta,\sigma\rangle $ if $\sigma'\in B(\sigma)$.
As a first special case, we have $\langle\theta,\sigma\rangle =\langle \theta,\alpha\rangle  = F$ for every $\sigma\in B(\alpha)$.
we similarly have $\langle \theta,\sigma\rangle =\langle \theta,\beta\rangle $ for every $\sigma\in B(\beta)$ and $\langle \theta,\sigma\rangle =\langle \theta,\gamma\rangle $ for every $\sigma\in B(\gamma)$. Now, from $\gamma = \theta^2 \beta^2\theta \beta$ and $\beta = \theta \gamma \theta^2 \gamma ^2$ we see that $\langle \theta,\beta\rangle $ and $\langle \theta,\gamma\rangle $ are the same subgroup of $S_5$. This subgroup contains both $(1,2,3,4,5)=\theta$ and $(1,2)=\beta \theta ^{-1}$, and it is then easy to show that it is the whole of $S_5$.
Answer: I don't know how much this can be streamlined. Starting out with the following.
Let $G$ be a subgroup of $S_5$.
Observation #1. If $G$ is not transitive, then it preserves a partition of the type 1+4 or of the type 2+3, and the full stabilizers of such partitioins were explicitly listed.
So from this point on we can assume that $G$ is transitive, hence its order is divisible by five, and it contains a 5-cycle $\alpha$.
Observation #2. If $3\mid |G|$ then $A_5\le G$.
Proof. In this case $G$ contains a 3-cycle $\beta$. The five conjugates
$\alpha^i\beta\alpha^{-i}$ are all 3-cycles, each with two fixed points. It follows easily that among them we have two conjugate 3-cycles sharing exactly one fixed point $a\in\{1,2,3,4,5\}$. The stabilizer $G_a$ is thus a subgroup of $S_4$ that contains at least two 3-cycles $\beta$ and $\beta'$ that are not each others powers. Any such pair of 3-cycles generates a transitive subgroup of $S_4$, which thus has order at least twelve, and must contain $A_4$. So $G_a$ contains a copy of $A_4$, and the claim follows.
The remaining case is that $3\nmid |G|$. This means that the point stabilizers $G_a$ are 2-groups, and hence are subgroups of an appropriate copy of the dihedral group $D_4\le Stab_{S_5}(a)$. If $G_a$ contains a 2-cycle $\gamma$, then the 2-cycles $\alpha^i\gamma\alpha^{-i}$ generate all of $S_5$, a case already excluded. So if $|G_a|=2$, we know that $G_a$ is generated by a product of two disjoint 2-cycles. Such a permutation is the square of a 4-cycle. At this point I want to eliminate the possibility that $G_a$ contains two distinct permutations with cycle type $(2,2)$. Here we need to be more specific to do calculations with permutations. Without loss of generality $a=1$, $\alpha=(12345)$, and in the case to be eliminated $G_a$ contains at least two (and hence the third as their product) of the permutations $(23)(45)$, $(24)(35)$, $(25)(34)$. Conjugating all of these by $\alpha$ shows that $G$ contains all of $(12)(34)$, $(13)(24)$ and $(14)(23)$. As a product we then find a 3-cycle in $G$. For example $(14)(23)(23)(45)=(14)(45)=(145)$. Again taking us back to a case we already covered. We have shown:
Observation 3. If $G$ is transitive and $3\nmid |G|$, then the point stabilizers $G_a$ are all cyclic 2-groups of order $1,2$ or $4$, and cannot contain a 2-cycle.
If $|G_a|=2$, then $G$ must be the dihedral group $D_5$, and those are contained in a conjugate of $F$. The remaining case is $|G_a|=4$. In this case $|G|=20$, so its Sylow $5$-subgroup $P=\langle\alpha\rangle$ is normal. Hence $G_a\le N_{S_5}(P)$. There are $24$ 5-cycles in $S_5$, so $P$ has six conjugates in $S_5$ (each containing four 5-cycles, namely the non-trivial powers of $\alpha)$. It follows that $|N_{S_5}(P)|=120/6=20$, so $G=N_{S_5}(P)$ which is a conjugate of $F$.
Comment: Gotta commute next. Hopefully this can be simplified.

Maximal proper subgroups of $S_5$


Split comma separated values of a column in row, through Oracle SQL query

Question: I have a table like below:
-------------
ID   | NAME
-------------
1001 | A,B,C
1002 | D,E,F
1003 | C,E,G
-------------

I want these values to be displayed as:
-------------
ID   | NAME
-------------
1001 | A
1001 | B
1001 | C
1002 | D
1002 | E
1002 | F
1003 | C
1003 | E
1003 | G
-------------

I tried doing:
select split('A,B,C,D,E,F', ',') from dual; -- WILL RETURN COLLECTION

select column_value
from table (select split('A,B,C,D,E,F', ',') from dual); -- RETURN COLUMN_VALUE

Comment: @vipin.huddar Really? Oracle 11gR2 tells me "no such function". Where in the Oracle docs did you find this?
Comment: Will this work? `SELECT COLUMN_VALUE FROM TABLE(split('A,B,C,D,E,F', ','))` By the way what Oracle version do you use?
Comment: As u can see, I already tried doing this. I want corresponding value of 'name' column also.
Comment: Ohh, I meant, I want corresponding value of 'ID' column also.
Comment: What is split? Is this a function you're supposed to write?
Comment: @Frank: split function is available in Oracle after versions 10G.
Comment: See [**Split comma delimited strings in a table in Oracle**](https://lalitkumarb.wordpress.com/2015/03/04/split-comma-delimited-strings-in-a-table-in-oracle/)
Answer: Try using below query:
 WITH T AS (SELECT 'A,B,C,D,E,F' STR  FROM DUAL)   SELECT
 REGEXP_SUBSTR (STR, '[^,]+', 1, LEVEL) SPLIT_VALUES  FROM T
 CONNECT BY LEVEL <= (SELECT LENGTH (REPLACE (STR, ',', NULL)) FROM T)

Below Query with ID:
WITH TAB AS
(SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
)
SELECT    ID,
REGEXP_SUBSTR (STR, '[^,]+', 1, LEVEL) SPLIT_VALUES  FROM TAB
CONNECT BY LEVEL <= (SELECT LENGTH (REPLACE (STR, ',', NULL)) FROM TAB);

EDIT:
Try using below query for multiple IDs and multiple separation:
WITH TAB AS
(SELECT '1001' ID, 'A,B,C,D,E,F' STR FROM DUAL
UNION
SELECT '1002' ID, 'D,E,F' STR FROM DUAL
UNION
SELECT '1003' ID, 'C,E,G' STR FROM DUAL
)
select id, substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name
from
( select ',' || STR || ',' as STR, id from TAB ),
( select level as lvl from dual connect by level <= 100 )
where lvl <= length(STR) - length(replace(STR, ',')) - 1

order by ID, NAME

Comment: I want value from 'ID' column as well.
Comment: @user2531405: What is the maximum number of commas expected in your name column?
Comment: Not fixed. There can be any number of comma separated values, for a particular ID.
Comment: @Nisha This won't work for multiple IDs in the input data (single-row subquery returns more than one row) - I think you need to add a WHERE clause for the ID in your subquery for the LENGTH.
Comment: Thanks for the help, I got some direction. But value of ID is hard coded, which will not be the case with me. Ya, and as Frank said, it will not work for multiple IDs.
Comment: You can just replace the with clause with your table name. IDs need not be hardcoded. Check the latest edit. Its generic.
Answer: There are multiple options. See Split comma delimited strings in a table in Oracle.
Using REGEXP_SUBSTR:
SQL> WITH sample_data AS(
  2  SELECT 10001 ID, 'A,B,C' str FROM dual UNION ALL
  3  SELECT 10002 ID, 'D,E,F' str FROM dual UNION ALL
  4  SELECT 10003 ID, 'C,E,G' str FROM dual
  5  )
  6  -- end of sample_data mimicking real table
  7  SELECT distinct id, trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
  8  FROM sample_data
  9  CONNECT BY LEVEL <= regexp_count(str, ',')+1
 10  ORDER BY ID
 11  /

        ID STR
---------- -----
     10001 A
     10001 B
     10001 C
     10002 D
     10002 E
     10002 F
     10003 C
     10003 E
     10003 G

9 rows selected.

SQL>

Using XMLTABLE:
SQL> WITH sample_data AS(
  2  SELECT 10001 ID, 'A,B,C' str FROM dual UNION ALL
  3  SELECT 10002 ID, 'D,E,F' str FROM dual UNION ALL
  4  SELECT 10003 ID, 'C,E,G' str FROM dual
  5  )
  6  -- end of sample_data mimicking real table
  7  SELECT id,
  8        trim(COLUMN_VALUE) str
  9  FROM sample_data,
 10       xmltable(('"'
 11          || REPLACE(str, ',', '","')
 12          || '"'))
 13  /

        ID STR
---------- ---
     10001 A
     10001 B
     10001 C
     10002 D
     10002 E
     10002 F
     10003 C
     10003 E
     10003 G

9 rows selected.

Answer: i solved similar problem this way...
    select YT.ID,
           REPLACE(REGEXP_SUBSTR(','||YT.STR||',',',.*?,',1,lvl.lvl),',','') AS STR
    from YOURTABLE YT
    join (select level as lvl
          from dual
          connect by level <= (select max(regexp_count(STR,',')+1) from YOURTABLE)
         ) lvl on lvl.lvl <= regexp_count(YT.STR,',')+1

Answer: You may try something like this:
CREATE OR REPLACE TYPE "STR_TABLE"
as table of varchar2

create or replace function GetCollection( iStr varchar2, iSplit char default ',' ) return STR_TABLE as
pStr varchar2(4000) := trim(iStr);
rpart varchar(255);
pColl STR_TABLE := STR_TABLE();
begin
   while nvl(length(pStr),0) > 0 loop
         pos := inStr(pStr, iSplit );
         if pos > 0 then
            rpart := substr(pStr,1, pos-1);
            pStr  := substr(pStr,pos+1,length(pStr));
         else
            rpart := pStr;
            pStr := null;
         end if;
         if rpart is not null then
           pColl.Extend;
           pColl(pColl.Count) := rpart;
         end if;
   end loop;
   return pColl;
end;

Comment: Can't I do it through a single query, as I want to avoid adding a new function or something like that on my required DB environment.
Answer: Do not use CONNECT BY or REGEXP which results in a Cartesian product on a complex query. Furthermore the above solutions expect you know the possible results (A,B,C,D,E,F) rather than a list of combinations
Use XMLTable:
SELECT c.fname, c.lname,
trim(COLUMN_VALUE) EMAIL_ADDRESS
 FROM
  CONTACTS c, CONTACT_STATUS s,
  xmltable(('"'
  || REPLACE(EMAIL_ADDRESS, ';', '","')
  || '"'))
where  c.status = s.id

The COLUMN_VALUE is a pseudocolumn that belongs to xmltable. This is quick and correct and allows you to reference a column w/o know its values.
This takes the column and makes a table of values "item","item2","item3" and automatically joins to its source table (CONTACTS). This was tested on thousands of rows
Note the ';' in the xmltable is the separator in the column field.
Answer: I tried the solution of Lalit Kumar B and it worked so far. But with more data I ran into an performance issue (> 60 Rows, >7 Level). Therefore I used a more static variation, I would like to share as alternative.
WITH T AS (
      SELECT 1001 AS ID, 'A,B,C' AS NAME FROM DUAL
UNION SELECT 1002 AS ID, 'D,E,F' AS NAME FROM DUAL
UNION SELECT 1003 AS ID, 'C,E,G' AS NAME FROM DUAL
     )   --SELECT * FROM T
SELECT ID as ID,
       distinct_column AS NAME
  FROM ( SELECT t.ID,
                trim(regexp_substr(t.NAME, '[^,]+', 1,1)) AS c1,
                trim(regexp_substr(t.NAME, '[^,]+', 1,2)) AS c2,
                trim(regexp_substr(t.NAME, '[^,]+', 1,3)) AS c3,
                trim(regexp_substr(t.NAME, '[^,]+', 1,4)) AS c4 -- etc.
           FROM T )
UNPIVOT ( distinct_column FOR cn IN ( c1, c2, c3, c4 ) )

    ID NAME
------ ------
  1001 A
  1001 B
  1001 C
  1002 D
  1002 E
  1002 F
  1003 C
  1003 E
  1003 G

9 Zeilen gewählt

Comment: Fantastic. I was stuck with the performance of the `CONNECT BY` approach, and this way works perfectly as long as you know the max. number of elements in the string -- which you can check by something like: `select t.name, regexp_count(t.name, ',') from t group by t.name having regexp_count(t.name, ',') > 2;`
Answer: this version works also with strings longer than  one char:
select regexp_substr('A,B,C,Karl-Heinz,D','[^,]+', 1, level) from dual
  connect by regexp_substr('A,B,C,Karl-Heinz,D', '[^,]+', 1, level) is not null;

see How to split comma separated string and pass to IN clause of select statement


light web server to run on vps

Question: Has anyone tried to build a really light server that uses the least amount of space and memory, while giving high performance?
I would assume that linux kernel can be configured to keep only features that virtualbox, vmware or xen uses.
Gentoo with its USE flags might be the best option. But are there distros that are optimized specifically to run web servers under virtual machines?
Comment: feel free to correct me. I have experience with gentoo but I don't have experience maintaining a web server fro more than few days.
Answer: Or TinyCore with thttpd.
Answer: Damn Small Linux + lighthttpd
Doesn't get much more anorexic than that. I wouldn't bother with compiling your own kernel or stripping out too much, unless you're a kernel developer or want to be one. Unless you're running a web server on a wristwatch (or perhaps one of TomTom's mobile phones?), DSL should be small enough for you.
Comment: I thought DSL is not update these days.
Comment: @kirill_igum You didn't say anything about being up to date. =) mgorven's suggestion for TinyCore would be next best, IMO.

light web server to run on vps


How can I make my own white dot inlays?

Question: I have this old banjo mandoline and its dot inlays are just white stickers covering the holes. One of the stickers is missing and I actually want to replace all of the stickers by proper dot inlays. However, most companies (e.g. Allparts) sell their inlays by packs of 100 and I only need 4 (2X +/- 5.5mm - 7/32" & 2x +/- 8mm - 5/16")...
So any tips on materials from which I can make the dot inlays, how-to's or a webstore which sells them individually?
Many thanks!
Answer: You can make these a number of ways:

simplest: buy from any one of the hundreds of shops online that sell them (even though Allparts sells them by the 100, that's still around $10)
speak to a local luthier and ask if you can buy some from them
cut them from any flat white plastic (or any colour) - a hole punch of the right diameter is useful here
paint them - acrylic paint dripped into the hole, allowed to dry, and repeated until the hole is almost full, and then lacquer layered in on top

My recommendation is to go with the bag of 50 or 100 from an online shop. You may well mess up your first one or two, and it's not much money anyway.
Comment: Paint is actually easy - as long as you let each layer dry. Otherwise you are left with an uneven dot that just looks bad. As to which plastic - anything can work, even holes punched from credit cards, bits of metal, abalone from seashells etc
Comment: Well, you could find an elephant...
Comment: And then you'd be rightfully arrested and prosecuted, so best not go down the ivory route :-)
Comment: From memory of looking at old instruments,  I think these were often mother-of-pearl rather than ivory. Maybe you can find some old "worthless" jewellery in a junk shop and recycle the oysters one more time.
Comment: I'd recommend using tinted epoxy rather than layers of paint, as the latter never gets really hard.  Pick an epoxy that is *not* designed to be flexible :-) ; you should be able to mix in a little coloring while mixing the two agents.  Experiment first before filling the dots in your instrument!
Comment: Well, for Allparts I still have to pay for the shipping and that's the greatest downside (non-US resident). However, I have already searched (and maybe found) a distributor nearby! So it's 'regular plastic' that is being used? Was mostly wondering about the material to cut it from. Cool paint idea as well! Thanks!
Comment: I have found acrylic has worked well for me in the past, but I'm sure epoxy will work as well, yes.
Comment: All viable suggestions.  @alephzero- yes, mother of pearl is very often used for such buttons.  Two problems with it, though: one, it's rather difficult to work because it's very hard and brittle (much more so than bone) and two, you need to not breath the dust, which like asbestos particles, can cause problems in the lungs.  It can be done, however: the button must be filed and sanded into shape with everything kept wet.

How can I make my own white dot inlays?


Communication between Windows Store app and native desktop application

Question: ! For the sake of simplifying things I will refer to Windows Store applications (also known as Metro or Modern UI) as "app" and to common desktop applications as "application" !
I believe this is still one of the most unclear yet important questions concerning app-development for developers who already have established applications on the market:
How to manage communication between apps and applications on a Windows 8 system? (please let's not start a debate on principles - there're so many use cases where this is really required!)
I basically read hundrets of articles in the last few days but still it remains unclear how to proceed doing it right from the first time. Mainly because I found several conflicting information.
With my question here I'd like to re-approach this problem from the viewpoint of the final Windows 8 possibilities.
Given situation:

App and application run on same system
1:1 communication
Application is native (written in Delphi)
Administrator or if required even system privileges are available for the application
In 90% of the use cases the app requests an action to be performed by the application and receives some textual result. The app shouldn't be left nor frozen for this!
In 10% the application performs an action (triggered by some event) and informs the app - the result might be: showing certain info on the tile or in the already running and active app or if possible running the app / bringing it to the foreground.

Now the "simple" question is, how to achieve this?

Is local webserver access actually allowed now? (I believe it wasn't for a long time but now is since the final release)
WCF? (-> apparently MS doesn't recommend that anymore)
HTTP requests on a local REST/SOAP server?
WinRT syndication API? (another form of webservice access with RSS/atom responses)
WebSockets (like MessageWebSocket)?
Some other form of TCP/IP communication?
Sharing a text file for in- and output (actually simply thinking of this hurts, but at least that's a possibility MS can't block...)
Named Pipes are not allowed, right?

There are some discussions on this topic here on SO, however most of them are not up-to-date anymore as MS changed a lot before releasing the final version of Windows 8. Instead of mixing up old and new information I'd like to find a definite and current answer to this problem for me and for all the other Windows application and app developers. Thank you!
Comment: I wouldn't count on being able to communicate via a local file, either.  AFAIK, WinRT and the desktop currently share the same security token, but a split-token system similar to UAC would be sensible and might well be introduced in future versions of Windows.  (NB: I'm *speculating* here, this isn't based on information received.)  Besides, if MS do any sort of auditing of Windows Store apps, wouldn't you get kicked out once they noticed what you were doing?
Comment: @Harry Well I guess there's no way around trying it out... It's actually very sad to see how unwise MS treats this whole scenario of bringing applications and apps together. On the one hand they try to marry both worlds in one device - while pointing out that this is actually the best reason to choose a Win8 tablet. On the other hand they do everything to keep those worlds most possible apart. How foolish is that? Beats me.
Answer: If you are talking about an application going into the Store, communication with the local system via any mechanism is not allowed.  Communication with the local system is supported in some debug scenarios to make app development easier.
You can launch desktop applications from Windows Store applications with file or protocol handlers, but there is no direct communication.
So, to reiterate the point... communication between WinRT and the desktop is not allowed for released Windows Store applications.  Communication between the two environments is allowed in debug only.
The PG has posted in different places reasons for why communication is not allowed, ranging from security, to the WinRT lifecycle (i.e., you app gets suspended - how does that get handled re: resources, sockets, remote app, etc. -- lots of failure points) and the fact that Store apps cannot have a dependency on external programs (i.e., I need your local desktop app/service for the app to run, but how do I get your app/service installed?  You cannot integrate into the Store app.  You can provide another Store desktop app entry, but that is a bad user experience.)  Those are high level summaries, of course.
Comment: It can be done through a file - that's not blocked. Not saying its pretty, but it is possible. I also thoug a named pipe would work, but Im not sure on that.
Comment: Jeff, how sure are you on this? The ridiculous thing is that one cannot try it out because the behavior is apparently different for development and installed apps from the store... And since there are lots of useful use cases for this scenario, saying "Not possible" is basically not a solution. In the end developers will really work around this by passing commands and results through text files in localStorage. Is that really the only solution MS would allow?
Comment: @DominicHopton correct on files, though that is not really direct communication :)  AFAIK named pipes do not work.  That is based on statements made by the PG earlier.  Perhaps something changed, but I am not aware of any changes.
Comment: @CodeX  I am 98.72356% sure. :)  Unless a change slipped into RTM that I missed, that has always been the position of the PG for a long time.  Understood there are a lot of useful scenarios, but no communication is my understanding.  You can find some discussions around the web from the PG on why they have done this. I edited answer above to include some reasons.  Sorry that it not the answer you wanted, I will pass feedback along for consideration in future releases.
Comment: The behavior should be the same - the one exclusion is loop back, which one manually enable. If you wanna test it, don't enable it. If all else fails deploy the package rather just letting VS F5 deploy.
Comment: A couple of days ago Embarcadero released Delphi XE3 which comes with a component named "MetropolisSvc / TLiveTile". Please have a look at its [description](http://docwiki.embarcadero.com/RADStudio/en/Live_Tile_Support_for_Metropolis_UI_Applications).
Quote: "MetropolisSvc: This service application is a local REST service, and communicates between your application and your Live Tile."
How does it work then if no local communication is allowed? They use it for communication with the app tile but I don't think there's a difference to the app itself.
Comment: @CodeX  Did a quick scan... Metropolis UI is not a WinRT app... it is a desktop app that looks like a WinRT UI app.  From the site... "Only Metropolis UI desktop applications are supported in XE3. Metropolis UI mobile applications (and WinRT) are not currently supported. "  XE3 is specifically not supported in WinRT apps - notice only their desktop applications support XE3.  XE3 is a way for desktop apps to create/update a custom "LiveTile" on the  Start screen - it not communication between WinRT and the desktop.
Comment: @Jeff You're right with "Metropolis UI is not a WinRT app", however I wasn't talking about "Metropolis UI" but about "MetropolisSvc". They should work independantly. As for my understanding the live tiles on the start screen run in the same (or at least similar) context as the WinRT apps, don't they? So why are the tiles then allowed to communicate with a local webservice? They're located in the "Modern/Metro" world but somehow communicate with a service in the desktop world.
Are you saying that tiles and apps have different permissions?
Comment: @CodeX  No, tiles themselves are not WinRT apps.  For example, I have a tile for Outlook, Word, etc - but those are native apps.  Start Tiles are kind of just icons on steroids. From what I can determine, and I could be wrong, the XE3 stuff is just creating a custom "icon" that is created to look like a Tile, if that makes sense.  At the end of the day, there is no communication between the MetropolisSvc and WinRT.  That is why their docs say you cannot use MetroplisSvc with a WinRT app.
Comment: @Jeff There are two types of tiles. Static tiles and live tiles. While the first ones are basically shortcurts in a sqared tile form (they can be created by and for every desktop program as well), the latter ones are more apps than just icons. They have different layouts and settings for updates - but are actually limited to pre-defined preferences as they can't contain _everything_. Maybe that's the reason they're allowed to get their info updates from localhost? I quote again: "This service application is a local REST service, and communicates between your application and your Live Tile."
Comment: @CodeX that would go against everything I know about communication between the two environments.  I have not seen a single application that works that way.  I think they are generating custom Static tiles that they just replace via the service to mimic a Live Tile.  Their own docs specifically state their service DOES NOT work with WinRT applications.
Comment: I'm surprised by the black and white answer - one of the examples given was app communication with a locally hosted webserver...is this seriously not possible?
Comment: The reasons you mention for disallowing access to local services apply exactly the same for services hosted on the internet, but those are allowed.  From the perspective of managing the interactions, whether the service is local or on the internet is transparent.
Comment: IT should be mentioned that all limitations only apply if you try to distribute your app over the store. Sideloaded apps can communicate with a local service.
Comment: How about App to App communication using the [Share mechanism](https://msdn.microsoft.com/en-us/windows/uwp/app-to-app/index) - using it, maybe send JSON or XML data for example


How to apply improved Euler method to a systems of differential equation?

Question: I have the following problem (linearized pendulum problem):
$x_1'=x_2$
$x_2'=-\frac{g}{L}*sin(x_1)$
with the following initial condition:
$x_1(t_0)=0$
$x_2(t_0)=0$
Improved Euler Method says that:
$Y_{k+1}=Y_k+\frac{h}{2}*[f(t_k, Y_k)+f(t_{k+1}, Y_k+h*f(t_k, Y_k))]$
In this case I have done the following:
$x_{1, k+1}=x_{1, k}+\frac{h}{2}*[x_{1, k}+(x_{1, k}+h*x_{1, k})]$
$x_{2, k+1}=x_{2, k}+\frac{h}{2}*[-\frac{g}{L}*sin(x_{1, k})+-\frac{g}{L}*sin(x_{1, k}+h*(-\frac{g}{L}*sin(x_{1, k}))))]$
Where is my mistake?
Comment: Why do you think there's a mistake?
Comment: @caverac: I've been using it in a MATLAB code and it differs very much from the exact solution. That's why I have supposed that the method I've written is mistaken.
Comment: How could you notice a difference? It should be all zero with these initial values.
Answer: One of the most common problems in numerical integration is the time step. Make sure it is small enough so the system does not explode. Beyond that here are a couple of tips

The system has a fixed point at $(x_1, x_2) = 0$. That means that if your initial condition starts there, the system will not move
Define a function that takes x (array) and returns dx (array) with dx[1] = x[2] and dx[2] = - g * sin(x[1]) / l. This way is simpler to evaluate the system, and your code is easier to debug
Here's a solution using $h = 0.01$ in python, just for reference
Answer: You have to use the correct right side for the increments of the variables. If
$$
x_1'=f(x_2)\\
x_2'=g(x_1)
$$
then the method step reads
$$
x_{1,k+1}=x_{1,k}+\frac h2[f(x_{2,k})+f(x_{2,k}+hg(x_{1,k}))]\\
x_{2,k+1}=x_{2,k}+\frac h2[g(x_{1,k})+g(x_{1,k}+hf(x_{1,k}))]\\
$$
To keep track of these mixings you can either use a vector-based code or compute the steps like in the standard formulation of Runge-Kutta methods,
\begin{align}
Δ_1x_1 &= f(x_{2,k})Δt,&   Δ_1x_2 &= g(x_{1,k})Δt,\\
Δ_2x_1 &= f(x_{2,k}+Δ_1x_2)Δt,&    Δ_2x_2 &= g(x_{1,k}+Δ_1x_1)Δt,\\[2em]\hline
x_{1,k+1}&=x_{1,k}+\frac{Δ_1x_1+Δ_2x_1}2,&x_{2,k+1}&=x_{2,k}+\frac{Δ_1x_2+Δ_2x_2}2.
\end{align}


how to make rest requests with kafka and an api gateway

Question: I'm new to event driven architecture and have a very basic question about Microservices communication.
Given I have a website that has to make REST requests to an API Gateway. Say it does a fetch() to request some resource. How do I get a response or error in an event driven system?
Does Kafka accept rest requests and waits for a given event message from a service?
Answer: By default Kafka uses TCP. It does not have REST API endpoints.
However, for example, if created your Kafka cluster by Strimzi, you can use REST API by adding Kafka Bridge.
Here is an example using Strimzi Kafka Bridge.

Depending on how you created your Kafka cluster, you may find corresponding ways to expose REST API endpoints.
Reference: https://strimzi.io/docs/bridge/latest/
Answer: No, Kafka doesn't accept REST requests. It has a custom TCP protocol, not HTTP(S). You could use Kafka REST Proxy behind some API Gateway to solve this...
You track HTTP errors from the client, typically, unless the gateway has its own embedded metric collection.


How to reliably retrieve product attribute data?

Question: On a site where I started with WooCommerce version 2.. and then upgraded through newer releases (3.0.0, 3.0.1, ... 3.0.4), I'm noticing an inconsistency in how the order item meta data is stored for product attributes.
When using an attribute "Class Date" for variations, when an order is placed for some products in the store, the meta data for Class Date is stored using the key "pa_class-date".  But for other products, the data for that same attribute is stored using the key "class-date".
My code for fetching attribute data looks like this:
$items = $order->get_items();
if ( isset($item['item_meta']['class-date']) ) {
    $class_date = $item['item_meta']['class-date'];
} elseif ( isset($item['item_meta']['pa_class-date']) ) {
    $class_date    = $item['item_meta']['pa_class-date'];
} else {
    error_log("Missing class date. We tried pa_class-date and class-date, but both are empty");
}

I would like to be able to simplify this to just look in one key or the other (pa_class-date or class-date, not both). Is that possible?
Here is what a dump of the order meta data looks like for the purchase of two different products. This one uses pa_class-date.
[467] => stdClass Object
    (
        [key] => pa_class-date
        [value] => 2017-09-01
        [display_key] => Class Date
        [display_value] =>
2017-09-01

    )

But for a different product, the data stored using the key "class-date":
26-Apr-2017 16:26:06 UTC] Array
(
    [480] => stdClass Object
        (
            [key] => class-date
            [value] => 2017-05-18
            [display_key] => Class Date
            [display_value] =>
2017-05-18

        )

What causes the inconsistency in which key is used to store the data?
What is the most reliable (futureproof) way to retrieve the data?
Comment: Heads up that `$order->get_items();` now returns and array of `$item` *object* and you should start using the getter methods on it in lieu of accessing it like an array.
Answer: This inconsistency is possible. But its inconsistent data entry rather. When you add attribute to Products >> Attributes, they become part of woocommerce system. Then you can map them to variation by just selecting on product details page.
However, when you add "Custom Attribute" directly from product details page, that data will be specific for that product and can cause inconsistency.
Comment: Thank you. That explains it. I deleted the attribute from the classes that were using "class-date" as the key then added the attributes back using Product >> Attributes then configured the variations again. After that, the product now stores the data using pa_class-date.
Comment: I am glad it helped!


Linear Algebra Book with good proofs

Question: I'm taking a first course in Linear Algebra as an undergraduate.
I started reading Linear Algebra-A Geometric Approach by S Kumaresan.
I've been wondering if the proofs are too rigorous and formal and long.
I would like to know if Axler's Linear Algebra Done Right would be a better book to follow.
Comment: Adler? Do you mean, Axler?
Comment: Is it a good idea to couple Strang's Introduction to Linear Algebra with LADR? And give up Kumaresan's book altogether?
Comment: I am a huge fan of Adler's Linear Algebra Done Right and would really recommend going for this one! However, Adler's book is for a second course in Linear Algebra and so you might find it goes too fast if you haven't done any before. Either way it's definitely worth owning a copy.
Comment: I've done two chapters from Kumaresan's book so I have a rough idea of the concepts.I just wish the proofs were more intuitive.Should I be looking at simpler intuitive proofs or more formal long ones if I want to learn the subject well? Thank you!
Comment: I would give up on Kumaresan, if you look on amazon it has 59% 1 star reviews. I had a quick look through and it's not how I would want to learn linear algebra. LADR and Strangs book together should be all you need.
Comment: Woops yes Axler is right, Thanks!
Comment: Okay, will do that.Thank you so much!
Comment: I think Strang's linear algebra books do a great job of conveying intuition and showing how simple/easy linear algebra is. Then another book such as Friedberg can develop the theory for abstract vector spaces.
Answer: I agree wholeheartedly with the commenters; Axler's Linear Algebra Done Right is the best linear algebra book I have read, and one of the best books ever.

Linear Algebra Book with good proofs


What are the values of $x$ such that $\cos x \lessgtr \sin x$?

Question: How can I find all values of $x \in [0, 2\pi]$ such that $\cos x > \sin x$ and, similarly, considering the same interval, the values which satisfy $\cos x < \sin x$?
My initial attempt was to divide both sides of the inequality by $\cos x$:
$$\tan x < 1$$
What should I do next? Is this path correct?
Comment: Hint: You can get this information from the unit circle directly.
Comment: You can divide both sides of an inequality  only if you know the divisor is positive. If the divisor is negative, you have to reverse the inequality.
Comment: Instead of dividing that causes inequalities to reverse when $\cos x$ changes sign, better use $\cos(x)-\sin(x)=\sqrt{2}\sin(x+\phi)$ and it is quite easy to study $\sin(x+\phi)$ sign.
Answer: HINT: Be careful with the division on both sides, as $\cos(x)$ changes sign in the interval you are considering. Actually, even $\sin(x)$ changes sign.
You could also try to solve the inequality with a graphical method, plotting the two functions $\sin(x)$ and $\cos(x)$ on a paper and seeing where one of them is greater than the other.


how to reject droppable element in container with the help of jQuery?

Question: My jsfiddle is http://jsfiddle.net/aNreg/44/
Now I can drag and drop some elements, but I want to reject one element from container.
Comment: Why have you tagged this as having php?
Comment: [Please make your question self-contained and include the relevant parts of the code](http://meta.stackexchange.com/questions/114942/when-jsfiddle-and-other-related-sites-are-gone-so-is-the-information)
Answer: Please check updated code:
http://jsfiddle.net/aNreg/111/
Your divs had the same id shoppingCart1 and droppable function can be added to selector .shoppingCart ol instead of each id.
Comment: No bro this is working... but not as per my requirement. i want to the numbers like 400 200 300 500 700 from this number one number should be dragable but not dropable, understand?


Cleaner way to wrap up jquery functions

Question: I am building a brand editing screen with a jQuery powered preview of your colour changes.
I have set up some jQuery functions as follows but need several more of the same and was wondering if there is a cleaner way to write it to reduce repetitiveness.
<code>$('input[name="p-color"]').keyup(function() {
  var pColor = ($(this).val());
  $('.custom-style-demo p').css({"color":pColor});
});
$('input[name="heading-color"]').keyup(function() {
  var headingColor = ($(this).val());
  $('.custom-style-demo h1, .custom-style-demo h2, .custom-style-demo h3').css({"color":headingColor});
});
</code>
http://codepen.io/rachelreveley/pen/akVkxK?editors=1010
Comment: CodeReview might be a better place for this...but check their guidelines first.
Comment: Not seen that before. Thanks.
Answer: You can use named callbacks for your event listeners:
<code>$('input[name="p-color"]').keyup(pColor);
$('input[name="heading-color"]').keyup(hColor);

function pColor() {
  var pColor = ($(this).val());
  $('.custom-style-demo p').css({"color":pColor});
};

function hColor() {
  var headingColor = ($(this).val());
  $('.custom-style-demo h1, .custom-style-demo h2, .custom-style-demo h3').css({"color":headingColor});
};
</code>
Then you can reference the same callback with multiple events.

Cleaner way to wrap up jquery functions


Double Sharps in Just Intonation. The mathematics?

Question: So I'm experimenting around and I'm creating a small little thing in C#### minor just because. I understand the mathematics of C#### in Pythagorean and Equal Temperment music systems but how do you represent multiple accidentals in the Just Intonation system? Like Gbbb is mathematically different than E.
Thank you!
Answer: Unfortunately, it's a bit more complicated than that. There is no single "Just Intonation System"; instead, there are multiple systems which can be said to be just, by virtue of the fact that they use just intervals (i.e. integer frequency ratios). The problem is in determining which ratios you want to use.

One such Just system is the Pythagorean system, which only uses Just perfect fifths (a ratio of 3/2, or ~702 cents) and just octaves to generate all the notes of the scale. To find the mathematical ratio for any note, you just count how far it is from your reference note, along the line of fifths, and multiply by that power of (3/2). You can also multiply/divide by arbitrary powers of 2 (raise or lower by octaves) to get the resulting ratio into the desired octave.
...B♭♭ - F♭ - C♭ - G♭ - D♭ - A♭ - E♭ - B♭ - F - C - G - D - A - E - B - F♯ - C♯ - G♯ - D♯ - A♯ - E♯ - B♯...
So, for example, B♭♭ is 12 fifths below A, so these notes differ by a ratio of 2k * (3/2)-12 (where k is whatever factor is needed to make the ratio close to 1). The result ends up being the Pythagorean Comma.

Another Just system is Quarter Comma Meantone, which only uses Just major thirds (a ratio of 5/4, or ~386 cents) and just octaves to generate all the notes of the scale. To find the ratio for notes in this scale, you can count how many fifths it is on the line of fifths, and multiply by that power of 51/4. As usual, octave shifts are permitted. You can also construct a line of thirds, each of which is a ratio of (5/4) from the previous, but it will only have a quarter of the notes. The other notes are equally distributed in between (hence the fifths being the fourth root of five: four stacked fifths is octave-equivalent to a third).
...F♭ - A♭ - C - E- G♯ - B♯...

What you might be referring to as "just intonation" is what wikipedia calls "5-limit tuning". This uses a combination of Just perfect fifths (3/2) and Just major thirds (5/4), as well as octaves (2/1), to define notes. If the previous two systems can be depicted with one-dimensional lines, then this system can be depicted with a 2D lattice known as the Tonnetz. Moving one step to the right along this graph represents multiplication by (3/2), while moving up one step represents multiplication by (5/4).
<code> F  --{C} -- G  -- D  -- A -- E -- B -- F#
 |     |     |     |     |    |    |    |
[Db]-- Ab -- Eb -- Bb -- F --(C)-- G -- D
 |     |     |     |     |    |    |    |
 Bbb-- Fb -- Cb -- Gb --[Db]- Ab-- Eb-- Bb
 |     |     |     |     |    |    |    |
 Gbb-- Dbb-- Abb-- Ebb-- Bbb- Fb-- Cb-- Gb--[Db]
</code>
The problem is that there are many ways to get to any given note, and the resulting ratios from these different routes don't agree. In fact, every note will show up once per row, but in each row, it will have a different pitch. (Note: I'm going to be a bit sloppy by not explicitly counting octave shifts (factors of two) and just using 2k as a placeholder, as I did above. These k's are not necessarily all equal).
For example, from the parenthesized (C), you can get to another {C} by going down four fifths and then up a major third. The ratio between these C's is therefore: 2k * 3-4 * 5. Since this number cannot equal 1, the two C's must have different frequencies. In fact, the result is 81/80, which is called the Syntonic Comma. A chord progression which starts with one definition of (C), and ends up with a different definition of {C} has drifted pitch by a comma, despite singing only just intervals. This type of progression is called a Comma Pump.
Similarly, I've noted multiple instances of D♭, which have ratios (relative to (C)) of:

2k * 3-5
2k * 3-1 * 5-1
2k * 33 * 5-2

Again, because these numbers are different, the resulting notes are different (each by a syntonic comma). I will leave it as an exercise to extend this system to Gbbb or C####, and determine the multiple sets of interval combinations which produce these notes. Which one is "right"? All of them. Or perhaps none of them. In this kind of system, every time you use a note, you need to look at your context to determine how the note is being used, in order to figure out which version of the note should be used.
Comment: Thank you! Yes I am referring to 5-limit-tuning. It is pretty simple in the other tuning systems you listed. It gets even worse when it comes to like 17-limit tuning and things. So you just set up a big table? I get the fact that it sorta depends on when you need the note upon if it's right, but do you mean based upon key or in general? Like is there a correct C## in C major? Because I assume that for my C#### minor, I'd be transposing from A minor directly into that.
Comment: I don't know that there's any way to define a single one as being right, other than defining the specific intervallic relationship you want. In this case, there's no simple intervallic relationship between A and C####, in fact, the later is much more likely to be interpreted as an out of tune version of E, which *does* have a simple relationship (a fifth above) rather than a triply-augmented third. I can't think of any context in which the later interval even makes sense.
Comment: However, if you want to find a version of this note without reproducing the entire chart, you can find the nearest simple enharmonic (in this case, a fifth higher, at E = (3/2)), then create a chain of major thirds (up or down) to get to the desired spelling: E-G#-B#-D##-F###-A###-C#### = (5/4)^6. Then you can get to other versions of that note by multiplying (or dividing) by the syntonic comma (81/80) as many times as desired to put it in the desired row. The final result is: A * (3/2) * (5/4)^6 * (3^4/(5*2^4))^k (for any integer k).
Comment: I could be wrong but what I've found with meantone, and probably applies to pure intonation is you just need to decide what a chromatic semitone is. If you've decided that C to C# is 25/24, then C to C### is going to be (25/24)^3.
It's also worth remembering that playing in C### is kinda pointless, you could just as well say you are e.g. playing in C but A = 497Hz or whatever it is and get the same result.


Understanding loops in-conjunction with if/elif/else statements (Python)

Question: Evening all,
I'm new to programming and I am attempting to understanding while loops that are used with if/elif/else statements.
My Thought Process
The function that I have created is a part of the game Tic Tac Toe (or Noughts and Crosses). The idea behind the function is to prompt Player 1 for their symbol choice (O or X).
My logic behind the function is such that, the player will continue to be prompted (the loop) for a valid choice. Once the player has made a valid choice, the loop should end and print the player's choice.
My Question
What I don't understand is that the function only works if I include break at the end of both the IF and ELIF blocks of code. Why won't the loop break upon the user entering a valid choice?
Please see the code, written in Python, below.
Regards,
def player_input():
    player1_input = str
    player1_symbol = str

    while player1_symbol != "X" or "O": #loop until user supplies an valid (X or O) input
        player1_input = str(input("\nPlayer 1, would you like to be X or O?:  ")) #prompt user for their choice
        player1_symbol = player1_input #link player1_input to player1_symbol

        if player1_symbol == "X": #follow this block if Player 1 selected X
            print("\nPlayer 1: You are now X") #states that Player 1 is X
            print("Player 2: You are now O") #states that Player 2 is now O as a result of Player 1's choice
            print("IF Statement Executed") #lets me know that this block was executed
            break #WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE?

        elif player1_symbol == "O": #follow this block if Player 1 selected O
            print("\nPlayer 1: You are now O") #states that Player 1 is O
            print("Player 2: You are now X") #states that Player 2 is now O as a result of Player 1's choice
            print("ELIF Statement Executed") #lets me know that this block was executed
            break #AGAIN, WHY DO I NEED THIS TO BREAK THE LOOP IF A VALID SELECTION WAS MADE

        else:
            print("\nInvalid choice. Please choose X or O.") #lets Player 1 know that he needs to make a valid (X or O) input
            print("ELSE Statement Executed") #lets me know that this block was executed

Comment: "X" or "O" is not the preferred nomenclature, you may find `while player1_symbol != "X" and player1_symbol !="O"` to work better for you. Or more succinctly `while player1_symbol not in ["X","O"]`
Comment: `while player1_symbol != "X" or "O":` is almost certainly not what you meant
Comment: Thanks @Chris, the ' while player1_symbol not in ["X","O"] ' is quite handy.
Answer: The comment gives the appropriate fix. To understand why this is happening, note that the or operator combines two separate logic statements. In your case, these two logic statements are player1_symbol != "X" as well as "O". Because the latter statement is nonzero, python always evaluates it as True so that the entire statement player1_symbol != "X" or "O" is always true, no matter the value of player1_symbol.
Edit: To be clear what I mean by "the latter statement is nonzero", I mean the ASCII value for the character "O" is nonzero, so python evaluates it as true.
Comment: So it should be fixed like this: player1_symbol != "X" or player1_symbol != "O"
Comment: This is the correct answer, the condition is not well formulated:


Create a reference all available block content

Question: In Drupal 7 there is Block Reference field module that can reference pretty much all available blocks, including views' blocks, system blocks, menu blocks etc.
I'm just starting with Drupal 8 and since the Block Reference module doesn't have a version for it, and the built-in Entity Reference doesn't seem to pick up views' blocks, system blocks, I want to create a new custom block type. In this new block type, I want to have a reference field that can reference all available block content.
Is there a way to do it?
Answer: Like I said, I'm new to Drupal 8 so not familiar with new rule and features. After a bit digging here is what I found out.
Entity Reference field allows to reference block instances (config) or custom blocks (content).
Before I was set my field to Content > Custom block, now I switch it to Configuration > Block then you have to Place the block that you want to reference to, even if it is in disabled. After that, you can have your Entity Reference field pick that up otherwise it won't show.
You can have a look at here for more detail.
Comment: Forgive my tardiness, I just find out that you can reference a block instance but it can't be in disabled state : ( it won't show with "Restrict access" message. If I create a custom block type that display some block instances, those instances have to be enabled. Then what is the point?! May be I misunderstand the concept. Anyway to workaround I create another block region but won't show in page and put all the instance that I want to reference to into this block region.
Comment: Wow. Both a good question and a pretty good answer. So this works even if block is disabled? All logic for block visibility can be done in code?
Comment: Did you ever find another solution?  Seems odd to have to enable another unused block region, I wonder if that is the expected use?  There may be some better way to be going about this?  I will post back if I find anything.
Answer: To fix the restricted access: make a region in yourtheme.info. Don't render the region in your page.html.twig.
Place the config block in that region.
Comment: FYI: https://drupal.stackexchange.com/questions/186968/restricted-access-on-reference-field-type


How to prove these problems? (Operation on N)

Question:
If $m+n = m+k$, then $n=k$.
If $mk = nk$ and $k\neq0$, then $m=n$.

I'm not sure what t do. Do I have to use math induction or not? (Base on Peano system)
Answer: If you want to prove these sort of things in Peano, then using induction is probably a strong candidate for the first attempt.
To prove the on about addition, use induction on $m$. Note that this requires you to know that $x+y=y+x$ first, which you can also prove using induction. Similarly, the multiplication should be proved by induction on $k$.


If $ \displaystyle \frac{h}{k} $ and $ \displaystyle \frac{h'}{k'} $ are two consecutive terms of a Farey series, then $ h'k - hk' = 1 $

Question: I am learning about Farey series from Hardy and Wright Intro to Number Theory and they give the following theorem whose proof I currently have trouble understanding.
$ \textbf{Theorem 28} $: If $ \displaystyle \frac{h}{k} $ and $ \displaystyle \frac{h'}{k'} $ are two consecutive terms of $ \mathcal{F}_{n} $, then $ h'k - hk' = 1 $.
I am reading section 3.3 First proof of Theorem 28 and the proof, extracted from the book, is given below for convenience:
$ \textbf{Proof} $: The theorem is true for $ n = 1 $; we assume it true for $ \mathcal{F}_{n - 1} $ and prove it true for $ \mathcal{F}_{n} $. Suppose that $ h / k $ and $ h' / k' $ are consecutive in $ \mathcal{F}_{n - 1} $, but separated by $ h'' / k'' $ in $ \mathcal{F}_{n} $. Let $ h''k - hk'' = r > 0 $ and $ h'k'' - h''k' = s > 0 $. Solving these equations for $ h'' $ and $ k'' $ and remembering that $ h'k - hk' = 1 $, we obtain: $ h'' = sh + rh' $ and $ k'' = sk + rk' $. Here $ \gcd(r, s) = 1 $ since $ \gcd(h'', k'') = 1 $.
Consider now the set $ S $ of all fractions $ \displaystyle \frac{H}{K} = \frac{\mu h + \lambda h'}{\mu k + \lambda k'} $ in which $ \lambda $ and $ \mu $ are positive integers and $ \gcd(\lambda, \mu) = 1 $. Thus $ h'' / k'' $ belongs to $ S $. Every fraction of $ S $ lies between $ h / k $ and $ h' / k' $ and is in its lowest form since any common divisor of $ H $ and $ K $ would divide $ k(\mu h + \lambda h') - h(\mu k + \lambda k') = \lambda $ and $ h'(\mu k + \lambda k') - k'(\mu h + \lambda h') = \mu $.
$ \textbf{Hence every fraction of $ S $ appears sooner or later in some $ \mathcal{F}_{q} $; and plainly the first to} $
$ \textbf{make its appearance is that for which $ K $ is least, i.e. that for which $ \lambda = \mu = 1 $. This} $
$ \textbf{fraction must be $ h'' / k'' $ and so $ h'' = h + h' $ and $ k'' = k + k' $.} $
I am having trouble understanding the bold paragraph. What do they mean by "Hence every fraction of $ S $ appears sooner or later in some $ \mathcal{F}_{q} $; and plainly the first to make its appearance is that for which $ K $ is least" and why is that the case. Also, why does the fraction with $ K $ least must be $ h'' / k'' $?
Any help is appreciated
Comment: How do Hardy and Wright define the Farey sequence iteration: the way you get from $\mathcal F_n$ to $\mathcal F_{n+1}$? The way I've seen it defined, you simply insert $\frac{h+h'}{k+k'}$ between $\frac{h}{k}$ and $\frac{h'}{k'}$, so the statement in the bolded paragraph is part of the definition and the proof of this theorem follows from easy algebra.
Comment: My thought for the paragraph is that if I have two elements in $ S $, say $ \frac{\mu_{1} h + \lambda_{1} h'}{\mu_{1} k + \lambda_{1} k'} $ and $ \frac{\mu_{2} h + \lambda_{2} h'}{\mu_{2} k + \lambda_{2} k'} $, then the one to first make its appearance is the smaller one. And solving $ \frac{\mu_{1} h + \lambda_{1} h'}{\mu_{1} k + \lambda_{1} k'} < \frac{\mu_{2} h + \lambda_{2} h'}{\mu_{2} k + \lambda_{2} k'} $ yields $ \frac{\mu_{1}}{\lambda_{1}} < \frac{\mu_{2}}{\lambda_{2}} $, but this doesn't align with what they imply, so maybe my interpretation is incorrect.
Comment: He define the Farey series $ \mathcal{F}_{n} $ of order $ n $ is the ascending series of irreducible fractions between $ 0 $ and $ 1 $ whose denominators do not exceed $ n $, but he doesn't define how to go from $ \mathcal{F}_{n} $ to $ \mathcal{F}_{n + 1} $.
Answer: Okay, to expand on the bolded paragraph:
In the preceding steps, we've shown that if $\frac{h}{k}$ and $\frac{h'}{k'}$ are consecutive in $\mathcal F_n$ but not in $\mathcal F_{n+1}$, then any fraction $\frac{h''}{k''}$ that lies between them in $\mathcal F_{n+1}$ has to be of the form $\frac{h''}{k''} = \frac{\mu h + \lambda h'}{\mu k + \lambda k'}$.
So let $S = \left\{\frac{\mu h + \lambda h'}{\mu k + \lambda k'} : \lambda, \mu \ge 1, \gcd(\lambda,\mu) = 1\right\}$: the set of all things that $\frac{h''}{k''}$ could possibly be. Each element of $S$ is a fraction in simplest terms, so each element of $S$ appears in some Farey series. For example, $\frac{2h + 3h'}{2k + 3k'}$ appears in the Farey series $\mathcal F_{2k+3k'}$, by definition.
We know that none of the fractions in $S$ have appeared in $\mathcal F_n$ yet: if they did, they would be between $\frac hk$ and $\frac{h'}{k'}$, but we are told that $\frac hk$ and $\frac{h'}{k'}$ are consecutive in $\mathcal F_n$. On the other hand, at least one of the fractions in $S$ appears in $\mathcal F_{n+1}$: it's $\frac{h''}{k''}$. Therefore no fraction in $S$ has denominator $n$ or less, and $\frac{h''}{k''}$ is in $S$ and has denominator $n+1$ or less. It must have denominator exactly $n+1$, and this must be the least possible denominator of any fraction in $S$.
The least possible denominator of a fraction of the form $\frac{\mu h + \lambda h'}{\mu k + \lambda k'}$, where $\mu,\lambda \ge 1$, is obtained when $\mu = \lambda = 1$. So $\frac{h +  h'}{k + k'}$ is the (unique) fraction in $S$ with the least denominator, and therefore $\frac{h''}{k''} = \frac{h+h'}{k+k'}$.
Comment: Side comment: note that we didn't assume that $\frac{h''}{k''}$ is the *only* fraction between $\frac hk$ and $\frac{h'}{k'}$ in $\mathcal F_{n+1}$. This follows from the proof, because $S$ contains only one fraction with the least possible denominator of $k+k'$.


What are the 'primitive' accessors for in Core Data?

Question: From the Core Data Programming Guide (my emphasis):

By default, Core Data dynamically creates efficient public and primitive get and set accessor methods for modeled properties (attributes and relationships) of managed object classes.

Although I've been using Core Data and mogenerator happily since I started on Objective-C, I've never had a look at what this means, until an app submission got rejected due to alleged use of private API. Long story about a generated setPrimitiveTypeValue: method, but not what my question is about.
While reading the guide I stumbled on the idea of public and primitive accessors for entity attributes. Another quote, but further down:

For example, given an entity with an attribute firstName, Core Data automatically generates firstName, setFirstName:, primitiveFirstName, and setPrimitiveFirstName:.

What are the primitive accessors for? Is it just so you can assign a BOOL value directly, without wrapping it in an NSNumber? If so, why would mogenerator have gone through the trouble of generating all kinds of <Attribute>Value, set<Attribute>Value:, primitive<Attribute>Value, setPrimitive<Attribute>Value: accessors?
I'm confused, who can help me out?

Related questions:

Core Data Primitive Accessors (no answers)
why would I need to use a primitive accessor methods in a core data project? (answered)
Comment: Someone else [answered this one already][1] with what looks like a good answer.

  [1]: http://stackoverflow.com/questions/5509106/why-would-i-need-to-use-a-primitive-accessor-methods-in-a-core-data-project
Answer: As far as I understand it, the primitive method does the actual getting and setting, but does not issue any KVC or KVO notifications ('willAccessValueForKey' and so on). The public method calls the primitive method, but wraps the call in the KVO calls. So from outside the object, you'd typically call the public methods, but if you needed to use the properties of the object for internal reasons (to validate or derive some other property, for example) you would use the primitive methods to avoid firing all the notifications.
I'd welcome any corrections or clarifications on the answer as it is a subject I am interested in but not fully versed in.
Comment: Awesome answer @jrturton. Just adding this link as a reference if people want to have a quick look at [Custom Primitive Accessor Methods](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CoreData/Articles/cdAccessorMethods.html#//apple_ref/doc/uid/TP40002154-SW5) in the Core Data doc which backs up your answer.
Comment: @Mick that link is now obsolete.
Answer: @jrturton's answer covered issues regarding Custom Attribute and To-One Relationship Accessor Methods, where public-accessor is straightforward.
In addition, to fully support To-Many Relationship Accessors, in custom implementation, public-accessors may have to call primitive-accessors in combination with NSMutableSet methods  (unionSet: and minusSet:), which must be wrapped inside KVO method pairs ( will...did...).


Is there something wrong with my recording, I guess the timing sounds strange but I cannot tell exactly whats wrong

Question: Today I played guitar to a backing track, it is the song Drive by Incubus. When I listen to it something sounds strange, but I cannot tell. Might it be out of time?
Here is a link to my recording, but especially this intermediate part sound strange when I play the bass note of the guitar, it sound as it comes to late, but then the rest fits again.
So do I just imagine something, or is there an issue with the timing somehow??
I am no musical expert and far from being a real musician, but I try to improve myself and listen critically to my recording, so it would be a great help to figure out if there is something wrong with my playing. Thank you!
Answer: It's because the chord changes sometimes happens on the first beat of a measure, and sometimes on the second eighth of the 4th beat.
So if you're counting along you'd count "One and two and three and four and". So the chord change happens on the "and" after four, and not on the one. Pay close attention and count along with the song and see if you can notice this.
Comment: Okay, I guess I noticed. The A-chord in the intermediate part, where it changes between C and A, comes a little bit early (on the **and** before). But am I doing this wrong in my recording? I guess yes but I am not 100% sure??
Comment: Yeah, it's mostly noticeable in the measure before the first chorus. The chord switch happens on the off-beat of the fourth beat and you play it on the first best. That's why it sounds off timing or late to you as you describe it.
Comment: Thanks, guess I am noticing. Strange that I did not noticed anything as I was playing, but just when listening afterwards... but just to make it clear. We are talking about the C-A part before the chorus (the chorus goes "Whatever tomorrow [...]", and the C-A-part with "Its driven me before [...]") which is again on the progression Em-Em-C-A?
Answer: The rhythm is being 'pushed' half a beat earlier than it normally is. Instead of changing chord at the very beginning of the bar, it's coming in half a beat before. You can do this by playing the new chord on the upstrum that normally gets played there, or change it to a downstrum, which messes up the rhythmic pattern of the strumming arm.
It's a very common rhythm change, often with vocals; the Beatles featured it in a lot of songs, and it's almost expected in pop music - try singing some songs without the push, and they sound bland.
Comment: But this is not used on every chord change? The Em and C in the main riff start on the one, and the 2nd Em and the A in this riff slightly before. For the Pre-Chorus part, the C chord starts on one, and the A-chords the way you describe it, right?
Comment: It's not on every change,no. Your homework is to listen very carefully to determine exactly which changes it does occur on. That's a far better way to understand it than have it all on a plate!!
Comment: Surely, I guess I have it. Main-Riff: 1st Em and C on one, then 2nd Em and A 'pushed', in prechorus: C on one, A 'pushed'. Okay, now I hand in my homework! When do I get my corrected and annotated sheet back? :)
Comment: The 'verse' - 1st part of song - is on one, most of 'chorus' - next part - is pushed. If that's what you came up with, 10/10 !


How to send email from another address

Question: So I was wondering, how would I send my email from another email address in Laravel. Currently I have this email address and domain. This is an example. Sender = firstname.lastname@example.com
Now I have many auth()
users. I want to be able for them to send emails as well. So how would I do that? So for an example: email@example.com
My point is, currently the admin guard is able to send an email to the owner of the post who is user(). I have multi auth so admin is one guard and the other is the default.
So the admin is able to send email to email@example.com
 So how can I do it so that firstname.lastname@example.com can send an email back to email@example.com
Is this even possible?
Note: I am using mailgun.
Comment: Yes, just change env variables in runtime.
Comment: @PayamKhaninejad perhaps an example would work. What I am saying is to be able to use 2 domains. One is anotherdomain.com. And the other is domain.com. Auth user will send emails from anotherdomain.com and auth admin would send emails from domain.com
Answer: You have two option in this situation:
1) use email clients independently like Phpmailer or Swiftmailer
2) change the config file and email credentials on the fly(make sure your config isn't cached)
Accessing Configuration Values

How to send email from another address


How to skip form validation with ajax?

Question: I am building a form with tabledrag and ajax "add more" and "remove item" buttons.
I tried different variations with '#type' => 'button' and '#type' => 'submit'.
Currently, pressing one of those ajax button always triggers form validation and then a form rebuild. (this means every element is processed twice).
If a user wants to add a bunch of items with required values, then validation errors will block and disrupt the "add more" mechanic, or they will show up with the error colors, which is all undesirable.
I experimented a bit with '#limit_validation_errors', but I am not sure this does what I need. If I understand correctly, this only suppresses the error output, but the actual validation is still executed.
I looked at drupal_process_form(). The validation and rebuild happens here:
  $form = form_builder($form_id, $form, $form_state);

  // Only process the input if we have a correct form submission.
  if ($form_state['process_input']) {
    drupal_validate_form($form_id, $form, $form_state);
    [..]
      $form = drupal_rebuild_form($form_id, $form_state, $form);

This means the form is processed one time, then it is validated, and later it is built and processed again.
For my purposes, the entire validation and rebuild could be skipped.
I managed to implement the "add more" mechanic in a value callback, so I don't need a #submit handler on the ajax "add more" button.
The code in drupal_process_form() suggests that I could skip the validation and rebuild by setting $form_state['process_input'] = FALSE. However, this also suppresses the detection of $form_state['triggering_element'], which means that ajax_form_callback() won't work correctly anymore.
I might figure something out here, but perhaps there is something simpler that I missed.
I think the problem is the same as described here, https://www.drupal.org/project/drupal/issues/2476569.
But I am not going to wait for this issue to be done for D8 and backported  to D7. I am looking for something I can do right now.
Answer: You want #limit_validation_errors. Setting this value to an empty array will mean that nothing is validated when the button is clicked.
Comment: But the validation handlers are still executed, just the output is suppressed, right?
Comment: No, I don't believe that's the case
Comment: I just did a debugging session. #limit_validation_errors does not stop the validation, just suppresses the errors. `form_set_error()` is called for e.g. missing required fields, but then inside `form_set_error()` the `$record` variable will be FALSE, which suppresses the output.
Comment: I can confirm that #limit_validation_errors is sufficient for my needs. There might be performance issues on big forms or if there is expensive validation, but for me it is good enough.

How to skip form validation with ajax?


link field template syntax / display link field as an image / devel dpm (D7)

Question: My link field is currently displaying as a URL as you can see here (yellow border). I have added dpm($items) to my link field template file. How do I read the dpm output or more specifically how do I edit my template file to say "display this field as the specified image"?
The following example works in a different situation where the field is an uploaded file but in this case the field is a link.
<?php $path = $items[0]['#file']->uri; ?>
<a href="<?php print file_create_url($path); ?>">

Comment: In the example with the yellow border, the URL is a file in mp3 format. Do you want to display a play option for the mp3?
Comment: @ Collins thanks for your reply - I am using a separate field for an MP3 player so my question here is about the red button here http://imgur.com/NGoKJMt ie click the button to download the MP3 file - which is a link to the MP3 file (as opposed to a file I have uploaded). In my example above I thought that #file referred to an uploaded file ie a different field and a different situation - will #file apply where the field is a URL link?
Answer: I dont really understand what the problem is, If you are already outputting the link URL, and you want to display that as an image, surely you can just wrap it in an img tag?
<?php $path = $items[0]['#file']->uri; ?>

<img src="<?php print file_create_url($path); ?>" />

OR, with an mp3 file like in your example...
<?php $path = $items[0]['#file']->uri; ?>
<audio controls>
  <source src="<?php print file_create_url($path); ?>" type="audio/mpeg">
</audio>


Is this a closed embedding of schemes?

Question: Let $X$, $Y$ be two schemes and $f$ be morphism from $Y$ to $X$. Now, consider the corresponding morphism $Y \times_{X} Y$ to $ Y \times Y$. Is this a closed embedding?
Comment: By $Y\times Y$ do you mean $Y\times_{\operatorname{Spec}\Bbb{Z}} Y$?
Comment: Yes! I mean $Y\times_{\operatorname{Spec}\Bbb{Z}} Y$
Answer: If $X$ is separated over $\newcommand{\ZZ}{\mathbb{Z}}\newcommand{\Spec}{\operatorname{Spec}}\Spec\ZZ$, then yes.
Proof:
The following is a pullback diagram (see Vakil's notes, pg. 37, Ex 1.3.S):
$$\require{AMScd}
\begin{CD}
Y\times_X Y @>>> Y\times_{\Spec\ZZ}Y\\
@VVV @VVV\\
X @>>> X\times_{\Spec\ZZ}X\\
\end{CD}
$$
If $X$ is separated over $\Spec\ZZ$, then the bottom morphism is a closed immersion. Then since the base change of a closed immersion is a closed immersion, $Y\times_X Y\to Y\times_{\Spec \ZZ}Y$ is a closed immmersion.
Edit: As Marc Paul pointed out below, if $X$ is not separated over $\Spec\ZZ$, then if $Y=X$ and $f=\textrm{id}_X$, then the map $Y\times_X Y\to Y\times_{\Spec\ZZ} Y$ is just the map $X\to X\times_{\Spec\ZZ} X$, which is the diagonal map. By the assumption that $X$ is not separated over $\Spec\ZZ$, this is not a closed embedding.
For more on the general form of the pullback diagram above, see this nice MO answer.
Edit: in response to the further question below as to whether the map $Y\times_X Y\to Y\times_{\Spec\ZZ} Y$ is always a monomorphism, the answer is yes. In fact to be more precise, the map is always a locally closed immersion.
Proof: The morphism $X\to X\times_{\Spec\ZZ} X$ is always a locally closed immersion. For a justification, see the Stacks project. Locally closed immersions are preserved under base change, so $Y\times_X Y\to Y\times_{\Spec\ZZ} Y$ is a locally closed immersion. Finally immersions are monomorphisms.
Comment: If $X$ is not separated over $\mathbb Z$, I think you can just take $Y= X$  for a counterexample. Then $Y\times_X Y = X\times_X X = X$, and the morphism we consider is probably just the diagonal map $X\to X\times _\mathbb Z X$?
Comment: @MarcPaul Oh yeah, good point xD I'll edit that in.
Comment: Thanks for the answer! Is it true that the map $Y \times_{X} Y$ to $Y \times Y$ a monomorphism?
Comment: @grok Yes, I'll edit an explanation into my answer.

Is this a closed embedding of schemes?


Identificar uma parte especifica da tela

Question: É possível eu identificar uma parte específica da tela com Jquery os javascript? Por exemplo ao passar pela altura y ele executar para mim uma função?
Imagino algo assim:
var minha_altura = $(window).height();
var altura       = 400;
if(minha_altura > 400)
{
   //faz algo
}

Está correto o conceito e de fato isso funciona?
Answer: Você pode criar um evento no window para detectar o movimento do mouse e com isso o pageX/Y dele.
window.addEventListener('mousemove', function(event) {
  if(event.pageY > 400) {
    //{...}
  } else {
    //{...}
  }
});

Veja um exemplo:

window.addEventListener('mousemove', function(e) {
  document.body.innerHTML = '
 PageY:'+e.pageY+'

 PageX:'+e.pageX+'
';
});
Comment: @MarcosHenrique Claso que sim, desta forma é possível. `window.addEventListener('scroll', function() {
console.log(window.scrollY);
});`
Comment: muito obrigado pelo feedback, eu conseguiria fazer isto com o scroll da página tb?
Comment: agradeço a ajuda, foi de grande valia


Minimizing weighted sum of distances

Question: given a set of coordinates and the following function:
cost = $\sum \sqrt{(x_i−X)^2+(y_i−Y)^2}w_i$
I would like to find the point (X, Y) for which this function is minimal.
A simple example shows that the weighted average of the coordinates does not deliver the desired output: P1:{0, 0}, P2:{3, 0}, w1=1, w2=3 would result in {2, 0}, with a cost of 4, while the optimal solution is {3, 0} with a cost of 3.
I have a good (although bit rusty) knowledge of math, but my attempt to derive this function resulted in something to complex for me. I suspect there is some kind of trick that would simplify everything, but I cannot seem to find it.
Comment: In one dimension this becomes a question of finding the (weighted) median: this may not be unique.
Comment: Indeed, I had not came up with that myself yet. However, my problem does require 2 dimensions.
Answer: As Henry points out, the point you're asking for is the (weighted) Fermat-Weber point, also known as the geometric median. There is an algorithm that converges to the optimal solution known as Weiszfeld's algorithm: however, it's not known exactly how long it takes, and there are some technical difficulties when the iteration lands at a data point. This link describes the basic method and some modifications.
It is also known that there is no closed form solution for the problem involving radicals, so that line of attack is DOA :).
If you're willing to tolerate a (provably) approximate solution with an error guarantee as much as you wish, then there's a PTAS by Bose, Maheshwari and Morin that is relatively straightforward.
Answer: As I said in a comment, this is the two-dimensional equivalent of a (weighted) median, and it is not obvious that there is any suitable trick.  Indeed there are good reasons to think there may not be: while the medians of a solid triangle pass through a single point, other area bisectors do not so there will not be a solution as simple as finding where two easily calculated lines intersect, as you can for the mean.
Steve Witham has a nice page looking at two-dimensional extensions of medians, with an applet which lets you see various examples.  He observes that the point which minimises the sum of the absolute distances is also the point where the sum of unit vectors pointing at the original points sum to zero.
In your weighted case each of the directional vectors to the original points should be as long as the respective weight, but again you want find the point(s) where these sum to zero (or if an original point then the weighted directional vectors pointing to the other points have a vector sum with magnitude less than the weight for that point: for example a triangle where the weights are equal and one of the angles is more than $2\pi/3$: the Fermat/ point).
So one approach might be to add up these weighted directional vectors, and seek to optimise by moving in the direction of the vector sum by an amount related to its magnitude, in a form of gradient descent.

Minimizing weighted sum of distances


How to count the number of NSString in a NSString

Question: Hello I try to convert my java function in objective-c for iphone
Java:
    public int substrCount(String str, String needle) {
    int count = 0;
    int index = -needle.length();
    while ((index = str.indexOf(needle, index + needle.length())) != -1) {
        count++;
    }
    return count;
}

Iphone:
-(int)substrCount:(NSString *) str withSearch:(NSString *) needle
{
  NSRange lastIndex;
  lastIndex.length = [str length];
  NSInteger count =0;

  while(lastIndex.length != -1){
    lastIndex = [str rangeOfString:needle options:NSCaseInsensitiveSearch range:lastIndex];
    //lastIndex = str.indexOf(needle,lastIndex);

    if( lastIndex.length != -1){
        NSLog(@"+1");
        count ++;
    }
  }
}

But it's so hard, I don't understand when I can make it.
Maybe there are better solution existing? I don't have found anything :/
Sorry for my bad english !
Answer: I'd probably never write this code in production, but You could simply ask:
[[str1 componentsSeparatedByString:str2] count] - 1;
The result of that expression will be an integer representing the number of times str2 was found in str1.
However, the problem with your code is rangeOfString: returns NSNotFound if it can't find the substring, not -1.


How to interpret in swing a 16th triplet followed by an 1/8 note?

Question:
So the combined 1/16 triplet and 1/8 note cover a quarter note. The question is does the 1/16 triplet cover a straight 1/8 note or does it cover the 1st two 1/8 notes of a set of an 1/8 triplet. So is the quarter note duration considered two straight 1/8 notes with the first being a 1/16 triplet or are the 1/8 notes swung as an 1/8 triplet with the first two 1/8 notes of the triplet used for the 1/16 triplet. I know I have verbosely stated the issue in two different ways as I am just trying to be clear. BTW Musescore if you export midi one gets a straight interpretation - two straight 1/8 notes the first being covered by a 1/16 triplet.
Comment: Thanks for asking! As per the site's idea it would be great if you could accept the answer which most clearly solved the issue for you. :)
Comment: thanks folks, for the answers. I play by ear so what I play is 1/16 triplet in elongated 1/8 and then the short 1/8. Just wanted to understand the notation. Thanks again and Happy New Year!
Answer: The second E and the C of the triplet on the third beat are purely ornamentation. Try playing the phrase without them, you'll find that you'll automatically swing those two notes. Then try to fit the triplet in the first (swing-elongated) eighth.
Answer: Too bad they didn't say if they meant "swing 8ths" or "swing 16ths". But the duration of three 1/16 triplets is the same as one 1/8th note. Here is how to count one and two and three and four and.

A triplet means that more stuff is squeezed in the same space. https://en.wikipedia.org/wiki/Tuplet#Triplet
Do you mean to ask, if "swing" means "swing 8ths", then does the triplet cancel the swing? Well... I'd say, it's up to interpretation. The exact strength of swing is up to interpretation anyway. FWIW, I tried playing the third beat completely without swing, and it sounded stupid.
Comment: There are no 16ths to swing, so I'm pretty certain it won't be swung 16ths!
Comment: @JudyN. Where did you find the rest of the song?
Comment: Haha, touché...
Comment: Although of course if it is swing 16ths, one plays it precisely as it is written, so there is no conundrum
Answer: The basic swing feel is to elongate the first eighth note of the beat and shorten the second, depending on the feel, it could be anywhere from close to even to a triplet feel where the first eighth is twice as long as the first. For your example, I would play the triplets in the time of a first eighth note with an even amount of time for each with the second eighth shortened. I wouldn't worry about whether to swing the triplets at all since they're playing fairly quickly (about 0.13s each) and the variation of length of the notes at that tempo won't be something heard so much as felt.
Comment: When I just play it (looking at the audio or midi) I play with the 1/16 triplet in the elongated 1/8 and the G in the shortened 1/8 and it sounds right. Just wondered why Musescore's algorithm
Answer: Your comment's pretty much right on the money. To formalize it a little, in X:Y swing, the triplets "ought" be counted three-against-X.
This is dead simple if you're strictly counting a 3:2 "pentuplet swing", you just come down on each pentuplet.
In a strict 2:1 "triplet swing", it's a little more difficult, you'll need to divide your beat into nine so you can come down like so
x-x-x-x--
against
3--&--u--
but you can probably (and, arguably, should) feel it ("fudge it", if you're cynical) in most contexts
Answer: 'Swing' can be translated into a 12/8 equivalent. Yes, I know it can vary considerably between almost straight and totally swing, but for an explanation to answer the question. Read on before dving!
It's swing quavers (eighth notes), so if we put a count of 12 in for the bar, here goes.
The first G comes in on --3, followed by the two triads on 4 and 6. That puts the triplet semis on 7 and 8, so the G comes on 9, leaving the last part on 10 and 12. Since the triplet semis are just that - a triplet, they can be played as such. There's no need to 'swing' them - in fact, it's better played as a triplet.
Referring to my first paragraph, the swing can be as soft or hard as you want, but now at least everything is in its place clearly.
Comment: Another unexplained dv! Reasons are accepted!
Answer: I would play this by elongating the E-G dyad slightly and playing the following three notes as a triplet within the remaining time. However, in doing that, I'm not trying to play in a metrically precise way; I rely on feel.
I'm playing something in between these two approximations.
X: 1
T: Approximation 1
T: E-G is too long here
M: 4/4
K: C
{/^d}[eg](3e/2c/2G/2 [Fc]

X: 1
T: Approximation 2
T: E-G is too short here
M: 4/4
K: C
{/^d}[eg]/2e/2c/2G/2 [Fc]

My E-G dyad is a big shorter than Approximation 1, but a bit longer than Approximation 2.
Comment: Neither of your examples correspond to the notation as written. You can get away with changing the rhythm if you're playing solo, but in a section that's not going to work.
Comment: @PiedPiper Yes, that's true. I called them approximations rather than examples because of that departure from the literal notation. And you also correctly note that I'm presuming a solo player. In an ensemble I'd ask the group, the section leader, or the direction how they'd like to play the figure.


No input file specified with nginx

Question: I'm getting "No input file specified." when I attempt to browse to the phpmyadmin domain, not sure what I'm doing wrong.. using both php-fpm and php-cgi, php-fpm is currently working another directory fine..Had to change the port number to 8888 since -fpm was already using 9000
http://pastebin.com/kdEckiL3
from nginx.conf:
server {
    listen 80;
    server_name phpmyadmin.domain.com;
    access_log /home/fanboy/logs/phpmyadmin.access_log;
    error_log /home/fanboy/logs/phpmyadmin.error_log;

location / {
    root /usr/share/phpmyadmin;
    index index.php;
    }

location ~ \.php$ {
    fastcgi_pass 127.0.0.1:8888;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /usr/share/phpmyadmin$fastcgi_script_name;
    include /usr/local/nginx/conf/fastcgi.conf;
    }
}

Answer: A better way will be relocate your "root" line out of your location block.
server {
    listen 80;
    server_name phpmyadmin.domain.com;
    access_log /home/fanboy/logs/phpmyadmin.access_log;
    error_log /home/fanboy/logs/phpmyadmin.error_log;

    root /usr/share/phpmyadmin;

    location / {
        index index.php;
    }

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:8888;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME /usr/share/phpmyadmin$fastcgi_script_name;
        include /usr/local/nginx/conf/fastcgi.conf;
    }
}

Apparently nginx server configuration some how missed the document root setting.
Got this idea from Nginx Configuration Guide for PHP FastCGI.
Comment: Awesome. This worked. Kudos!
Comment: Glad it helps :)
Answer: fastcgi.conf is redefining SCRIPT_FILENAME to $document_root$fastcgi_script_name.  If you set the root in the server (Just remove the "location / {" and matching }) and remove the SCRIPT_FILENAME line from your php location, it should work fine.

No input file specified with nginx


Undo command working so late

Question: I am trying to delete the shapes with animations to take slide printscreens without them. After that I want them back so I use Undo command. The problem is that this command is working to late. I mean that it makes the undo when all my vba code ends and I need it to do just when I call to the command. I am trying to stop the code for some seconds but is not working. Here is the code that I am using:
<code>  For Each sl In ActivePresentation.Slides
        shapeNum = sl.Shapes.count
        'ActivePresentation.Slides(1).Shapes(1).
        While shapeNum <> 0
            If sl.Shapes(shapeNum).AnimationSettings.Animate = msoTrue Then
                animationNum = animationNum + 1
                sl.Shapes(shapeNum).Delete
                animationNum = animationNum + 1
            End If
            shapeNum = shapeNum - 1
        Wend
   Next

   ActivePresentation.SaveAs "c:\dink_template\created_files", ppSaveAsPNG, msoTrue

   If animationNum <> 0 Then
        Application.CommandBars.ExecuteMso "Undo"
        'to make the code stop for 5 seconds
        waitTime = 5
        Start = Timer
        While Timer < Start + waitTime
        Wend
   End If
   ' Here the code continues doing several things
</code>
I also try to put a MsgBox or another way to stop that I saw here: http://www.pptfaq.com/FAQ00466_Put_your_macro_to_Sleep.htm
But nothing works it stay 5 seconds doing nothing but the undo doesn't work until I finish the code. What works is to use the debugger. If I stop it with the debugger it works but I want to do it without using the debugger because when I put the code as a macro I won't be able to use it.
Answer: Ok guys I think I found the solution for this. Is just to use DoEvents after Application.CommandBars.ExecuteMso "Undo" This solve the problem. Hope at least that this will help to someone.

Undo command working so late


Is it a way to get know if more than one user edit the same node?

Question: I'm looking for the way to inform site editors if the other editor is trying to edit the same node. In other words I need functionality that is similar to the Checkout module. But it is no longer maintained and I don't like to lock anything, just show a popup message.
Do you think that it is possible? I didn't find any hooks in Drupal API that could do that.
And the last thing - this is Drupal 6
Answer: This is already built-in in Drupal 6 (and 7), in the function node_validate.
The relevant piece of code is reproduced below:
<code>if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}
</code>
It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done.
The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.
Comment: The main difference is that the user sees this when they click save, not when they navigate to the page before they have edited.
This method of doing it on save is better though because it reduces false positives where users are on a node edit page but don't actually make edits.


Bayes' rule / Probability Tree question

Question:
One percent of a population suffer from a certain disease. A diagnostic test gives a positive indication 97% of the time when an individual has the disease, and a negative response 95% of the time when an individual doesn't have the disease.

(i) Draw tree diagram
(ii) A person selected randomly reacts positively to the test. What is the probability that this person actually has the disease.
(iii) Calculate the probability that the test yields correct diagnosis for an individual chosen at random
Here's my tree diagram:

For part (ii) I used Baye's rule and said:
$$\frac{P(D∩+)}{P(D∩+)+ P(no D∩+)}$$
For part (iii) I simply said:
$$P(D∩+)+P(no D∩-)$$
So far am I correct? Please advise.
Comment: For (iii) you are asked to provide $P(+\vert D)p(D)+P( -\vert no\ D)p(no\ D)=P(+\wedge D)+ P(-\wedge no\ D)$, which is precisely what you wrote. "Individual chosen at random" means that you have to add the probablities of all branches of the diagram that yield a correct diagnosis.  -- Why do you think that something else was meant by the question? Am I overlooking something?
Comment: So far it is correct, you are almost done. What remains to be done is the calculation of the joint probabilities via the conditional probabilities you can read from the tree, e.g. $P(D \wedge +)=P(D)P(+\vert D)$,...
Comment: Apologies, is that for part (iii) the question doesn't seem to ask for that
Comment: Basically I thought I left something out, you didn't overlook anything, thanks for answering my question.
Answer: At no point in this question does it say use Bayes' rule, and as you are asked to draw the contingency tree you are expected to derive the asked for results from that tree.
For part (ii) you are probably expected to take the ratio of the + leaf on the upper branch (the probability that you tested positive and have the disease) to the sum of the probabilities of the + leaves (the probability that you test positive); that is $\frac{0.01\times 0.97}{0.01\times 0.97+0.99\times 0.05}=0.16385$, or $\approx 16\%$
For part (iii) you are probably expected to sum the probabilities of the correct diagnosis leaves in the tree, that is the + leaf on the upper branch and the - leaf on the lower branch to get $0.01 \times 0.97+ 0.99\times 0.95=0.9502$ (or $\approx 95\%$)
Which should agree with the results of applying Bayes' rule since the tree is a visualisation of the rule.

Bayes' rule / Probability Tree question


Attempt to delete a question "for privacy"

Question: The OP has deleted the text from the body of this question and replaced it with "Apologies, deleted for privacy".
What should we do about this?  Obvious choises to me are:
Revert the edit
The OP is obviously not aware that previous versions are still visible in the edit history.  The edit is essentially vandalism.  (A mod might have to lock the post in some way to prevent the OP repeating the edit.)
Delete the post
That would ensure that the previous version is only visible to 10k users (and not, in particular, to Google's spider).
Comment: I suggest flag for moderator attention and revert if nothing seems to personal  (as you mention the edit only hides the info a little)
Comment: @StrongBad You're a *moderator*.  You ought to know better than to post an answer in the comment box!
Comment: I do. I wanted to respond quickly and didn't have time to write a full answer.
Answer: An alternative is disassociating the post from the poster, which can be requested by them as described here: Could we have a Help Center page on disassociating posts?
As a moderator I can (and did) also ask for this from the CM team on behalf of the poster, which was done recently
Answer: In these cases it is important to flag the question to let a moderator know what is happening. Often a user will revert edits, deface other content of theirs or even content of third parties. If the community goes around fixing these things, a mod might never know about the bad behavior. So in summary, definitely flag the post. We can lock it, help the user disassociate the post, redacted the problematic content, and give the user a time out.
As for rolling the edits back, this is a personal call. If it seems like the user is trying to hide something (e.g., they posted some PII), I would leave the edit. While the PII would still be in the revision history and need to be dealt with, at least it is a little hidden. If it seems like everything was fine in the original version I would revert the edi, leave a comment, and flag the content.