Partition a set into g groups, k different ways, such that no pair of elements is ever in the same group together more than M times

Question: Over at Wolves and Sheep on puzzling.stackexchange.com, noedne's answer involves repeatedly partitioning a group of 99 sheep into a series of "test groups" such that

All but one sheep are tested six times.
No pair of sheep shares more than one test.

This feels like it ought to be a well-studied combinatorics problem, something like a generalization of Kirkman's schoolgirl problem, but I can barely state the generalized problem, let alone figure out how to Google it!
The problem is:

Define a "partition of a set $S$ into $g$ groups" as a mapping $P : S \rightarrow [1..g]$.
  Given a collection $S$ of $n$ elements, produce $k$ different $g$-group partitions of the collection, such that no pair of elements is ever in the same group together more than $M$ times.
  That is, produce $k$ different partitions $P_0, P_1, \cdots, P_k$ such that $\forall s_1, s_2\in S, \sum_{i\in [1..k]}{\big(P_i(s_1)=P_i(s_2)\big)} \leq M$.

noedne's answer to Wolves and Sheep gives one viable solution for $n=99$, $g=11$, $k=6$, $M=1$: "Given a collection $S$ of 99 elements, produce 6 different 11-group partitions of the collection, such that no pair of elements is ever in the same group together more than once."

So I'm asking you, Math StackExchange: What is the name of this problem, and what is known about the space of parameters $(n,k,g,M)$ for which it is solvable?
Comment: This sounds similar to block design: https://en.wikipedia.org/wiki/Block_design
Comment: Hmm, following the "related questions" links, I suspect that for $M=1$ (which is the most interesting case anyway), this is exactly the "Social Golfers Problem"; see e.g. https://math.stackexchange.com/questions/69325/social-golfer-problem-quintets  I'm not sure what happens when we let $M$ vary, though!
Comment: Yes this is just block designs
Comment: @Elaqqad: Uh-oh! [Fisher's theorem](https://en.wikipedia.org/wiki/Fisher%27s_inequality) states that if you tackle this problem using BIBDs, you will never ever find a solution where the total number of groups $b$ (which I called $k\cdot g$ above) is less than the number of elements $v$ (which I called $n = \lvert S\rvert$ above). So noedne's colorful solution above is not a BIBD, and BIBDs can't help us improve on it.
Comment: When you tackle the problem using BIBDs, you don't work with normal blocks, instead, you work with the the *dual" of the BIBDs, in the dual the points are the lines and the blocks are the points.
Comment: In the bock I mentioned in my answer (Combinatorial Designs: Constructions and Analysis), you can find this in section 11.3 Group Testing Algorithms (page 265). But using BIDDS, of course, constrains us in fact if you have, say $(v,k,1)$-BIBD then the relation is $b=(v^2-v)/(k^2-k)$ in your case $k=6$ (a BIBD induces a solution with $k-1$ defectives ) . the $b$ is the number of points so it is equal to $100$. this implies that $v\geq 46$
Comment: If don't think that BIBD is the way forward to get a better solution, Because it' is an open problem if there is a BIBD $(61,6,1)$ (or at least a difference set) which if it does exist it gives you a new bound (but we don't think that it does exist). If there is a new bound it should be based on something else, like PDBs, free cover families, d-disjunct matrices, generalized quadrangles ..... .There are a lot of methods to tackle the group testing problem. Your question is what do we call this model and what is known about it and that's only what my answer discusses.
Comment: @Elaqqad: I don't understand what you mean at all, then. Could you post an example of a block design that solves _any_ instance of the Wolves and Sheep problem — say, for 2 wolves out of 8 sheep? My impression from your initial answer had been that to find 2 wolves out of 8 sheep you'd have to find a BIBD for $(v\ge 8, b=\textrm{minimal}, r=3, k=?, \lambda=1)$. Your latest comment says nope, you'd have to find a BIBD for $(v=\textrm{minimal}, b\ge 8, r=?, k=3, \lambda=1)$. But I still don't see either how to find that BIBD nor how it would be massaged back into a Wolves and Sheep solution.
Comment: if you read carefully, the second generalization on my answer you will find out that my comment coincides with it, for the example you gave the second interpretation $(v=\textrm{minimal}, b\ge 8, r=?, k=3, \lambda=1)$ is the correct one.
Comment: Also, in the end of my answer, there are two examples (not developed completely, I will try to add more details later on ,this is my phone, and I can't really write it now)  If the subject is new to you, then you have to follow alongside the book and do some exercises and examples in order to understand.  I have another very good book on the subject (more recent) https://www.amazon.com/Handbook-Combinatorial-Discrete-Mathematics-Applications/dp/1584885068 (I can send to you by email if you want it).
Answer: What you are looking for is block designs, precisely $BIBD$s. This answer can be viewed as a comment. In the first part, it states the main question and its relation to group testing and design theory. In the second part, it tries to analyze the given solution to the puzzle and gives one generalization. And in the third part, it states the definition of balanced incomplete block designs and references a book containing a comprehensive analysis.

First of all, let's state the original puzzle:
Question:
Given a large population of items (sheep) containing a small set of defectives (Wolves), Assuming you can perform a test on a group of items and get a positive result if and only if the group contains a defective. How many tests are required to identify all the defectives?

Mathematically, given integers $d<n$, and $X$ a set of size $n$, we call a family $\mathcal{F}$ of subsets of $X$ $d$-distinguishing, if the function $f : {n \choose X} \to 2^ \mathcal{F}$ defined by $A \mapsto \{X\in \mathcal{F}, X\cap A \neq \varnothing \}$ is injective. What is the minimum size of a $d$-distinguishing family $\mathcal{F}$ denoted by  $t(n,d)=|\mathcal{F}|$ ?

In Combinatorial design theory, one of the most beautiful areas of mathematics, this is called the Group Testing Problem. It is a very well studied subject because it has a lot of applications. It's very difficult to navigate all the research done on it but for the interested, I can refer to the survey Combinatorial Group Testing and Its Applications. by D. Du and F. Hwang.
To summarise, the only value for which $t(n,d)$ is known completely is $d=1$ for which $t(n,1)=\lceil \log n\rceil$, the exact value even for $d=2$ is not known. Generally, the solutions to this problem are called testing designs, and the main considered ones are:

Set-packing designs or block designs.
Transversal designs.
Designs whose $d$-disjunct or $d$-separable matrices are directly constructed.

Using these methods, It's known that :
$$\frac{d^2}{2\log(d)}\log(n) \leq t(n,d) \leq d^2 \log e(1+o(1)) \log(n) $$
This basically suggests that for your puzzle, the solution would be close to $30$.

Now returning to the answer given for the puzzle. Basically, the design that is proposed is the following :
Solution: First of all, put all the items in a grid $11\times 11$ and then create a set of tests, each test corresponds to a line in that grid. Additionally, every line contains every item exactly $6$ times and every two lines intersect in only one point. then every $5$ items (points) subset is a member of a nonshared set of lines.

Mathematically, Given a field $\Bbb F$, and $X \subset \Bbb F^2$ a subset of pairs of size $n$.  For any $A \subset \Bbb F$ define the following family
  $$\mathcal{L}_{A}=\Big\{L(a,b)=\{x+ay=b, (x,y)\in X\}, a\in A , b\in \Bbb F \Big\} $$
  then $\mathcal{L}_{A}$ is $d$-distinguishing for $X$ of size $|A||\Bbb F|$ for any $d<|A|$.

Proof: This formalizes the set of lines in a $2$ dimensional space over $\Bbb F$. Because of the fact that all the matrices $\begin{pmatrix}1&a\\1&a'\end{pmatrix}, a\neq a'\in A$ are invertible (thus fixes $b$), each two lines intersect only in one point. and of course, the definition ensures that every item is a member of exactly |A| groups.
Remarks:

In the puzzle $|X| = 100$, $|\Bbb F|=11$, $|A|=6$ and $d=5$.
The design applies to up to $|X|=121$ without changing the number of tests
This implies that $t(n,d) \leq (d+1)p^k \sim (d+1)\sqrt n$ where $p^k$ is the smallest prime power $\geq \sqrt n$
Of course this is not the optimal solution.

One first generalization of this solution is to consider higher dimensions, but a very difficult constraint arizes, mainly that of No-three-in-line problem and more (this is because of the argument of matrix invertible above).

First generalization (dimension $=3$), Given a field $\Bbb F$, and $X \subset \Bbb F^3$.  For any $A \subset \Bbb F^2$ with no three colinear points, define the following family
  $$\mathcal{L}_{A}=\Big\{L(a,b,c)=\{x+ay+bz=c, (x,y,z)\in X\}, (a,b)\in A , c\in \Bbb F \Big\} $$
  then $\mathcal{L}_{A}$ is $d$-distinguishing for $X$ of size $|A||\Bbb F|$ for any $d$ such that $2d<|A|$.

Proof: This is the set of planes in a $3$ dimensional space over $\Bbb F$. Because of the fact that all the matrices $\begin{pmatrix}1&a&b\\1&a'&b'\\1&a''&b''\end{pmatrix}$ are invertible for distinct $(a,b),(a',b'),(a'',b'')\in A$, each three planes intersect only in one point. and of course, the definition ensures that every item is a member of exactly |A| groups. The proof is the same as before, in fact, it is just an application of the generalized pigeonhole principle. This is why we need the last inequality $2d<|A|$.
Remarks:

The non-$3$-colinearity condition is very strong, and the existence of such points requires $|A| \leq \sqrt {|F|} $, which in our cases is not applicable.
This implies for $n>> d^6$ that $t(n,d) \leq (2d+1)p^k \sim (2d+1)\sqrt[3] n$ where $p^k$ is the smallest prime power $\geq \sqrt[3] n$
Of course this remains not the optimal solution.

This two types of solutions are called grid designs (or affine planes, projective planes in combinatorial design theory) and they are also studied by for example Hwang in the book I referenced above. In their constructions, the property that no two points are in the same line twice is called the unique collinearity condition.

These methods - when not randomized - don't give us better bounds. The main methods used in the field are block designs and direct constructions of the matrices. Your generalization is equivalent to the following

Second generalization. Let $n$, $g$, and $M$ be positive integers such that $n > g \geq 2$. A $(n, g, M)$-balanced incomplete block design (which we abbreviate to $(n, g, M)$-BIBD) is a design $(X, \mathcal A)$ such that the following properties are satisfied:

$|X| = n$,
each block contains exactly $g$ points, and
every pair of distinct points is contained in exactly $M$ blocks.

then the dual of every $(t, g, 1)$-BIBD is $(g-1)$-distinguishing of size $t$ for a set $Y$ of size $\frac{t^2-t}{k^2-k}$.

The third property above is called the balance property, which you do not require in your definition. If it's relaxed to "every pair of distinct points is contained in no more then $M$ blocks", the design will be called an incomplete block design. Also, we can relax the second property by allowing multiple block sizes in a set of integers $G$. We obtain a $\bf{(t,G,M)}$-pairwise block design. This is exactly what you are looking for.
All the results I know are focused on $BIBD$s (and $PDB$s, ...) as combinatorial structures. This is a very largely studied subject and in any book on Design Theory (for example Combinatorial Designs: Constructions and Analysis) you will find a lot of examples, constructions, and conditions of existence.
The book contains an example of $(37, 4, 1)$-BIBD (resp. $(19, 3, 1)$-BIBD) which means that we can identify $3$ (resp. $2$) defective items in a group of size $\frac{37^2-37}{4^2-4}=111$ (resp. $58$) using $37$ (resp. $19$) tests. These specific block designs generally provide a solution with an order of magnitude $t(d,n) \sim d\sqrt n$.

Edit : As you requested here is an example of how you can solve a group testing problem given a block design. An example of $(37,4,1)$-BIBD can be constructed as follows, Let $D_1=\{0,1,3,24\}$, $D_2=\{0,10,18,30\}$ and $D_3=\{0,4,26,32\}$ (a difference family), now define :
$$
    X=\Bbb{Z}_{37}=\{0,....,36\} \\
    B_{i,j}=\{ d+j , d \in D_i\}, i\in {1,2,3}, j\in X
$$
Addition is done modulo $37$, the number of blocks is $111$, size of $X$ is $37$ and each block contains exactly $4$ elements of $X$.
Now given $111$ items (Sheep), assign every sheep to a block in the example, and create the following tests $T_x=\{B\in \mathcal{B}, x \in B\}$ for each $x\in \Bbb{Z}_{37}$. I claim that these $37$ tests are sufficient to find $4-1=3$ defective items (wolves) in the original set.
In your puzzle, what you need is $(v,6,1)$-BIBD with $v\geq 46$ (or a $(v,\Bbb{N}_{\geq 6},1)$-PBD) if you have done some research on this you will find that :

If there is a $(v,6,1)$-BIBD, then $v \equiv 1,3 \mod 15$.
It is proven that there is no $(46,6,1)$-BIBD
It is an open problem if there is $(v,6,1)$-BIBD for a finite list$v=51, 61, ...$ (as far as I know)
Using BIBDs the best solution we can get less than $63$ is $61$ but that's an open problem.

What I have tried (without success) is to find instead $(v,\{6,7,8\},1)$-PBD ($v$ should be bigger than $42$).
Edit: Using packings, which is the structure that satisfies your two conditions (kind of), then if a solution exists for your puzzle that satisfies both conditions, it should contain at least $56$ tests. The argument is based on the fact that every packing design satisfies $D(v,k,2) \leq  \left\lfloor \frac v k \lfloor \frac {v-1}{k-1}\rfloor \right\rfloor$.
Solution for your puzzle A possible answer for your puzzle with $60$ tests.
First, consider the following $4$ base blocks :
BaseBlocks = [
    {(0,0,0,0),(0,1,0,2),(0,2,1,0),(1,0,1,1), (1,1,1,2), (1,2,∞,∞)},
    {(0,0,0,0),(0,1,0,1),(1,0,0,2),(1,1,0,2), (1,2,1,1), (0,2,∞,∞)},
    {(0,0,0,0),(0,1,0,0),(0,2,1,1),(1,0,0,0), (1,1,0,3), (1,2,∞,-∞)},
    {(0,0,0,0),(0,1,0,3),(1,0,1,3),(1,1,1,1), (1,2,0,3), (0,2,∞,-∞)}
]

Now consider the following blocks (addition is done modulo the subscripts, and infinity plus anything stays the same) :
Blocks = [
   { (a,b+i,c+j,d+k) , (a,b,c,d) in B}
   B in BaseBlocks
   i in Z_3
   j in Z_2
   k in Z_4
]

There are exactly $96$ blocks. There are $60$ points of the form $(a,b,c,d)$ in the union of those blocks. Now as for the first example, the blocks correspond to Sheep and the points to the tests. Up to here, with these $60$ tests, you can find $5$ wolves among $96$ sheep.
But actually you can add $8$ more sheep, By adding more blocks :
Blocks' = Blocks ∪ [
   {(0,0,∞, ∞),(0,1,∞, ∞),(0,2,∞, ∞),(1,0,∞,-∞),(1,1,∞,-∞),(1,2,∞,-∞)},
   {(0,0,∞,-∞),(0,1,∞,-∞),(0,2,∞,-∞),(1,0,∞, ∞),(1,1,∞, ∞),(1,2,∞, ∞)},

   // The pattern : all the first two elements are the same
   {(0,0,0,0),(0,0,0,1),(0,0,0,2),(0,0,0,3),(0,0,1,0),(0,0,1,1),(0,0,1,2),(0,0,1,3)},
   {(0,1,0,0),(0,1,0,1),(0,1,0,2),(0,1,0,3),(0,1,1,0),(0,1,1,1),(0,1,1,2),(0,1,1,3)},
   {(0,2,0,0),(0,2,0,1),(0,2,0,2),(0,2,0,3),(0,2,1,0),(0,2,1,1),(0,2,1,2),(0,2,1,3)},
   {(1,0,0,0),(1,0,0,1),(1,0,0,2),(1,0,0,3),(1,0,1,0),(1,0,1,1),(1,0,1,2),(1,0,1,3)},
   {(1,1,0,0),(1,1,0,1),(1,1,0,2),(1,1,0,3),(1,1,1,0),(1,1,1,1),(1,1,1,2),(1,1,1,3)},
   {(1,2,0,0),(1,2,0,1),(1,2,0,2),(1,2,0,3),(1,2,1,0),(1,2,1,1),(1,2,1,2),(1,2,1,3)}
]

Now with this, you can find $5$ wolves among $104$ sheep using $60$ tests !
Comment: I will try to do that hen I have some time (need to create the matrix).
Comment: Posted! https://puzzling.stackexchange.com/a/92546/3896
Comment: "Of course this is not the optimal solution" — why "of course"? Do you know of a better solution, or do you mean more like "Of course _the odds are that_ this is not the optimal solution"?  Related: when you say that "for your puzzle, the solution would be close to 30," do you have any sense of the error-bars on that? When I plug d=5, n=100 into your formulas, I get "35.7 ≤ t(100, 5) ≤ 115+epsilon", which seems very different from "close to 30."
Comment: "being close to $30$" is just my intuition not a fact, however, it is based on the fact that all the solutions we know (even consider) are based on some specific type of structure that we understand well, and therefore we restrict ourselves in a very small subset. The actual search space is much much larger than what is taken into account in those specific mechanisms.  The asymptotics there are only when $n$ is very large ( I don't know how much exactly) and we can't apply them for small values (I forgot something in the formula). The only bound we have for sure is $t(5,100)\geq 27$.
Comment: But certainly is not the optimal solution, as there are other more complicated mechanisms that give us better bounds.  I actually have a solution with 47, but the details are very messy and it could require writing a lot, I am not sure if I should include it in the answer without those messy details.
Comment: In fact, all the solutions that came for a  $BIBD$ can give only a number of tests $t$  that satisfy $t^2-t\geq 2000$ which means, that the best we can hope for using BIBD is a solution with $46$ tests. If we need a better solution we have to consider some new (probably more complicated) type of block designs
Comment: If you have a solution to ["Wolves and Sheep"](https://puzzling.stackexchange.com/questions/81737/wolves-and-sheep/) in 47 (or any-fewer-than-63) tests, then you should post it over there! You don't even have to explain it at all, let alone the "messy details," if you don't want to.  It's quick and easy for anyone to verify that a solution is a solution; for example I have a C++ program to verify proposed solutions [here](https://github.com/Quuxplusone/wolves-and-sheep/blob/master/main_verifysolution.cc).
Comment: I just tried to apply your "First generalization" to t(n=100,d=5). Unfortunately, it seems to say that we should start with an _A_ of size 11 or more, which makes for more than 121 tests if I understand your notation correctly. So not only it "remains not the optimal solution," but it becomes much worse than the [worst possible solution](https://puzzling.stackexchange.com/a/81871/3896)? ;p Seems like these generalizations have good asymptotics but really poor constant factors, and thus aren't likely to help with "small" concrete examples like t(100,5). Yes/no?
Comment: Yes exactly, that's what I meant by "which in our cases is not applicable". I discovered an error in my solution with 47 tests. Maybe 30 is completely off the scale.  Small cases are really hard it seems.
Comment: @Quuxplusone I added some more explanations, and also I explained how you can find $3$ wolves in a pack of $111$ sheep using $37$ tests (can you verify that it works using a computer ? mathematically it should)
Comment: Note that if you follow the same approach as noedne's answer, then you will get originally 44 tests ( instead of 66), but as he did, we can probably reduce that number by removing some tests.  Also if you reduce the number of sheep to $105$ then we can do it in $36$ tests using a $(36,4,1)-BIBD$.
Comment: "find 3 wolves in a pack of 111 sheep using 37 tests (can you verify that it works using a computer?" — Yes, verified! Thank you very much! I have added that solution to my GitHub repo [here](https://github.com/Quuxplusone/wolves-and-sheep/commit/5f0cc0586f5e96a3353abd03848db317e59c34cd).
Comment: @Quuxplusone, I added a solution for your puzzle with $60$ tests. Can you please test it ?
Comment: Your t(96,5)=60 solution works fine! Your t(102,5)=60 solution fails, assuming I have transcribed it correctly: https://github.com/Quuxplusone/wolves-and-sheep/commit/11583400 produces indistinguishable wolf-arrangements https://pastebin.com/TQZDUap6 . I'll investigate more later.
Comment: Yeah, you're right I made a mistake, I don't know what I was thinking when I wrote that. The updated answer should be the correct one.
Comment: Also, this should work even if you don't know initially how many wolves are there but you know that there are no more than $5$. Because all the combinations with less than $5$ elements produce different outputs. That's why I would say this is not optimal we can just deduce that $t(104,5)\leq 60$ ( we can probably remove some tests for the case $t(100,5) $)
Comment: Your t(104,5)=60 solution works! https://pastebin.com/b9w90YTH FYI, I *had* misinterpreted your earlier t(102,5)=60 solution — I had added the new blocks to the list of *base blocks*, instead of to the final generated list of blocks. But I didn't go back and re-test after realizing that, because you'd already updated your solution into t(104,5)=60. If you remove the first test, t(100,5)=59 also works. https://github.com/Quuxplusone/wolves-and-sheep/commit/b2f29faa
Comment: Great!, you can post that on the other site if you want. I don't have enough points to do so.
Comment: You don't have enough points to post an _answer_? That's not possible AFAIK (unless you just don't have an account over there at all, and really don't want to create one). I'll give you another day-ish to reconsider, ;) and then I'll happily post your answer with credit and as much explanation as I can reliably reproduce, and take all the upvotes for myself. ;)
Comment: Yes, because the question is Highly active. You have done work too, you deserve the upvotes!


mysql results truncated here, but not there

Question: My first post here.  I have a mysql table,
 - InnoDB
 - latin1-bin
There are about 300 rows/9 columns.  This is a choral library, so most of the columns are varchar, except for an auto-incremented key index column.  Much like a book collection; title, author, composer, etc.
There are two types of views, list view and record view in the CMS.  They are much like typical list and record views in a desktop app such as Lotus Approach or MS Access.
The list view is build on a table with headers (th), rows(tr) and data (td).  30 results per page.  The record views are built on text inputs, where data can be modified, records created/deleted, or searched, and display only one record at a time.
The problem is that on the list views titles that contain subtitles (double quoted strings) are not truncated, and the data is displayed perfectly, (Santus and Bendictus from "St. Cecilia Mass").
echo "$row[TITLE]	";

However, the same code in a text input doesn't work:
Allowing for escaping characters, changing the code to:
echo "<input type='text' name='title' id='title' value= \"$row[TITLE]\" style='width:390px; margin-right:150px; maxlength:75; margin-top:15px' />";

Yields "Santus and Benedictus from".  Bear in mind, the first code snippet was from an index view, and the second is from the browse/edit view.  I've tried other combinations such as:
...'$row[TITLE]'  or  $row["TITLE"]  or  $row['TITLE']

Either of the last two statements throw a php error and just kill the page.  The escape character with double quotes yields everything up to the double quotes. Enclosing the expression in single quotes corrects the problem, but then creates another problem with the title, "God's Wondrous Love" where it is truncated at the apostrophe.  Again, the problem only exists on the record views, (text inputs) and not on the table (list view).
My question: why the difference in behavior?  The data is not getting truncated by the query.  I know that I can simply instruct the users to not use double-quoted strings, and that seems to solve the problem.  But I just thought it curious.
Hope I haven't missed something.  First post wouldn't allow me to post images, so I hope nothing is out of context.
Thanks.
Comment: Consider adding more code (of the view functions/files and of the controller) . Maybe the controll doesn't pass this data or it does pass it with a variable which not named $row.
Comment: just tried a plain old echo, not to an input and that worked ok, but it was still truncated in the text input.
Answer: I don't know why is that happening, but you could always use regex to parse the value and escape any conspicuous characters in your view.
Comment: ok added this: $temp=$row[TITLE];  $temp = preg_replace('#["]#', "'", $temp); and finally, echo "";  That works.  Don't see any formatting rules here.  Hope I got it right.
Answer: When you are inserting the values in an  box, the problem is that the quotes for the 'value' attribute conflict with the quotes in the value itself. This conflict causes the value to be truncated.
Below is an example of how the outputted  will look like assuming $row['title'] contains (Santus and Bendictus from "St. Cecilia Mass"):
<input type='text' name='title' id='title' value="Santus and Bendictus from "St. Cecilia Mass"" style='width:390px; margin-right:150px; maxlength:75; margin-top:15px' />

So what is happening here is that the first quote in the value is taken as the closing quote for the 'value' attribute. Therefore what the text-box only shows is (Santus and Bendictus from)
I think what you need is the call to htmlentities(). Like this:
-- values enclosed in single-quote
echo "<input type='text' name='title' id='title' value='" . htmlentities($row[TITLE]) . "' style='width:390px; margin-right:150px; maxlength:75; margin-top:15px' />";

or
-- values enclosed in double-quotes
echo "<input type='text' name='title' id='title' value=\"" . htmlentities($row[TITLE]) . "\" style='width:390px; margin-right:150px; maxlength:75; margin-top:15px' />";

Hope it helps!
Comment: Abhay, thanks.  No 2 works.  I had tried something similar to your first suggestion, but with my second example, "God's Wondrous Love", it throws the page out of whack.  Labels and inputs are scattered helter skelter, and the value is still truncated.  Your second suggestion works: the page is not scattered, and the results are not truncated with either sample.  Even picks up the double quotes, rather than having to tweak it with preg_replace.
Comment: Great that it works @jazcam. Even my first suggestion should work for values like "God's Wondrous Love" unless the single-quote isn't actually the single-quote
Comment: Tried to reply but the page went dead.  The scattering was that I missed the space after the second concat operator, `. "' style=...` between the single quote and "space".  The outerhtml is getting whacked.
Comment: Sorry, yes I kept getting cut off.  Isp or something.


check if an element is being hovered over

Question: I want to check if a element is being hovered over. I get this error:
<code>Syntax error, unrecognized expression: unsupported pseudo: hover
</code>
when I use this code:
<code> $('.class').blur(function(){
    if(!$(this).is(':hover')){
       //element not being hovered over
    }
 });
</code>
i also tried this:
<code> $('.class').blur(function(){
    if($(this+":hover").length === 0){
       //element not being hovered over
    }
 });
</code>
this also does not work. Is there any other way of doing this. Thanks.
Comment: Upgrade to 1.11.x  (lastest one?), it still support ie6/7/9, only 2.x branch has removed support
Comment: Which jQuery version are you using? This was buggy in jq 1.9.x. Be aware though, this still doesn't work if matched set returns more than one element, in any jq version AFAIK **but** `if(!$(this).is(':hover'))` would work on 1.10.0 e.g
Comment: I am using 1.9.x because I want support for ie6/7/8
Answer: <code>$(".class").mouseover(function(){
    $(this).attr('checked',true);
    });
});
</code>
Answer: jQuery has this functionality built-in. See documentation on .hover()
<code>$(".class").hover(
  function() {
    // item is being hovered over
    $(this).addClass('hover');
  }, function() {
    // item is no longer being hovered over
    $(this).removeClass('hover');
  }
);
</code>


ABC notation: percussion / rhythm staff

Question: Alas, the Percussion example here doesn't work for me:

It renders differently, in that it's on a 5- rather than 1-line staff and the clef shows as a single "hollow" box rather than the 2 black lines.
More importantly though, it doesn't play. (Other files do play, so my EasyABC is working, as is my system's sound.)

I have EasyABC 184.108.40.206, Windows 10.
Does anyone have any suggestions to get it to work please?
Comment: The hollow box is an alternative percussion clef. The default midi output is probably channel 1 but it might output percussion on channel 10.
Comment: I've tried program 10 @PiedPiper, as well as 9 and 11- I noticed in the past it's sometimes off by 1- no change. Even if the program is wrong and it doesn't sound, shouldn't the note head change to orange when it's played?
Answer: EasyABC is a little different to the ABCjs that's running on this site, so you'll need to make a few adjustments.
The following works for my setup (EasyABC 126.96.36.199 on macOS Sonoma 14).
Staff and Clef

Set the key signature to something:
K:none (or K:C)

Unfortunately, I don't think you can change the percussion clef symbol (without changing the music font).
But, if you're trying to display a rhythm part (as apposed to an actual percussion part), you might want to remove the clef symbol entirely:
clef=none

Remove the spaces around the equals sign when declaring the number of staff lines:
stafflines=1

Stem direction (optional)

Set the stem direction in the voice field:
V:1 stem=up

MIDI Output

Send the MIDI output to the percussion channel:
%%MIDI channel 10

Choose a percussion instrument using standard MIDI percussion mapping numbers.*
For example: to put Acoustic Snare (38) on the middle staff-line ("B"):
%%MIDI drummap B 38

Working Code

X:1
T:Percussion example
M:4/4
L:1/8
K:none clef=perc stafflines=1
V:1 stem=up
%%MIDI channel 10
%%MIDI drummap B 38
BB B2 B2 B/2B/2B/2B/2 |

* Such as table A.8.2 Percussion Instruments, as found in Guido Gonzato's Making Music with ABC 2, p. 184.

ABC notation: percussion / rhythm staff


Setting standards on boundary length

Question: When there is a standard length for cricket pitches,  why aren't there such standards for boundary sizes?
Answer: The ICC do specify boundary sizes as do many competitons.   I would suggest the reason that the laws remain silent on this is the wide variety of sizes of ground from small chocolate box grounds to massive international fields.
Answer: There hasn't been any fixed rules given by the International Cricket Council, but they have said that a ground should have a minimum size of 137 meters appromxicately 68 meters from either side of the pitch although it varies on whic pitch is used on the given day.
The shortest boundary should be around 60meters and longest one should be around 83 meters from the center of the pitch.Also the distance between the boundary ropes and the advertising boards should be mimimum 3 metres.Check this link
http://www.sportscourtdimensions.com/cricket/
Comment: Could you give some references to support this answer?

Setting standards on boundary length


Group policy and OpenLDAP

Question: Is there any sort of group policy mechanic for OpenLDAP? And just like the GUI tool OpenLDAP is there a version of the GPMC for OpenLDAP's group policy?
Answer: OpenLDAP is just an LDAP server. Of course, you could use it to store something like group policies (in fact, the GP equivalent on MacOS is stored inside the OpenLDAP directory part of OpenDirectory), but there is no general mechanism for group policies on Linux or any other unixoid OS.

Group policy and OpenLDAP


nokogiri not installing correctly for ruby-1.9.1

Question: I have recently installedHi everyone,
I have recently installed ruby-1.9.1 using rvm. I have tried installing
nokogiri following this guide:
https://github.com/tenderlove/nokogiri/wiki/what-to-do-if-libxml2-is-being-a-jerk
but I am still getting the following error once the gem is installed:
HI.  You're using libxml2 version 2.6.16 which is over 4 years old and has
plenty of bugs.  We suggest that for maximum HTML/XML parsing pleasure, you
upgrade your version of libxml2 and re-install nokogiri.  If you like using
libxml2 version 2.6.16, but don't like this warning, please define the constant
I_KNOW_I_AM_USING_AN_OLD_AND_BUGGY_VERSION_OF_LIBXML2 before requring nokogiri.
I have also ensured that libxml2 I have installed in my leopard operating system is greater than 2.6:
$fink list libxml2
Information about 11516 packages read in 2 seconds.
 i   libxml2          2.7.8-102    XML parsing library, version 2
 i   libxml2-bin      2.7.8-102    XML parsing library, version 2
(i)  libxml2-py25     2.7.8-1      Python bindings for libxml2 library
     libxml2-py26     2.7.8-1      Python bindings for libxml2 library
     libxml2-py27     2.7.8-1      Python bindings for libxml2 library
     libxml2-rb18     0.5.4-1      Ruby bindings for libxml2
 i   libxml2-shlibs   2.7.8-102    XML parsing library, version 2

Comment: I am a bit confused why you'd install Ruby 1.9.1, which is known to be buggy, when RVM could just as easily install 1.9.2, which is the recommended version. See `rvm list known` for the versions RVM knows about.
Answer: So, either nokogiri isn't getting fully rebuilt, or it is but it's getting rebuilt against another version that's still living on your system. The easiest thing is to try is gem uninstall nokogiri && gem clean && gem install nokogiri. Be sure to uninstall every version if you have more than one.
The next thing is to try to ensure that the gem is actually being built against the version of libxml listed by fink. Try removing other versions (perhaps installed by MacPorts or Homebrew?) and rebuilding the gem.
If that doesn't help, we'll need to try troubleshooting the dynamic linker paths. I'm not so up on how to do that on OS X, so let's see if any of the above solutions help first.


jq: error (at :125): Cannot index array with string "DefId"

Question: I have below json data. Need help in parsing it.
{
  "e4624072-a9a2-4181-9649-550b9cfeb7cd||220000d7f738801": {
    "List": [
      {
        "Insts": [
          {
            "DefId": "A1",
            "data1": 1073741824,
            "data2": 0,
            "data3": 0
          }
        ]
      }
    ],
    "name": [
      "AMIT||220000d7f728801"
    ],
    "id": "e4624072-a9a2-4181-9649-550b9cfeb7cd||220000d7f738801",
    "endTime": 96285337200000
  },
  "0b1141b2-c2de-47c9-aa0c-2742f92b63f2||220000d7f738801": {
    "List": [
      {
        "Insts": [
          {
            "DefId": "B1",
            "data1": 5368709120,
            "data2": 5368709120,
            "data3": 5368709120
          }
        ]
      },
      {
        "edigest": "MV6shIv5NE5vWkc0cx6Q/JTwid4=",
        "csDefRef": "BoostYES_B1"
      },
      {
        "edigest": "MV6shIv5NE5vWkc0cx6Q/JTwid4=",
        "csDefRef": "BoostOff_B1"
      }
    ],
    "name": [
      "AMIT||220000d7f728801"
    ],
    "id": "0b1141b2-c2de-47c9-aa0c-2742f92b63f2||220000d7f738801",
    "lifeCycle": 0
  },
  "23e529f9-b2f3-4730-9b28-4ee05ca678b6||220000d7f738801": {
    "List": [
      {
        "Insts": [
          {
            "DefId": "A2",
            "data1": 1073741824,
            "data2": 0,
            "data3": 0,
            "lastUpdateTime": 1619541451476,
            "origInitialVal": 1073741824
          }
        ]
      }
    ],
    "name": [
      "AMIT||220000d7f728802"
    ],
    "id": "23e529f9-b2f3-4730-9b28-4ee05ca678b6||220000d7f738801",
    "endTime": 96285337200000,
    "lifeCycle": 0
  },
  "66b2229b-2c16-4d54-b2a8-fcc1baeaf51c||220000d7f738801": {
    "List": [
      {
        "Insts": [
          {
            "DefId": "B2",
            "data1": 10737418240,
            "data2": 10737418240,
            "data3": 10737418240,
            "lastUpdateTime": 1637766239807,
            "origInitialVal": 10737418240
          }
        ]
      },
      {
        "edigest": "MV6shIv5NE5vWkc0cx6Q/JTwid4=",
        "csDefRef": "RMN_B2"
      }
    ],
    "name": [
      "AMIT||220000d7f728801"
    ],
    "startTime": 1637766000000,
    "id": "66b2229b-2c16-4d54-b2a8-fcc1baeaf51c||220000d7f738801",
    "endTime": 1637852400000,
    "lifeCycle": 0
  },
  "b896eb1b-d6b0-432b-8925-af17431c0f3e||220000d7f738801": {
    "List": [
      {
        "Insts": [
          {
            "DefId": "B3",
            "data1": 2147483648,
            "data2": 2147483648,
            "data3": 2147483648,
            "lastUpdateTime": 1635692405780
          }
        ]
      },
      {
        "edigest": "MV6shIv5NE5vWkc0cx6Q/JTwid4=",
        "csDefRef": "BoostYES_B3"
      },
      {
        "edigest": "MV6shIv5NE5vWkc0cx6Q/JTwid4=",
        "csDefRef": "BoostOffCS_B3"
      }
    ],
    "name": [
      "AMIT||220000d7f728801"
    ],
    "id": "b896eb1b-d6b0-432b-8925-af17431c0f3e||220000d7f738801",
    "lifeCycle": 0
  }
}

Required output is as below :
AMIT||220000d7f728801,A1,1073741824,0,0
AMIT||220000d7f728801,B1,5368709120,5368709120,5368709120
AMIT||220000d7f728801,A2,1073741824,0,0
AMIT||220000d7f728801,B2,10737418240,10737418240,10737418240
AMIT||220000d7f728801,B3,2147483648,2147483648,2147483648

I tried to execute below jq to start with but it giving as mentioned in title. This might be due to DefId is not present at all the places. Similarly for data 1, data2 and data3.
jq -r '.[] | ."name", ."List"[]."Insts"."DefId"'

What is the right jq command in order to get the correct output?
Comment: `Insts` is a list of dictionaries.  I don't think you're taking that into account.
Answer: Unfortunately you say nothing about constraints (guaranteed existence of fields, lengths of arrays, etc.) regarding your data structure. Therefore, simply based on what you have provided, this will extract the contents into your desired output format:
jq -r '.[] | [.name[0] , (.List[0].Insts[0] | .DefId, .data1, .data2, .data3)] | join(",")'

AMIT||220000d7f728801,A1,1073741824,0,0
AMIT||220000d7f728801,B1,5368709120,5368709120,5368709120
AMIT||220000d7f728801,A2,1073741824,0,0
AMIT||220000d7f728801,B2,10737418240,10737418240,10737418240
AMIT||220000d7f728801,B3,2147483648,2147483648,2147483648

Demo
Answer: You can dynamically walk within List.Insts array without error by using
.List[].Insts | select( . != null ) for the returning values of to_entries[]
while it's straightforward to extract the value for the name key.
Then join the components of the formed array through use of wrapper square brackets such as
jq -r 'to_entries[] | .value | [ .name[] , (.List[].Insts | select( . != null ) | .[] | .DefId, "\(.data1)", "\(.data2)", "\(.data3)" ) ]  | join(",")'

Demo


How many positive integer solutions are to a system of linear equations?

Question:
Given the linear system of equations:
  $$
\begin{cases}
x_1 + x_2 + x_3 = n\\
x_1 + x_2 + x_3 + x_4 + x_5 = 3n\\
2x_1 +2x_2 +2x_3 +x_4 +x_5 +3x_6 +3x_7 +3x_8 =10n
\end{cases}
$$
  how many solutions are in $\mathbb N\cup\{0\}$?
The solution must not be using sum notation like $\sum y$.

I know how to find the number of solutions to the regular equations like $x_1+x_2+x_3+\dots=n$ but I'm not sure how to do this for a system of equations. I thought of substituting some $x$'s:
$$
x_1 + x_2 + x_3 =3n - (x_4 + x_5)\\
x_4 +x_5=10n-2(x_1 +x_2 +x_3)  -3(x_6 +x_7 +x_8)\\
\implies
x_1 + x_2 + x_3=3n-(10n-2(x_1 +x_2 +x_3)  -3(x_6 +x_7 +x_8))\\
\implies x_1+x_2+x_3+3(x_6+x_7+x_8)=7n \quad *
$$
As far as I understand finding the number of solutions for the system is equivalent to finding the number of solutions to the equation *.
The only next step from here I can think of is using generating functions:
$$
(1+x+x^2+\dots)^3(1+x^3+x^6+x^9+\dots)^3
$$
and we need to find the coefficient of $x^{7n}$.
From the closed form identities we have:
$$
\sum_{k=0}^{\infty} {3-1+k\choose k}x^k\cdot \sum_{i=0}^{\infty} {3-1+i\choose i}x^{3i}
$$
But I have no idea now how to find the coefficient of $7n$ from here and certainly not without using some kind of sum notation.
Comment: Title says positive, body says ℕ ∪ {0}.
Comment: You don't mention how many unknowns there are.
Answer: This is more of a hint rather than a solution, but still:
You have $$x_1+x_2+x_3=n.$$ Substituting this into your second equation gives $$x_4+x_5=2n.$$ Substituting both in the third gives $$x_6+x_7+x_8=2n.$$
If I've understood correctly you can solve this new system of equations since each $x_i$ appears in exactly $1$ equation.
Comment: @Yos Not quite. Remember (by the "stars-and-bars method") that the number of ordered partitions of $n$ items into $k$ bins is $\frac{(n+k-1)!}{n!(k-1)!}$, so you should have $\frac{(n+2)!}{n! 2!} \frac{(2n+1)!}{(2n)!1!} \frac{(2n+2)!}{(2n!)2!)}$, where each factor represents the number of solutions to one of the equations. (Note that this expression can be considerably simplified!)
Comment: It's the same formula - he's just expanded the binomial coefficient. The answer $2n+1$ is false though
Comment: Then the number of solutions would be ${2n+1\choose 1}=2n+1$
Comment: @ConnorHarris I'm not familiar with the formula you posted. As far as I know there're ${n-1+k\choose k}$ solutions (over $\mathbb N\cup \{0\}$) to equation of type $x_1+x_2+\dots +x_n=k$ I'm not sure where you get the factorial.
Comment: oh I noticed the mistake it's ${2n+2\choose 2n}=(2n+1)(n+1)$
Comment: @asdf For completeness, it would be nice if you get to a final answer incorporating the comment by Connor Harris.


Attaching maps of products of CW-complexes.

Question: I am a bit confused about how the "product attaching-maps" work.
For instance, if I wanted to find the cell structure for $S^1\times S^1$ then I can proceed similarly to here.
So we will call $e_0$ and $f_0$ the zero-cells of $S^1$ and $S^1$, respectively. Similarly, $e_1$ and $f_1$ are the respective one-cells. Then $\phi$ and $\psi$ are the attaching maps taking the boundary of $D^1$ to $e_0$ and $f_0$ respectively.
When we attach the cell $e_1\times f_1$ to the one-skeleton of $S^1\times S^1$, we do so via the attaching map $\phi\times \psi$. But $\phi\times \psi$ are only defined on $\partial D^1 \times \partial D^1$, and not on $\partial (D^1\times D^1) = (\partial D_1\times D_1) \cup (D_1\times \partial D_1)$. This is where I get confused.
If anyone can explain what's going on I would highly appreciate it.
Answer: Be careful!  You forgot the 1-cells $e_0\times f_1$ and $e_1\times f_0$ which are attached to the 0-cell $e_0\times f_0$ in the obvious way to form the 1-skeleton $S^1\vee S^1$ of $S^1\times S^1$.  Now glue your 2-cell $e_1\times f_1$ to the 1-skeleton.
Edit to bring the discussion into the answer The attaching map $\phi$ of a cell $e^n$ of a CW-complex $X$ defines the characteristic map of this $n$-cell
$$
e^n\hookrightarrow X_{n-1}\amalg e^n\to X_n\hookrightarrow X
$$
and restricting the characteristic map to $\partial e^n$ gives the attaching map, so with an abuse of notation they have the same name $\phi$.  Then the product of attaching maps is actually taken as the restriction of the set-theoretic product of characteristic maps (using $e^n\times e^m\cong e^{n+m}$), so they are not the set-theoretic product of attaching maps but $\phi\times 1\cup 1\times\psi$ (where the $1$ is the obvious identification).
Comment: Sorry I didn't phrase what I mean properly. I see that we have a zero-cell and two-one cells and their attachment maps make sense to me. My issue is that when I glue the 2-cell to the one-skeleton, the attaching map is not well-defined. Intuitively, I see what should happen. My issue is with where I am misunderstanding how $\phi\times\psi$ works.
Comment: The attaching map is well-defined.  The attaching map that we write as $\phi\times\psi$ is not the set-theoretic $\phi\times\psi$, but $\phi\times 1\cup 1\times\psi$.
Comment: That makes sense (if you write this as an answer I'll accept it). Thank you.
Comment: I've added some details of this discussion to the answer.


How to compute theoretical compression limit?

Question: Assume we have a sensor field with dimension M*M. In order to apply any data compression technique, first I want to know what is the compression limit or minimum entropy of the entire sensor field. How could I compute the minimum entropy or compression limit for the sensor field?
or
Actually I want to have the theoretical compression limit. Let's put the problem for an image. I want to know whether there are any mathematical methods to calculate the theoretical compression limit. Please let me know or suggest any readings to formulate the problem.
Thanks
Answer: The "entropy" is defined only within the context of a probabilistic model for the data.  If you characterize the image as a set of $M^2$ distinct "characters" and assume the frequencies of those characters adequately reflect their probabilities, then you need only apply the formula
Entropy = Sum (over all characters $c$) of [-log(probability of $c$) * probability of $c$].
A standard (but by no means the only) estimate of the probability of a character in a set of $N = M^2$ characters is
Estimated probability of $c$ = (Number of occurrences of $c$) / $N$.
Comment: Thanks for your quick reply. Yes I know this straight forward computation. But I am not sure is this the lower bound of the entropy or upper bound.
Comment: Bound in what sense?  You need a context here.  What set of values are you trying to bound and how is it defined?  Read the Wikipedia segment I linked to: it has some good examples.  For instance, if you model the image as one realization of a set of possible images, then its entropy equals -1*log(1) = 0.  You can't do better than that!
Comment: Let us take an example, we have a sensor filed of M*N dimension and sensors are uniformly distributed in grid architecture. let say they are sensing the temperature in the agriculture field. and it is obvious they have spatial correlated data. Assume the they are sensing 35,40,45 and 50 degree C. Now I want to calculate the minimum entropy, is this follow the same formula as you said earlier in your post?
Comment: Nope: This is a different probability model.  You need to specify the nature of the spatial correlation and estimate its parameters.
Comment: Entropy calculations for fully specified data have been used to get a theoretical bound on how much that data can be compressed. My specified filed is the data from sensor filed. And I want to calculate the minimum entropy (assuming lossless compression) for entire sensor field not for individual nodes.


Conversão de String para int

Question: meu xml
`

<android.support.design.widget.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    app:layout_constraintTop_toTopOf="parent"
    tools:layout_editor_absoluteX="0dp"
    tools:ignore="MissingConstraints">

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.CardView
    android:id="@+id/cardfejaum"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="16dp"
    android:layout_marginTop="20dp"
    android:elevation="50dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/appBarLayout">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    <ImageView
        android:id="@+id/fejaum"
        android:layout_width="386dp"
        android:layout_height="200dp"
        android:background="@drawable/fejaum"
        android:padding="4dp"
        android:src="@color/transparencia"
        tools:layout_editor_absoluteX="8dp"
        tools:layout_editor_absoluteY="200dp" />

    <android.support.design.widget.TextInputLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:textColorHint="#fff"
        tools:layout_editor_absoluteX="168dp"
        tools:layout_editor_absoluteY="205dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/edt"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:backgroundTint="#fff"
            android:hint="Comprado:"
            android:inputType="number" />

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="No estoque"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Feijão"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff"
        android:textSize="32sp" />

    <SeekBar
        android:id="@+id/seekBar"
        android:layout_width="110dp"
        android:layout_height="15dp"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="158dp"
        android:layout_weight="1"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:max="4"
        android:progressDrawable="@drawable/custom_seek_bar"
        android:progress="6"/>
    <TextView
        android:id="@+id/tvseek"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="280dp"
        android:layout_marginTop="150dp"
        android:text="0"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="120dp"
        android:layout_marginTop="150dp"
        android:text="0"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ok"
        android:textColor="#fff"
        android:layout_marginTop="110dp"
        android:layout_marginLeft="200dp"
        android:background="@null"/>

</android.support.v7.widget.CardView>

<android.support.v7.widget.CardView
    android:id="@+id/cardarroz"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="4dp"
    android:elevation="50dp"
    app:layout_constraintEnd_toEndOf="@id/cardfejaum"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@id/cardfejaum"
    app:layout_constraintTop_toBottomOf="@+id/cardfejaum">

    <ImageView
        android:id="@+id/arroz"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@drawable/arrozbranco"
        android:padding="4dp"
        android:src="@color/transparencia" />

    <android.support.design.widget.TextInputLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="130dp"
        android:textColorHint="#fff"
        tools:layout_editor_absoluteX="168dp"
        tools:layout_editor_absoluteY="205dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/edtarroz"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:backgroundTint="#fff"
            android:hint="Usado:"
            android:inputType="number" />

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="Restante"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/tvarroz"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="0"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Arroz"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff"
        android:textSize="32sp" />

</android.support.v7.widget.CardView>

<android.support.v7.widget.CardView
    android:id="@+id/cardaçucar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="208dp"
    android:elevation="50dp"
    app:layout_constraintEnd_toEndOf="@id/cardfejaum"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintStart_toStartOf="@id/cardfejaum"
    app:layout_constraintTop_toBottomOf="@+id/cardfejaum">

    <ImageView
        android:id="@+id/açucar"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:background="@drawable/acucarrefinado"
        android:padding="4dp"
        android:src="@color/transparencia" />

    <android.support.design.widget.TextInputLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="130dp"
        android:textColorHint="#fff"
        tools:layout_editor_absoluteX="168dp"
        tools:layout_editor_absoluteY="205dp">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/edtaçucar"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:backgroundTint="#fff"
            android:hint="Usado:"
            android:inputType="number" />

    </android.support.design.widget.TextInputLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="150dp"
        android:text="Restante"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:id="@+id/tvaçucar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="150dp"
        android:text="0"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Açucar Refinado"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        android:textColor="#fff"
        android:textSize="32sp" />

</android.support.v7.widget.CardView>

Meu código java
`package org.lucas.aplicativo;

import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;

public class Principal extends AppCompatActivity {
    CardView cardfejaum, cardarroz, cardaçucar;
    TextInputEditText edtarroz, edtaçucar, edt;
    TextView tv , tvarroz, tvaçucar, tvseek;
    SeekBar seekBar;
    Button btn;
    int progresso;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_principal);
        cardfejaum = findViewById(R.id.cardfejaum);
        cardarroz = findViewById(R.id.cardarroz);
        cardaçucar = findViewById(R.id.cardaçucar);
        edt = findViewById(R.id.edt);
        edtarroz = findViewById(R.id.edtarroz);
        edtaçucar = findViewById(R.id.edtaçucar);
        tv = findViewById(R.id.tv);
        tvarroz = findViewById(R.id.tvarroz);
        tvaçucar = findViewById(R.id.tvaçucar);
        seekBar = findViewById(R.id.seekBar);
        tvseek = findViewById(R.id.tvseek);
        btn = findViewById(R.id.btn);
        seekBar.setProgress(0);
        seekBar.setMax(15);
        calcular();
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int prog, boolean b) {
                progresso = prog;
                tvseek.setText(" "+prog);
                calcular();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                tvseek.setText(" "+progresso);
                calcular();
            }
        });

        tv.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        }

    public void calcular() {
    int sub = Integer.parseInt(edt.getText().toString());
    int sub2 = Integer.parseInt(tvseek.getText().toString());
    int calc = sub - sub2;
    tv.setText(String.valueOf(calc));
}
}`

Comment: me desculpe é que sou novo aqui então...
Comment: Que problema? onde que ocorre? precisamos de mais detalhes, não faça a pergunta toda no enunciado
Comment: @LucasSantosSilva clique em [editar](https://pt.stackoverflow.com/posts/294563/edit) e adicione mais informações a sua pergunta
Comment: Relacionado: [Como considerar um EditText vazio como "0"](https://pt.stackoverflow.com/q/89367/2541)
Answer: Quando você usar Integer.parseInt pode ocorrer um NumberFormatException. Como você está colocando direto o Integer.parseInt(tvseek.getText().toString()); isso pode dar um problema caso o texto do campo texto esteja vazio ou com uma letra por exemplo.
Answer: Você pode usar 2 formas, conforme necessidade:
Integer.parseInt(valorString): retorna um Integer.
ou
Integer.valueOf(valorString): retorna um primitivo (int)

Como o prmottajr disse, você pode ter problemas com um String vazio.
Um exemplo de como tratar:
if (valorString.length() > 0)
    Integer.parseInt(valorString);

Links úteis:
Integer
Diferença entre int e Integer em Java

Conversão de String para int


Is there a function between real vector spaces that satisfies exactly one of the requirements to be a linear transformation?

Question: As almost everyone reading this probably knows, a function $T$ from one real vector space to another is defined to be a linear transformation if for all vectors $\mathbf{u}, \mathbf{v}$ in the domain and all real $a$, (i) $T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v})$, and (ii) $T(a\mathbf{u}) = aT(\mathbf{u})$.  Does anyone know of an example of two real vector spaces and a function $T$ from one to the other that satisfies one of the requirements but not both?  I'm assuming there is one, or else it wouldn't be defined that way.
I can show that if $T$ satisfies (i), then (ii) holds for all rational $a$.
Is there such an example where the vector spaces are both finite-dimensional?
I am not interested in complex vector spaces or additional requirements such as norms.
I browsed the Similar Questions and couldn't find an answer.  I apologize if this is a duplicate question.
Stefan (STack Exchange FAN)
Comment: Related: http://math.stackexchange.com/questions/106785/an-additive-map-that-is-not-a-linear-transformation-over-mathbbr-when-ma?rq=1
Answer: An example that satisfies $(i)$ but not $(ii)$:
We can construct a function from $\mathbb{R}$ to itself; construct a basis for $\mathbb{R}$ over $\mathbb{Q}$ by taking the set $\{1, \sqrt{k}\}$ for some squarefree $k$, and extend this to a basis using the axiom of choice. Then define $f(1)=1$ and $f$ to be $0$ for all other basis elements. If we also define $f$ to be linear from this vector space of $\mathbb{R}$ over $\mathbb{Q}$, then $f$ is only $\mathbb{Q}$-linear and additive in $\mathbb{R}$, but it can be seen that it's nonhomogeneous, as $f(\sqrt{k}\cdot 1) = 0$ while $\sqrt{k}f(1)=\sqrt{k}$.
Comment: Thanks.  I mostly understand this.  Is this basis what is often called a "Hamel basis"?  Do you know if there are any examples satisfying (i) but not (ii) that don't require the Axiom of Choice, or can this be proven to be impossible?
Comment: Yep, this is exactly a Hamel basis. It seems likely that there is such an example, but unfortunately I don't know any off the top of my head.
Comment: Your vector space is over $\mathbb Q$. What does multiplication by $\sqrt{k}$ mean? It is not a scalar.
Answer: I'll give one example of a function satisfying (ii) but not (i) that I think is simple. Consider $T:\mathbb R^2 \to \mathbb R$ mapping $(r\cos\theta, r\sin\theta)$ to $r\theta$ for $\theta \in [0, \pi)$ and to $-r(\theta - \pi)$ for $\theta \in [\pi, 2\pi)$.
Comment: $r\cos^3\theta$ would also work.
Comment: You're right. Forgot that the scalar can be negative. I'll fix that now.
Comment: @JonasMeyer That's right. Your other example is also simpler. (I think you have $r|\cos\theta|\cos\theta$ somewhere.)
Answer: For ii) but not i), I think $f:\mathbb{R}^2 \rightarrow \mathbb{R}$ given by $f(x,y) = (x^3 + y^3 )^{1/3}$ is the simplest example. For i), examples actually exist for when the domain of $f$ is simply $\mathbb{R}$ - see here.
Comment: Thank you.  Yours is the first obviously correct answer that I spotted, so I am accepting it.  I am embarrassed that there is such a simple example.  I looked at the link you gave, and it appears that finding an example of (i) but not (ii) is much more difficult, and I didn't have time absorb it fully.  In those examples, can the target also be finite-dimensional?  Is the Axiom of Choice required?  I'll try to read it myself tomorrow.  To anyone else who gave a correct example, I apologize, but I can only accept one answer.
Answer: (ii) but not (i):
$f:\mathbb{R}^2\to\mathbb{R}^2$,
$f(r\cos\theta,r\sin\theta) = \theta(r\cos\theta,r\sin\theta)$
where $\theta\in[0,\pi), r\in\mathbb{R}$
This is well defined because every point in $\mathbb{R}^2$ can be written in terms of polar coordinates, $f(0,0)=(0,0)$ independently of $\theta$.
$f(ax,ay)=f(ar\cos\theta,ar\sin\theta)=a\theta(r\cos\theta,r\sin\theta)=af(x,y)$.
$f((0,1)+(1,0)) = f(1,1) = \frac{\pi}{4}(1,1)$
$f(1,0) + f(0,1) = 0 + \frac{\pi}{2}(0,1) \ne \frac{\pi}{4}(1,1)$
Comment: A variant of this idea: $T:\mathbb R^2\to\mathbb R$, $T(x,y)=\dfrac{|x|x}{\sqrt{x^2+y^2}}$ if $(x,y)\neq (0,0)$, $T(0,0)=0$.
Answer: In one dimension, the i) but not ii) half of this reduces to Cauchy's functional equation
$$
f(x+y)=f(x)+f(y)
$$
which has nonlinear solutions, but not nice ones.
Essentially, i) guarantees that your function is a linear transformation between rational vector spaces. But not every $\Bbb{Q}$-linear transformation is also $\Bbb{R}$-linear, even if its domain and range are $\Bbb{R}$-vector spaces...
Comment: Can you give an example of a $\mathbb{Q}$-linear transformation that is not $\mathbb{R}$-linear?  Does such a linear transformation exist between finite-dimensional vector spaces? Is there one that does not require the Axiom of Choice, or can it be proven that the Axiom of Choice or some weak form of it is necessary?  I'll check out the link.
Comment: @StefanSmith: Any such thing is non-Lebesgue-measurable, which as I understand it means you need some version the axiom of choice to prove it exists (though I'm no expert). I don't think the Wikipedia article mentions this, but [here](http://imi.kyushu-u.ac.jp/~ssaito/eng/maths/Cauchy.pdf)'s a proof. Writing  down such a function is either impossible or easy, depending on how explicit you want to be; it boils down to "pick a $\Bbb{Q}$-basis for $\Bbb{R}$, and then arbitrarily choose values for the function on these basis elements."


Goodness of fit for discrete data: best approach

Question: The data:
For the purposes of this question/communication we can assume the data looks like rnbinom(1000,size=0.1,prob=0.01) in R, which generates a random sample of 1,000 observations from a negative binomial distribution (with size=0.1 and probability of success prob=0.01). This is the parametrization where the random variable represents the number of failures before size number of successes. The tail is long, and 1,000 observations is not a lot of data.
The problem:
I have been given some data (integer on {1,2,....}) [see above] (1,500 data points) and asked to find "best fit" distribution and estimates of any parameters. I know nothing else about the data. I'm aware I this is not a very large sample for data with a long tail. More data is a possibility.
What I've done:
I have considered using a likelihood ratio test by fitting two different distributions to the data, but I don't think this applies (as in, I cannot determine appropriate critical p-values) unless the two distributions are nested...
I then considered using a Kolmogorov-Smirnov test (adjusted for discrete data) but, in R anyway, it complained it could not compute a p-value for "data with ties".
What is the best way for me to go about testing/determining the fit of different distributions in this context?
Here are some other things I have considered:

Ask for (lots) more data. But will this help? Will I be able to use asymptotic results, for instance?
Consider some bootstrap/re-sampling/monte-carlo scheme? If so, is there a standard reference I can/should read to learn how to do this correctly? Thanks
Answer: If I understood your question correctly, you just need to fit data to distribution. In this case, you could use one of functions in R packages, such as fitdistr from MASS package, which uses maximum likelihood estimation (MLE) and supports discrete distributions, including binomial and Poisson.
Then, as a second step, you would need to perform one (or more) of goodness-of-fit (GoF) tests to validate results. Kolmogorov-Smirnov, Anderson-Darling and (AFAIK) Lilliefors tests all are not applicable to discrete distributions. However, fortunately, chi-square GoF test is applicable to both continuous and discrete distributions and in R is a matter of calling stats::chisq.test() function.
Alternatively, as your data represents a discrete distribution, you can use vcd package and its function goodfit(). This function can be used either as a replacement for standard GoF test chisq.test(), or, even better, as a full workflow (distribution fitting and GoF testing). For the full workflow option, just use default setup and do not specify parameters par (you can specify size, if type = "nbinomial"). The parameters will be estimated, using maximum likelihood or minimum chi-square (you can select the method). Results can be obtained by calling summary() function.
Comment: Discrete KS tests do exist in fact: http://www.stat.yale.edu/~jay/EmersonMaterials/DiscreteGOF.pdf


Viewing a Server's GAC from another machine using Windows Explorer doesn't see all the DLL's

Question: When I view a Windows Server's GAC (through Internet Explorer) I can see all the dll's that have been registered for the cache. However, when i navigate to the same location from another server, some of the dll's are not visible. Why is that? I have the same rights on the each server (administrator). Machines are both WK28.
Answer: The GAC folders are a virtual file system.  They are not real folders with real files in them.  What you see in the virtual filesystem is based on what assemblies are available to the version of the dotnet framework available to the system running explorer.exe.


How ViewModel could catch exception not thrown by the above layer?

Question: Currently developing an Android application in Kotlin I decided to learn the MVVM pattern.
I'm in a situation where I have :
Fragment --> ViewModel --> Controller --> Repository
My controller only serves as a cache for the current session.
Currently able to contact my API, I wanted to handle potential exceptions that might occur such as "UnknownHostException", "SocketTimeoutException" and display a different message for each Exception.
NB : I used retrofit 2.6.0 with coroutines to do the job
The steps to request contact to the API are as follows:

The fragment subscribes to the viewModel variables

The viewModel launches its "fetchCommandList" method where it launches a coroutine with a try/catch and asks the controller to return the list of commands.

The controller calls the repository if necessary.

The repository tries to retrieve the data in a try/catch block

And that's where my question comes in. If you've read correctly, my controller doesn't have a try/catch, however, if in the repository an exception is thrown, the viewModel catches it well and changes its LiveData which displays the specific message of the exception in the fragment.
I don't understand how the exception is able to "skip" the Controller layer and still arrive in the viewModel.
Below is the code for each layer, from the view to the model:
Fragment part about error LiveData
mviewModel.mErrorStatus.observe(viewLifecycleOwner, Observer {
        mbinding.fragmentCommandListRecyclerview.visibility = if (it != null) View.GONE else View.VISIBLE
        mbinding.fragmentCommandListErrorTextView.visibility = if (it != null) View.VISIBLE else View.GONE
        mbinding.fragmentCommandListErrorTextView.text = it
    })

ViewModel call to the controller
fun fetchCommandList(){
    //TODO : contact the controller method tha will firstly check is in list & if not result ask the repository to retrieve it
    viewModelScope.launch {
        mProgressBar.postValue(true)
        try {
            mCommandList.postValue(CommandControllerMock.getCommandsList())
            mCommandActive.postValue(CommandControllerMock.getCurrentCommand())
        }
        catch (e: UnknownHostException) {
            //this exception occurs when there is no internet connection or host is not available
            //so inform user that something went wrong
            mErrorStatus.postValue(e.message)
        } catch (e: SocketTimeoutException) {
            //this exception occurs when time out will happen
            //so inform user that something went wrong
            mErrorStatus.postValue(e.message)
        } catch (e: Exception) {
            //this is generic exception handling
            //so inform user that something went wrong
            mErrorStatus.postValue(e.message)
        }
        finally {
            mProgressBar.postValue(false)
        }

    }

}

Controller getCommandsList called by the viewModel (NO TRY/CATCH)
override suspend fun getCommandsList(): List<Command> {
        if(m_commandList.size <= 0){
            //Todo: replace by auth.userID
            //Todo : before return the result, check if a command is already active to set currentCommand
            val returnedList = m_commandRepository.getAllCommandByUser(USER_ID)
            returnedList?.let{
                m_commandList = it.toMutableList()
            }
            checkForActiveCommand()
        }
        return m_commandList
}

Repository method calling the API endpoint
override suspend fun getAllCommandByUser(idUser: String): List<Command>? {
    try {

        val response = apiService.getAllCommandByUser(idUser)

        if (response.isSuccessful) {
            return response.body()
        } else {
            throw Exception("not 200 code")
        }
    } catch (e: Exception) {
        //this is generic exception handling
        //so inform user that something went wrong
        throw e
    }
}

So if for example, I disabled Internet on my phone I received the following message due to UnknownHostException  :
"Unable to resolve host "MY_API_ADRESS" : No adress associated with hostname"
If I put a readTimeout of 1sec in OkHTTP I received the following message due to SocketTimeoutException :
"timeout"
I just don't understand the part where I forget to throw the exception in controller but it still catch by the ViewModel .
Comment: well, you can test it. write a function to throw an exception with a try catch like yours and then one without, see if they are different or the same
Comment: what is the point of having a try catch inside your repository and then inside the catch having `throw e` ?
Comment: I want to propagate the exception until the viewModel to handle the UI display in it.

The repository just have to give the exception to lower layers
Comment: so what purpose does the try catch serve if it's catching the excepting and throwing the same thing ? then your try catch is redundant
Comment: I think I doesn't know how exceptions work, for me, if I didn't do that in my repository, the exception would have been lost.
Comment: Thanks for your help :) !
Answer: It is natural for suspended functions to propagates runtime exceptions to top caller, until it either hits a try and catch block or coroutine scope, which is then either handled by exceptionHandler or cause the app to crash.
So in your case, nothing is suspicious, and the try&catch with exception rethrowing in repository layer is unnecessary.
See Coroutines exception handling doc
Comment: yes, and check exception handling in Coroutines doc, which I added in the comment
Comment: So, if I understand well (sorry I'm not english), the exception will be "automatically" thrown until the top caller (my ViewModel here) ?

So I can delete the try catch in my repository but let the one in ViewModel ?
Comment: Thanks for your help !!


Add to Cart Button not showing next to product in Woocommerce

Question: I have one weird issue with add to cart button into product archives page. When i open some product like here
then i dont see "Add to Cart" button, but if i check in debugger i  see that in code add to cart link exist.. This is CSS class for selected element:
.woocommerce ul.products li.product .price, .woocommerce-page ul.products li.product .price {
color: #FFF;
display: block;
font-weight: 300;
margin-bottom: 0;
font-size: 16px;
}

and code from Inspect Element:

Přida do košíku

can someone to help me , or give me some tip how to resolve?
EDIT: When i inseert this CSS button is showing but float too big into page:
#layout .woocommerce a.button, .woocommerce-page a.button, .woocommerce button.button, .woocommerce-page button.button, .woocommerce input.button, .woocommerce-page input.button, .woocommerce #respond input#submit, .woocommerce-page #respond input#submit, .woocommerce #content input.button, .woocommerce-page #content input.button {
display:inherit;
}

Comment: You can check it by removing the `absolute` value or just add `position: relative` to products or product class.
Comment: add_to_cart_button has `absolute` value. Please check the closest parent element which has `relative` property. That might be the reason.
Comment: I checked but cant find near object with relative property.
Comment: Does add_to_cart_button have an `z-index` value?
Comment: I dont know really.
Comment: If you haven't set up any relative parent element, your absolute button will be placed 10px from top and left side of the browser. You may want to read here to learn more: https://stackoverflow.com/questions/4457790/difference-between-style-positionabsolute-and-style-positionrelative
Comment: I didnt haved set nothing.. Its from Remix theme and Woocommerce.
Comment: Can't access your link. Its with a coming soon
Comment: Anyone? Still cant resolve this myself.
Answer: Try this:
display: inline-block;
opacity: 1;


Difference between these two Authentication Ticket making ways?

Question: I came across this part of code in a MVC Application
  var authTicket = new FormsAuthenticationTicket(
                                                           1,                             // version
                                                           oModel.UserID,                      // user name
                                                           DateTime.Now,                  // created
                                                           DateTime.Now.AddDays(30),   // expires
                                                           oModel.RememberMe,                   // persistent?
                                                           "Jt_AutoLogin"
                                                           );
                        string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
                        var authCookie = new HttpCookie("Jt_AutoLogin", encryptedTicket);
                        if (authTicket.IsPersistent)
                        {
                            authCookie.Expires = authTicket.Expiration;
                        }
                        System.Web.HttpContext.Current.Response.Cookies.Add(authCookie);

and there was this code
FormsAuthentication.SetAuthCookie(oModel.UserID, oModel.RememberMe);
As far as I know, SetAuthCookie() method generates the authenticated ticket and adds it to the cookie collection.
But what about the first way?
If they are both indeed doing the same thing then what is the difference?
Answer: they both work
The SetAuthCookie method adds a forms-authentication ticket to either the cookies collection or the URL
the first one
var authTicket = new FormsAuthenticationTicket
allow you to add more user define data to it like expiration etc..
https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication(v=vs.110).aspx


Find the contrapositive of this lemma

Question: Lemma: If a harmonic function $h$ vanishes on two lines $L₁$ and $L₂$ and if the angle between $L₁$ and $L₂$ is not a rational multiple of $π$. Then $h$ vanishes identically.
The proof of this result can be found in: Harmonic functions with zeros on two lines
My question is:
Find the contrapositive of this lemma.
I want some thing like this: The function $h$ is not vanishes identically imply that $h$ vanishes on two lines $L₁$ and $L₂$ and the angle between $L₁$ and $L₂$ is a rational multiple of $π$
Comment: my question is what have you tried?
Comment: for example after a bit researching i found http://math.stackexchange.com/questions/298776/harmonic-functions-with-zeros-on-two-lines
Comment: @datodatuashvili: Repeated reflections produce a dense set of lines on which the function vanishes. However, some steps are not clear.
Comment: about harmonic functions this may help you http://www.maths.qmul.ac.uk/~boris/potential_th_notes.pdf
Comment: @datodatuashvili: But there is no enought informations on that example.
Comment: maybe proof is  long  term calculation procedure or something like this
Comment: @datodatuashvili: No, it is not clear in several sides
Answer: The lemma is of the form

Suppose X.  If A, then B.

There are two different statements that might be called the converse, depending on context.
First:

Suppose X. If B, then A.

Second:

If $B$, then $A$ and $X$.

But it seems from the question that you are actually looking for the contrapositive, not the converse. The converse will not negate the conclusion - in this case, the converse will assume $h$ does vanish identically.  In general the converse is the additional statement needed to turn an "only if" into an "if and only if".
For the contrapositive, based onthe form of the lemma, the two possibilities are

Suppose X. If not B then not A.

and

If not B then (not A or not X).

The first of those is more likely to be useful here. It would say

Suppose $h$ is a harmonic function that vanishes on two lines $L_1$ and $L_2$. If $h$ does not vanish identically, then the angle between the two lines is a rational multiple of $\pi$.

By the way, the reason that there are multiple options is that the original statement (like many) is not the most simple kind of "if/then"; it has a nested structure.
Comment: @AR1: I added some info about that
Comment: @ Carl Mummert: Yes, I mean the contrapositive.

Find the contrapositive of this lemma


Grails and Amazon SimpleDB

Question: How to setup Grails project to use Amazon SimpleDB?
One possibility is to install gorm-jpa plugin and use SimpleJPA library, but I couldn't setup it correctly.
Has someone experience with this combination?
Comment: Out of curiosity, what is the compelling use case for SimpleDB?
Comment: Just read http://aws.amazon.com/simpledb/#highlights: low touch, scalable, highly available, flexible, fast, inexpensive, ...
Answer: Try simpledb GORM plugin for grails: http://grails.org/plugin/simpledb
Answer: after many trials and errors i am managed to use simple jpa project from grails web application
I have used it :
using EntityManagerFactory and the JPA provider APIs
writing few service artifacts was able to use to simple bd features seamlessly
Answer: It can be done with the gorm-jpa plugin and simplejpa, but there are a lot of conflicts between the limitations in gorm-jpa and simplejpa (in addition to those on that page, simplejpa currently only supports named parameters not positional parameters, which GORM requires).
I've found it much better to just use simplejpa and inject the entityManager directly into objects that need it.
Also keep in mind that there are some limitations to SimpleJPA's support for groovy: it supports JPA annotations on grails domain class attributes, but you have to annotate a getter for ManyToOne and OneToMany relationships.
Answer: The current release of the GORM SimpleDB plugin (0.5) is a bit dated and doesn't work with the current release of GORM (2.0.7) used in Grails.
You can make it work, but it requires a little bit of effort. See http://twasink.net/2014/01/29/how-to-grails-gorm-and-simpledb/

Grails and Amazon SimpleDB


Prevent users from closing certain application

Question: I have a Wpf (.Net app with GUI) application that a company would install across their employees' computers. They don't want their users to be able to kill it from TaskManager. The app resides in taskbar; it listens for incoming messages and displays notifications about new messages; user can always maximize/minimize it to see the details of a message - but she should not be able to stop it.
I tried to develop windows service that would monitor the mentioned application and restart it - unfortunately services cannot spawn process with GUI attached.
Is there any administrative way that would disallow users to kill certain application (or restart it)?
It can be assumed that users work on Windows 8 or higher and they have administrative privileges on their laptops.
Answer: EDIT: I just reread and realized that you were not the one writing the .Net application, which invalidates most of what I just suggested. I'll leave it up there in case some of it is useful. But will come back if I come up with other thoughts.
The administrative privileges are what really throws things off. It is pretty hard to make something that an admin cannot do, as that goes against basic admin principles.
There are three way's I can think to do this, two are not exactly what you want, the other is a lot of work...
1) Create one or more background processes that will monitor the process you want to stay alive, and have it restart the process when its no longer there. If you create 2 other processes they can monitor eachother as well as the main process, that way if one of them gets killed they restart themselves as well. This is pretty much what you tried to do before, but rather than a service just make more applications.
2) More simple than the above, but a little Dicey and may not work: Add to your wpf an overarching "try...catch" statement that on exception, relaunches the program, essentially running a new instance anytime it dies... This could potentially lead to massive memory problems as the old instances likely would not clear out until the new instances closed.
3) Take away admin privileges from everyone, and create a specialized group that has pseudo admin privileges for everything the user would need admin privileges for, minus process in question. This option would be hard, and likely lead to a lot of user frustration.
I can't go into great detail right now, But if one of these sounds like a good option, and you want/need more details let me know and I'll see what I can do later on.
Answer: A windows service can access to user sessions on the computer and borrow user token and launch an application with that token an connect it to Windows Station.
And voila you got what you need.
At this very moment, I do not remember the APIs I've used but I've used that technique to launch an application for logged on user to connect to outlook of one of my colleague to send a prank email.


Determining rates in an ODE

Question: I am building a model with a system of ODEs for the interaction of bacteria with human cells.
I want to determine the rate parameters in the model and in the literature I found that the maximum number of bacteria that can get attached to a single cell is 20 and this maximum number will be reached within 4 hours.
I want to know how I can use these information to come up with the rates that I want.
In the model I have a rate with which unattached bacteria gets attached. As it takes 4 hours for 20 bacteria to attach, can I take the rate with which a bacterium moves to the attached state to be 4/20?
Then I have another rate, namely the rate with which cells move into the infected cell stage. This happens when a cell can no longer attach any more bacteria (having reached its maximum capacity for attachment) is reached. So, can I take it to be 1/4 hours?
My model is somewhat similar to the model found here (the rate with which cells become infected in my model is modelled similarly to the rate $\omega$; $P$ is the bacteria, $E_A$ is the uninfected cells, $E_U$ is the infected cells):
Comment: @Harry49 Intuitively I want the rate with which unattached bacteria gets attached to be much lower than cells move into the infected cell stage. But what do you mean by assuming constant? Although there can be a relationship between these two rates I don't know exactly what thst is and how to find it.
Answer:
In the model I have a rate in which unattached bacteria gets attached. As it takes 4 hours for 20 bacteria to attach, can I take the rate that a bacteria moves to attached state be 4/20.

That strongly depends on how the attachment works. Consider the following mechanisms of attachment:

There is a big reservoir of mostly randomly moving bacteria.
Whenever a bacterium is in the vicinity of a cell that is not yet covered with bacteria, it will seek out a free space and become attached to the cell.
In this case, your model would make sense as the 4 hours in question are determined only by how long it statistically takes for 20 bacteria to come within the vicinity of the cell.
A differential equation that models the number of bacteria $n$ attached to a single cell would be:
$$\frac{\mathrm{d} n}{\mathrm{d} t} = \frac{20}{4\,\mathrm{h}} = 5 \,{\mathrm{h}}^{-1}$$
There is a big reservoir of randomly moving bacteria.
When a bacterium collides directly with a cell, it "sticks".
Twenty bacteria fully cover a cell such that there is no way another bacterium can directly collide with the cell (it can only hit other bacteria).
In this case, your model is not accurate, as the more bacteria are already attached to a cell, the less likely it is for another one to hit a free spot and become attached.
Instead you would the number of bacteria $n$ attached to a single cell to behave roughly exponentially over time, for instance: $n=20·(1-\exp(-ρt))$.
The corresponding differential equation could be something like $$\frac{\mathrm{d} n}{\mathrm{d} t} = ρ·(20-n).$$
(Note that $ρ=\frac{1}{\mathrm{h}}$ roughly matches your observations.)

The model you quote suggest something along the lines of option 2. However, things are a bit different:

There is no infinite reservoir of bacteria.
It's a population model and not a model for a single cell.
There are other things going on which I can only understand with studying the paper.
Comment: Thanks for the reply. I have the differential equation as ${dB\over dt}=rate*B*C$  where B is bacteria and C is uninfected cell. The equation of change of infected cells is similar, and the only difference is the rate where I expect much lower rate than to the bacteria equation.
Comment: Thanks for answering this question. So,when looking for the value of `rate` parameter I found a figure in an article which has plotted number of bacteria per **10** cells over time. There were four data points and I fitted a function of the form $a (1-exp(-\rho t))$ and found values for `a` and $\rho$. The differential equation I have in the model is of the form ${dB\over dt}=rate*B*C$ where B is bacteria and C is uninfected cell. I would appreciate your help to clarify two things. First, whether I should divide $\rho$ by $C$ as in the differential equation I am multiplying by it
Comment: This is continuation of the previous comment. So, my second question is, because the figure in the article has plotted bacteria per **10** cells, I am not sure if the values I obtain for `a` and $\rho $ should be divided by 10, before I use them in the model. It would be a great help if you can help me to clarify this.Thanks
Comment: Please do not ask a follow-up question as a comment. Before you ask your question, please clarify or consider: 1) What exactly is the data you used for your fit? Is this information about a population or about individual bacteria? 2) Assuming that *rate* is constant, your fitted function does not match your differential equation. 3) Please figure out all the assumptions going into your model, in particular about which populations can be seen as reservoirs (i.e., the process in question doesn't affect them) and how the attachment process works.

Determining rates in an ODE


Convergence of $\sum \frac{\lambda^y}{y!}$ to $e^\lambda$

Question: How can I show that
$$ \sum_{y=0}^\infty \frac{λ^y}{y!} = e^λ $$?
I only get so far as to show that the series will converge (by ratio test), but not further, I'm not even sure where to start.
Comment: Which definition of $e^\lambda$ are you using?
Comment: Some older related posts: [Series proof for $e^x$](http://math.stackexchange.com/questions/792332/series-proof-for-ex) and [Why is $ \sum_{n=0}^{\infty}\frac{x^n}{n!} = e^x$?](http://math.stackexchange.com/questions/433442/why-is-sum-n-0-infty-fracxnn-ex)
Comment: It is impossible to answer this question without knowing which definition of $e^{\lambda}$ you are assuming. For many people (like me) that series *is* the definition of $e^\lambda$, so there is nothing to prove.
Comment: Have you tried taking derivatives with respect to $\lambda$?
Comment: Consider what happens when $y\ge 2\lambda$.
Comment: Do you know about Taylor series?  In probability, this is used for Poisson distributions ($\lambda > 0$)..  $P(X = k) = e^{-\lambda} \lambda^k/k!$, for $k = 0, 1,\dots .$ Your equation endures that $\sum_{k=0}^\infty P(X=k) = 1.$
Answer: Your series is one of the possible definitions of the exponential functions in the real field. There are really many possible definitions. I resume here the most known:
1) as a limit:
$$
e^x=\lim_{n \to \infty}\left(1+\dfrac{x}{n} \right)^n
$$
2) as the solution of differential function: $e^x = f(x)$ such that:
$$
f'(x)=f(x)\qquad \mbox{ with the initial condition } \qquad f(0)=1
$$
3) as the solution $e^x=f(x)$ of the functional equation:
$$
f(x+y)=f(x)f(y)\qquad \mbox{ with the condition } \qquad f'(0)=1
$$
4) as a series as in your question:
$$
e^x= 1+\sum_{k=1}^\infty\dfrac{x^k}{k!}
$$
5) as a continued fraction$$
e^x=\cfrac{1}{1-\cfrac{x}{1+x-\cfrac{x}{2+x-\cfrac{2x}{3+x-\cfrac{3x}{4+x-\ddots}}}}}
$$
And we can show that all these definitions are equivalent ( in $\mathbb{R}$).
As an example, using teh binomial formula, we have:
$$
\left(1+\dfrac{x}{n} \right)^n  =1+\sum_{k=1}^n\binom{n}{k}\dfrac{x^k}{n^k}
$$
and the coefficient of the $k-$power is:
$$
\dfrac{n!}{k!(n-k)!\,n^k}=\dfrac {1}{k!} \, \dfrac{1\times 2 \times 3 \cdots \times n}{[1\times 2  \cdots \times (n-k)]\,\times \,\underbrace {n\times n \cdots \times n}_{k \,\mbox{times}}}
$$
that, simplifyng and reordering becomes:
$$
\begin{split}
\dfrac{n!}{k!(n-k)!\,n^k}&= \dfrac {1}{k!} \,\dfrac{\overbrace{(n-k+1)\times(n-k+ 2) \cdots \times (n-1)}^{(k-1)\,\mbox{factors}}}{\underbrace {n\times n \cdots \times n}_{(k-1) \,\mbox{factors}}} \\
&=\dfrac {1}{k!}\,\left(1-\dfrac{k-1}{n}\right)\,\left(1-\dfrac{k-2}{n}\right)\cdots\,\left(1-\dfrac{1}{n}\right)
\end{split}
$$
and taking the limit $n\rightarrow \infty$ we have:
$$
\lim_{n \to \infty}\dfrac{n!}{k!(n-k)!n^k}=\dfrac{1}{k!}
$$
so that:
$$
\exp(x)=\lim_{n \to \infty}\left(1+\dfrac{x}{n} \right)^n = 1+\sum_{k=1}^\infty\dfrac{x^k}{k!}
$$
If you want link the definitions 2) and 4), than derive term by term the series, as suggested in the comments.
Comment: A limit $\lim_{n \to \infty} a_{k,n} = a_k$ does not imply that $\lim_{n \to \infty} \sum_{k=0}^{n} a_{k,n} x^k = \sum_{k=0}^{\infty} a_k x^k$ in general.  Some sort of uniformity/dominated convergence argument must be made.


Coupon collector's problem with increasing number of coupons needed

Question: In the ordinary coupon collector's problem, there are $n$ types of coupons, and we pick coupons uniformly at random until we get at least one of each coupon.
https://en.wikipedia.org/wiki/Coupon_collector's_problem
It is well known that the expected time to collect all coupons $k$ times (for a fixed integer $k$) is $ n \log n + (k - 1) n \log\log n + O(n)$. But what if we need to collect all coupons $n$ times? Is the expected time $\omega(n^2)$?
Answer: Following Balls into Bins: A tight analysis assume we throw $m$ balls independently and uniformly into $n$ bins and let $M$ be the maximum number of balls in any bin. This allows for $m$ to depend on $n$. Then, if $m\gg n (\log n)^3,$ the probability $P[M>k_\alpha]=o(1)$ if $\alpha>1$ and $P[M>k_\alpha]=1-o(1)$ if $\alpha\in (0,1).$ Here
$$
k_\alpha=\frac{m}{n}+
\sqrt{\frac{2 m \log n}{n}\left(1-\frac{1}{\alpha}\frac{\log \log n}{2 \log n}\right)}.
$$
This means that there is threshold behaviour for the maximum load around $m/n,$ and it will be upper bounded by $k_\alpha$ with probability going to one if we take $\alpha>1.$ Now let $m=n^2,$ and note that the bounded maximum implies that at least $n^2$ time is needed for the minimum load to exceed $n.$ In other words, since the maximum load is very close to the average load so is the minimum load.
Comment: I don't understand this. Isn't it trivial that at least $n^2$ time is needed for the minimum load to exceed $n$? Why do you seem to conclude this from a sophisticated analysis? Also, the question asks whether the expected time is $\omega(n^2)$; you don't seem to say anything about that.


Erro ao tentar passar um struct por referência em C?

Question: Estou tendo aula de ponteiros e estou tentando fazer o seguinte exercicio:
Considere um cadastro de alunos matriculados em uma disciplina, com as seguintes informações para cada aluno:
• Nome do aluno: com até 80 caracteres
• Número de matrícula: representado por um valor inteiro
• Notas obtidas em três provas, P1, P2, P3: representadas por valores reais
(a) Defina uma estrutura em C, denominada aluno, que tenha os campos apropriados para guardar as informações de um aluno, conforme descrito acima.
(b) Escreva uma função que receba como parâmetro um ponteiro para uma estrutura do tipo definido no item anterior e imprima na tela do computador uma linha com o nome do aluno e outra linha com a média obtida nas três provas. Essa função deve seguir o seguinte protótipo:
void imprime (struct aluno* a);

Só que está dando erro no código:
'#include stdio.h'
'#include stdlib.h'

void imprime(struct aluno *a);

int main()
{
    struct aluno{
        char aluno[80];
        int mat;
        float p1,p2,p3;
    } joao;

    printf("Digite o nome do aluno: ");
    gets(joao.aluno);

    printf("Digite a matricula do aluno: ");
    scanf("%i", &joao.mat);

    printf("Digite as notas do aluno:\n" );
    scanf("%d %d %d", &joao.p1,&joao.p2,&joao.p3);

    imprime(&joao);
    getchar();

    return 0;
}

void imprime(struct aluno* a){
    printf("%s",a->nome);
}

O erro é o seguinte:
ERRO: |28|error: conflicting types for 'imprime'|

Answer: Na primeira vez que o compilador encontra a funcao imprime() ele ainda nao encontrou a definicao de struct aluno.
Depois, dentro da funcao main() aparece a definicao da struct aluno; que tem efeito a partir dai ate ao fim do programa.
Na segunda vez que aparece a funcao imprime(), o compilador tem outra ideia do que é a struct aluno.
Ou seja, para o compilador ha duas struct aluno diferentes (com o mesmo nome) e ele queixa-se.
A solucao melhor é passar a definicao da struct aluno para antes de qualquer uso; para imediatamente a seguir aos #includes.
Comment: Exatamente isso, mt obrigado!!!
Answer: Analisando seu código, sugiro:
#include "stdio.h"
#include "stdlib.h"

struct aluno{
    char aluno[80];
    int mat;
    float p1,p2,p3;
} joao;

void imprime(struct aluno *a);

int main()
{
    printf("Digite o nome do aluno: ");
    gets(joao.aluno);

    printf("Digite a matricula do aluno: ");
    scanf("%i", &joao.mat);

    printf("Digite as notas do aluno:\n" );
    scanf("%d %d %d", &joao.p1,&joao.p2,&joao.p3);

    imprime(&joao);
    getchar();

    return 0;
}

void imprime(struct aluno* a){
    printf("%s",a->aluno);
}


Fastapi fullstack dockerfile: ModuleNotFoundError: No module named 'sqlalchemy'

Question: I created a fastapi docker app based on this.
After executing docker compose up, all worked fine but backend and celeryworker: they complain about ModuleNotFoundError: No module named 'sqlalchemy' (/app/app/backend_pre_start.py).
Since the package is managed by poetry, and poetry will create a venv, so I guess the error is caused by environment?
I searched the repo but found no issues similar to mine.
Do I have to manually call poetry shell in all .sh files?

UPDATE
I tried adding poetry shell,
now it complains (25, 'Inappropriate ioctl for device')
Comment: your issue should be similar to https://stackoverflow.com/a/75841882/8582353
Answer: I removed POETRY_VIRTUALENVS_IN_PROJECT=true and added poetry config virtualenvs.create false after poetry installation.
Now poetry won't create a .venv when doing poetry install, and all dependencies are installed to current directory.