MySQL - Select the least day of the current month/year, not necessarily the first day of the month

Question: Using PHP/MySQL
I'm trying to create a select statement that gets the data from the least day of the current month and year (I'm using it to show data from on a certain player 'this month').  The 1st of the months data may not always exist therefore if the first isn't found then it would use the 2nd or 3rd or so on, whichever is the least month.
The query would need to be something like:
SELECT * FROM table_name WHERE name = '$username' AND
[...theDate = the least day of data in the current month/year]

It would return a single row of data.
This is a query I use for getting the 'this week' data:
SELECT name, data, theDate
FROM table_name
WHERE name = '$username'
AND YEARWEEK(theDate) = YEARWEEK(CURRENT_DATE)
ORDER BY theDate;

Answer: Here is a simple solution:
SELECT a.*
FROM table_name a
INNER JOIN
(
    SELECT name, MIN(theDate) AS mindate
    FROM table_name
    WHERE MONTH(theDate) = MONTH(CURDATE()) AND
          YEAR(theDate) = YEAR(CURDATE()) AND
          name = '$username'
    GROUP BY name
) b ON a.name = b.name AND a.theDate = b.mindate
ORDER BY theDate

The inner subselect first selects the minimum date of the current month and current year. This should return exactly one result.
The outer query then joins on this one result, and thus you get the row(s) of the earliest recorded day of the current month & year.
Assuming only one row is generated per player per day, we can simplify even further:
SELECT *
FROM table_name
WHERE MONTH(theDate) = MONTH(CURDATE()) AND
      YEAR(theDate) = YEAR(CURDATE()) AND
      name = '$username'
ORDER BY theDate
LIMIT 1

Comment: Your inner query also needs to check for the correct `name`.  (What if we are looking for user "Foo" who joined on 2012-07-14, but user "Bar" has records dating back to 2012-07-01?)
Comment: Does it only once. MySQL only has to be done once, because that expression is deterministic, and doesn't vary depending on any row. It's a different story (of course) if we replace the `NOW()` and instead reference a column in the table... that's where we run into the "has to be executed for every row"... which is why we put the bare column on one side, and do all the gyrations on the other side with the literal (the NOW() function essentially returns us a literal for the statement.
Comment: I haven't tried this as the other solution worked for me, but thanks for the help.
Comment: @Zane: just pointing out, that with the YEAR() and MONTH() functions around `theDate`, MySQL cannot do an index range scan to satisfy those predicates. (I'm certain that` MONTH(theDate) = val` is not sargable, and I'm almost certain that `YEAR(theDate) = val` is also not sargable. I say almost certain, because MySQL could conceivably change that at some point, by rewriting that as a range scan. We can allow MySQL to use an index range scan operation by using range scan predicates on the bare column.
Comment: @spencer7593, I was just making a remark on your solution regarding the same thing as you posted your comment. One question about that though: you have `>= CAST(DATE_FORMAT(NOW(),'%Y-%m-01') AS DATE)`... would MySQL only need to execute that function once and then use the returned value to do the index scan, or would it execute for every row?
Answer: If you are interested in returning only one row, the easiest way to do this would be:
SELECT t.*
  FROM table_name t
 WHERE t.name = '$username'
   AND t.theDate >= CAST(DATE_FORMAT(NOW(),'%Y-%m-01') AS DATE)
   AND t.theDate < DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH)
 ORDER BY s.name DESC, s.theDate DESC
 LIMIT 1

The ORDER BY is based on the assumption that you have an index on (or with leading columns of) (name,theDate). That would be the most appropriate index for the predicates (i.e. conditions in the WHERE clause. There's really no need for us to sort the name column, since we know it's going to be equal to something... but specifying the ORDER BY in this way makes it more likely MySQL will do a reverse scan operation on the index, to return the rows in the correct order, avoiding a filesort operation.
NOTE: I specify the bare theDate column in the conditions in the WHERE clause, rather than wrapping that in any function... by specifying the bare column and a bounded range, we enable MySQL to make use of an index range scan operation. There are other possible ways to include this condition in the WHERE clause, for example...
DATE_FORMAT(t.theDate,'%Y-%m') = DATE_FORMAT(NOW(),'%Y-%m')

which will return an equivalent result, but a predicate like this is not sargable. That is, MySQL can't/won't do a range scan on an index to satisfy this.
If you are intending to get all the rows for the "least" date in a month for a given user (your question doesn't seem to indicate that you need only one row), here's one way get that result:
SELECT t.*
  FROM table_name t
  JOIN ( SELECT s.name
              , s.theDate
           FROM table_name s
          WHERE s.name = '$username'
            AND s.theDate >= CAST(DATE_FORMAT(NOW(),'%Y-%m-01') AS DATE)
            AND s.theDate < DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH)
          ORDER BY s.name DESC, s.theDate DESC
          LIMIT 1
       ) r
    ON r.name = t.name
   AND r.theDate = t.theDate

Again, MySQL can make use of an index (if available) with leading columns (name,theDate) to satisfy the predicates, and to do a reverse scan operation (avoiding a sort), and to do the JOIN operation.
NOTE: We're assuming here that 'theDate' is datatype DATE (with no time component).  If it's a DATETIME or a TIMESTAMP, there's a potential for a time component, and that query may not return all rows for a given "date" value, if the time components are different for the rows with the same "date". (e.g. '2012-07-13 17:30' and '2012-07-13 19:55' are different datetime values.) If we want to return both of those rows (because both are a date of "July 13"), we need to do a range scan instead of an equality test.
SELECT t.*
  FROM table_name t
  JOIN ( SELECT s.name
              , s.theDate
           FROM table_name s
          WHERE s.name = '$username'
            AND s.theDate >= CAST(DATE_FORMAT(NOW(),'%Y-%m-01') AS DATE)
            AND s.theDate < DATE_ADD(DATE_FORMAT(NOW(),'%Y-%m-01'), INTERVAL 1 MONTH)
          ORDER BY s.name DESC, s.theDate DESC
          LIMIT 1
       ) r
    ON t.name = r.name
   AND t.theDate >= r.theDate
   AND t.theDate < DATE_FORMAT(DATE_ADD(r.theDate,INTERVAL 1 DAY),'%Y-%m-%d')

Note those last two lines... we're looking for any rows with a theDate value that is greater than or equal to the "least" value found for the current month AND that is ALSO less than midnight of the following day.
Comment: This looks like it works for me, thanks spencer! my query I used is like: "SELECT *
FROM  player
WHERE playerName =  '$username'
AND theDate >= CAST( DATE_FORMAT( NOW( ) ,  '%Y-%m-01' ) AS DATE )
ORDER BY theDate
LIMIT 1" I can't vote up :(
Comment: Your solution should be faster than mine as it avoids passing the `theDate` column to a function, where it otherwise wouldn't be able to utilize an index. But just as a matter of style, I would use the `BETWEEN` syntax instead. =)
Comment: @Zane... good points. I avoid using BETWEEN with DATETIME and TIMESTAMP columns to get rows for a month (e.g.), because I really want to specify the boundaries as "midnight of the first day of the month" and "midnight of the first day of the following month", and I want only values LESS THAN the upper bound, not LESS THAN OR EQUAL TO the upper bound, which is what BETWEEN gets me. To effectively use BETWEEN I would need to subtract 1 second from the  upper bound. And with some databases (SQL Server) datetime resolutions are subsecond. I prefer the `lb <= col < ub` style because it works right.
Comment: @Zane: the query with the range scan predicates (like mine) will be faster only if there is a suitable index available, and the execution plan generated by the optimizer actually turns out to be faster. But, in general, for large tables, and index range scan on a narrow set of rows usually outperforms a full table (or full index) scan.
Comment: Just want to note that the 'theDate' column for my specific table has the 'date' datatype. Thanks for all the information!


How does pandas concat function do column joins without specify common key?

Question: Greetings to my dear fellow Pythoners!
Today, when I was going through a Python course on data camp, a simple data join with pd.concat() really stood up to me. I couldn't seem to understand the logic behind the join. I need your help!
Consider the following case which is a simplified version, and we want to use pd.concat() to join this two table:
Table A:
Date        Day        status_country        counts
1/5/2015    289        Cases_Guinea          2776.0
1/4/2015    288        Cases_Guinea          2775.0
1/3/2015    287        Cases_Guinea          2769.0
1/2/2015    286        Cases_Guinea             NaN
12/31/2015  284        Cases_Guinea          2730.0

Table B:
status    country
 Cases     Guinea
 Cases     Guinea
 Cases     Guinea
 Cases     Guinea
 Cases     Guinea

Python code:
pd.concat([ebola_melt, status_country], axis = 1)

Return Data:
Date        Day        status_country        counts    status    country
1/5/2015    289        Cases_Guinea          2776.0     Cases     Guinea
1/4/2015    288        Cases_Guinea          2775.0     Cases     Guinea
1/3/2015    287        Cases_Guinea          2769.0     Cases     Guinea
1/2/2015    286        Cases_Guinea             NaN     Cases     Guinea
12/31/2015  284        Cases_Guinea          2730.0     Cases     Guinea

Question:
Obviously, there is no common index between this two tables unless you parse 'status_country' column in table A and then match it to table B, but I am not sure if this function is smart enough to do that.
What kind of matching logic is behind this function?
Is it doing partial matching or parse then match?
How would I understand it?
Comment: It's doing nothing, all it did was to add your table B to the right of table A, because you specified `axis=1`
Comment: It's joining based on index, which you have not included in the question. Likely these two `DataFrames` have a simple `RangeIndex(start=0, stop=len(df), step=1)`
Comment: @RockyLi That explains it! It was a simple row-wise concatenation without finding a common index in the column value. Initially, I thought the pd.concat() algorithm could identify the match between "Cases_Guinea" with ["Cases", "Guinea"]
Answer: pd.concat is base on the index
For example you have
df1=pd.DataFrame({'A':[1,2,3,4]})
df2=pd.DataFrame({'A':[1,2,3,4]},index=[2,3,4,5])

When you do concat , you are doing join by index , or merge by index
pd.concat([df1,df2],axis=1)
Out[303]:
     A    A
0  1.0  NaN
1  2.0  NaN
2  3.0  1.0
3  4.0  2.0
4  NaN  3.0
5  NaN  4.0

Comment: Thanks, Wen! Given it's solely based on the row index with this concatenation, the result will be incorrect if the order of the data was wrong. That makes sense.
Comment: @smzsmzsmz glad I can help


If $N = q^k n^2$ is an odd perfect number with special prime $q$, then must $\sigma(n^2)$ be abundant?

Question: Preamble:  This post is an offshoot of this earlier MSE question.
The topic of odd perfect numbers likely needs no introduction.
Let $\sigma=\sigma_{1}$ denote the classical sum of divisors.  Denote the abundancy index of the positive integer $x$ by $I(x)=\sigma(x)/x$.  A positive integer $x$ satisfying $I(x) < 2$ (respectively, $I(x) > 2$) is said to be deficient (respectively, abundant).
An odd perfect number $N$ is said to be given in Eulerian form if
$$N = q^k n^2$$
where $q$ is the special/Euler prime satisfying $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.
The question is as is in the title:

If $N = q^k n^2$ is an odd perfect number with special prime $q$, then must $\sigma(n^2)$ be abundant?

UPDATE (September 11, 2021 - 1:56 PM Manila time) - Finally proved that $\sigma(n^2)$ must be deficient in my answer below.
MY ATTEMPT
From the trivial relationship
$$\sigma(q^k)\sigma(n^2)=\sigma(q^k n^2)=\sigma(N)=2N=2 q^k n^2,$$
I could only prove that $\sigma(n^2)/q^k \mid n^2 \mid N$ (since $\gcd(q^k, \sigma(q^k))=1$).  This means that $\sigma(n^2)/q^k$ is deficient.
Also, I obtain
$$\sigma(\sigma(q^k)\sigma(n^2)) = \sigma(2q^k n^2) = 3\sigma(q^k)\sigma(n^2).$$
Using the inequality
$$\sigma(AB) \leq \sigma(A)\sigma(B)$$
which holds for all positive integers $A, B$, we have
$$3\sigma(q^k)\sigma(n^2) = \sigma(\sigma(q^k)\sigma(n^2)) \leq \sigma(\sigma(q^k))\sigma(\sigma(n^2)).$$
From the paper titled On Odd Perfect Numbers and Even $3$-Perfect Numbers by Cohen and Sorli, published in Integers (2012, Theorem 3, page 3), we have the following result:

Let $q^k n^2$ be an odd perfect number with special prime $q$.  Then the following inequality holds unconditionally:
$$\sigma(\sigma(q^k)) \leq 3q^k - 1.$$

This result implies that
$$3\bigg(\frac{q^{k+1} - 1}{q - 1}\bigg)\sigma(n^2) = 3\sigma(q^k)\sigma(n^2) = \sigma(\sigma(q^k)\sigma(n^2)) \leq \sigma(\sigma(q^k))\sigma(\sigma(n^2)) \leq (3q^k - 1)\sigma(\sigma(n^2)),$$
from which we get
$$I(\sigma(n^2)) \geq 3\bigg(\frac{q^{k+1} - 1}{(q - 1)(3q^k - 1)}\bigg) = \frac{q - 3}{(q - 1)(3q^k - 1)} + \frac{q}{q - 1} := f(q,k).$$
I noticed that
$$f(5,1) = \frac{9}{7}$$
$$f(13,1) = \frac{21}{19}.$$
I did confirm (graphically, by using WolframAlpha) that it is true that
$$f(q,k) > 1.$$
My hunch is that $\sigma(n^2)$ is abundant, as $\omega(n) \geq 9$ (which means $n^2$ has a lot of prime factors), as proved by Nielsen (2015), where $\omega(n)$ is the number of distinct prime factors of $n$.
Alas, this is where I get stuck!
UPDATE
Since $3q^k - 1 < 3q^k$, then
$$I(\sigma(n^2)) \geq f(q,k) = 3\bigg(\frac{q^{k+1} - 1}{(q - 1)(3q^k - 1)}\bigg) > 3\bigg(\frac{q^{k+1} - 1}{{3q^k}(q - 1)}\bigg) = I(q^k) > 1,$$
which analytically confirms my graphical observation above.
Comment: Please clarify what remains to be shown exactly to complete your proof. You seem to be already quite close.
Comment: How so, @Peter?  Note that we need to show that $I(\sigma(n^2)) > 2$ in order to prove that $\sigma(n^2)$ is *abundant*.
Comment: Finally figured it out, @Peter! Writing out a conclusive answer now in this regard.  Thank you very much for your time and attention, and for the hint!  =)
Answer: Let $N$ be an odd perfect number given in the so-called Eulerian form
$$N = q^k n^2$$
where $q$ is the special/Euler prime satisfying $q \equiv k \equiv 1 \pmod 4$ and $\gcd(q,n)=1$.
From the trivial relationship
$$\sigma(q^k)\sigma(n^2)=\sigma(q^k n^2)=\sigma(N)=2N=2 q^k n^2$$
we obtain
$$\bigg(\frac{\sigma(q^k)}{2}\bigg)\cdot{\sigma(n^2)}=N=q^k n^2$$
which implies that $\sigma(n^2)$ is a proper factor of the (odd) perfect number $N$ (since $\sigma(q^k)/2 \geq (q^k + 1)/2 \geq (5+1)/2 = 3$).
We therefore conclude that $\sigma(n^2)$ must be deficient.


BitBucket deployment using SSH keys to remote server

Question: I am trying to write a YAML pipeline script to deploy files that have been altered from my bitbucket repository to my remote server using ssh keys. The document that I have in place at the moment was copied from bitbucket itself and has errors:
pipelines:
  default:
  - step:
      name: Deploy to test
      deployment: test
      script:
      - pipe: atlassian/sftp-deploy:0.3.1
      - variables:
         USER: $USER
         SERVER: $SERVER
         REMOTE_PATH: $REMOTE_PATH
         LOCAL_PATH: $LOCAL_PATH

I am getting the following error

Configuration error
  There is an error in your bitbucket-pipelines.yml at [pipelines > default > 0 > step > script > 1]. To be precise: Missing or empty command string. Each item in this list should either be a single command string or a map defining a pipe invocation.

My ssh public and private keys are setup in bitbucket along with the fingerprint and host. The variables have also been setup.
How do I go about setting up my YAML deploy script to connect to my remote server via ssh and transfer the files?
Answer: Try to update the variables section become:
      - variables:
         - USER: $USER
         - SERVER: $SERVER
         - REMOTE_PATH: $REMOTE_PATH
         - LOCAL_PATH: $LOCAL_PATH

Here is am example about how to set variables: https://confluence.atlassian.com/bitbucket/configure-bitbucket-pipelines-yml-792298910.html#Configurebitbucket-pipelines.yml-ci_variablesvariables
Answer: Your directive - step has to be intended.
I have bitbucket-pipelines.yml like that (using rsync instead of ssh):
# This is a sample build configuration for PHP.
# Check our guides at https://confluence.atlassian.com/x/e8YWN for more examples.
# Only use spaces to indent your .yml configuration.
# -----
# You can specify a custom docker image from Docker Hub as your build environment.
image: php:7.2.1-fpm

pipelines:
  default:
    - step:
        script:
          - apt-get update
          - apt-get install zip -y
          - apt-get install unzip -y
          - apt-get install libgmp3-dev -y
          - curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer
          - composer install
          - cp .env.example .env
          #- vendor/bin/phpunit
          - pipe: atlassian/rsync-deploy:0.2.0
            variables:
                USER: $DEPLOY_USER
                SERVER: $DEPLOY_SERVER
                REMOTE_PATH: $DEPLOY_PATH
                LOCAL_PATH: '.'

I suggest to use their online editor in repository for editing bitbucket-pipelines.yml, it checks all formal yml structure and you can't commit invalid file.
Even if you check file on some other yaml editor, it may look fine, but not necessary  according to bitbucket specification. Their online editor does fine job.
Also, I suggest to visit their community on atlasian community as it's very active, sometimes their staff members are providing answers.
However, I struggle with plenty dependencies needed to run tests properly. (actual bitbucket-pipelines.yml is becoming bigger and bigger).
Maybe there is some nicely prepared Docker image for this job.


Washer Dryer Hookup

Question: I moved into a new house and want to make sure I don't flood the place.
The spigot on the left does have water to it, I turned it on for a second only, it didn't feel hot, but maybe that wasn't long enough.  The gray hose goes to drainage. The cold water also has water in it.  The pipe directly above the spigot on the left is capped off right outside the picture.  The people living here before had a washer and dryer, so I'm assuming they made it work somehow.
Can the left spigot be treated as hot and the left cold?
Thanks in advance for the help.
Comment: If you hook up the washer and start a hot wash cycle, you will be able to feel if the valve on the left gets hot as the water gets hot. If the water doesn't get hot, start a cold cycle instead. If _that_ water comes out hot instead of cold, you can swap the connections.
Answer: Usually the left is hot and the right is cold but don't take that to the bank. Put a bucket under the left spigot and run enough water to see if it gets hot. The right valve has been replaced, with a blue handle, which could mean cold water, but don't take that to the bank either. At least they replaced it with a ball valve so that'll be good for a long time. Welcome to your new house... I'm sure you'll be back here.
Comment: Thank you :) and I think you're correct.

Washer Dryer Hookup


How do you find the minterm list of a boolean expression containing XOR?

Question: Let's say I have a boolean expression, such as F1 = x'y' ⊕ z .
How do I go about finding the minterm list for that expression?
The method I've tried is to take each term, such as x'y' and z, then fill in the missing values with all possibilities.  So for x'y' there exists two options of 00- where z is 000 and 001.  Then for Z it's --1, where the values can be 001, 011, 101, 111.  So the minterms would come out to be 0, 1,  1, 3, 5, and 7.
My method of finding them, however, is wrong, because the minterms are actually 0,3,5, and 7.
What's the appropriate method to obtain the minterm list in this situation?
Comment: You can use the identity $a\oplus b=ab+\bar a\bar b$.
Answer: Steps to find minterm:

Write the expression as sum of products form, i.e., containing AND, OR, NOT operators only. If there are other operators like XOR, XNOR, NAND, NOR, you have to replace them with AND, OR, NOT.
$(a'b')'z + (a'b')z'$
$= (a + b)z + a'b'z'$
$= az + bz + a'b'z'$
Modify each product term to contain every variable.
$= a(b+b')z + (a+a')bz + a'b'z'$
$= abz + ab'z + abz + a'bz + a'b'z'$
Remove the duplicate terms to get the required sum of minterms.
$= abz + ab'z + a'bz + a'b'z'$
$= m(7, 5, 3, 0)$
Answer: For an expression with just three variables, the usual way is to write a truth table, depict it as Karnaugh map and find a minimal set of terms which cover all 1entries in the map.
             xy
       00  01  11  10
      +---+---+---+---+
   0  | 1 | 0 | 0 | 0 |
z     +---+---+---+---+
   1  | 0 | 1 | 1 | 1 |
      +---+---+---+---+

The simplified expression:
$$xz \lor yz \lor x'y'z'$$
This assumes that the $\oplus$ exclusive or operator has lower precedence than the $\land$ logical and operator.
From the Karnaugh map, you can see that the expression has four minterms.
Assuming $z = false$, $x'y'$ must be $true$ for $F_1$ to be $true$. This implies $x = false$ and $y = false$.
Assumption $z = true$ implies $x'y' = false$. There are three possible combinations for this as shown in the lower row of the Karnaugh map.
Comment: Thanks so much for the response, this worked perfectly.
Comment: @AlexKemper how does it have four? I see only three $xz$, $yz$ and $x'y'z'$.
Comment: @Robut by definition (http://www.cs.ucr.edu/~ehwang/courses/cs120a/minterms.pdf), a minterm is a term with all variables. In this example, there are four 1-cells in the Karnaugh map which correspond to four minterms. These four minterms can be covered by three terms, one minterm with three variables and two terms with two variables each.


Understanding Helly's theorem

Question: The following is part of the inductive step in Wiki's proof for Helly's theorem. Why is it true?
<code>In this new collection, every subcollection of d + 1 sets will have nonempty intersection
</code>
Answer: The whole inductive step in the proof is

Suppose $n > d + 2$ and that the statement is true for $n−1$. The argument above shows that any subcollection of $d + 2$ sets will have nonempty intersection. We may then consider the collection where we replace the two sets $X_{n−1}$ and $X_n$ with the single set $X_{n−1} \cap X_n$. In this new collection, every subcollection of $d + 1$ sets will have nonempty intersection. The inductive hypothesis therefore applies, and shows that this new collection has nonempty intersection. This implies the same for the original collection, and completes the proof.

First we have

The argument above shows that any subcollection of $d + 2$ sets will
have nonempty intersection.

The argument referred to is the one given for the base case. It does not rely on the induction hypothesis. Now, we form a collection of $n-1$ sets consisting of $X_1$ through $X_{n-2}$ and $X_{n-1}\cap X_n$. If you choose $d+1$ elements from this collection and take their intersection, there are two possibilities:

The $d+1$ elements chosen includes $X_{n-1}\cap X_n$. In this case there are $d$ other sets $X_j$ selected. So the intersection of all of them is the intersection of those $d$ sets, $X_{n-1}$, and $X_n$, or a collection of $d+2$ sets, which by indicated argument we know must have a non-empty intersection.
Or the $d+1$ elements do not include $X_{n-1}\cap X_n$. Neither $X_{n-1}$ nor $X_n$ can be in the selected sets, so if we take the intersection of the $d+1$ sets and also intersect with $X_n$, this is a collection of $d+2$ sets, and again must have non-empty intersection. But $A \cap X_n \ne \varnothing$, then $A \ne \varnothing$. So once again, the intersection of the $d+1$ elements cannot be empty.

In either case, the intersection of $d+1$ elements is not empty.

Understanding Helly's theorem


When does a Markov chain not have a steady state?

Question: I was asked this question on an oral qual, and eventually I seemed to conclude that there have to be eigenvalues of modulus 1.  But I just realised every Markov matrix has one as an eigenvalue.  So should the condition be multiple eigenvalues with modulus 1?
Answer: Every Markov chain on a finite state space has an invariant distribution. As you said, this follows directly from the condition that the rows sum to $1$.
It is possible for a Markov chain on a finite state space to have multiple invariant distributions. However, the Perron-Frobenius theorem tells us that these can be decomposed into distributions which are concentrated on strongly connected components of the state space. Decomposing the process into strongly connected components results in one or more different Markov chains each of which has a unique invariant distribution.
Any transient states of the original chain will not be states in any of these sub-chains, since they are not in any strongly connected component. Confusingly, this means that a chain that is not irreducible is generically not reducible into chains on disjoint subsets of the state space. That's because generically some transient states would have to be in more than one sub-chain, which is because generically one can reach more than one strongly connected component starting from a transient state.
As an important special case, an irreducible finite state Markov chain has a unique invariant distribution which assigns positive probability to all states.
However many invariant distributions the process has, it can happen that no invariant distribution is approached over time. When the state space is finite, it turns out that this only happens when the chain is "periodic" (meaning that there are states $i,j$ and an integer $n>1$ such that all paths from $i$ to $j$ have a length which is a multiple of $n$). In this case the transition matrix has an eigenvalue which is not $1$ and has modulus $1$. If the corresponding eigenvector contributes to the initial condition, then its contribution does not decay, and no invariant distribution is approached. The classic example of a periodic chain is $P=\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$, but in general it is not essential that the chain is deterministic for it to be periodic.
It is possible for a Markov chain on an infinite state space to not have any invariant distributions. This is roughly because probability mass can escape to infinity. A simple example is a Markov chain on $\mathbb{Z}$ which deterministically moves one unit to the right at every step. Another example is the simple symmetric random walk: it has an invariant measure which is uniform on $\mathbb{Z}$, but this measure cannot be normalized.
Comment: @Math1000 Thanks. I don't like the flow of the new sentence, but I see the issue.
Comment: +1 This is an excellent answer that provides a lot of information. I suspect that what the OP means by "steady state" is not an invariant measure, but rather the convergence of $P^n$. I've added a short answer as a companion to yours.
Comment: "A Markov chain on an infinite state space can have no invariant distribution." - I would reword this, because it can easily be interpreted as "no Markov chain on an infinite state space can have an invariant distribution" which is clearly not true.
Comment: That is how I interpreted the sentence when I read it and I was very confused at first :)
Comment: So, is it true that a finite-state Markov chain with no unique equilibrium distribution must have multiple eigenvalues with modulus one?
Comment: @TorsionSquid A finite-state Markov chain with multiple invariant distributions has an eigenvalue of $1$ with a geometric multiplicity higher than $1$. Any eigenvalues which are not $1$, regardless of their modulus, are not relevant to the question of existence, only to the question of the long term limit. (Also, I would suggest you stick to the word "invariant" rather than "equilibrium" if there is a possibility that the invariant distribution is not approached. Math people will not get confused, but stat mech people might.)
Comment: +1 also for the last comment....and thank you very much for my recent question.
Answer: You are correct. If $P$ is a Markov transition matrix, then $P^n$ converges
as $n\to\infty$ if and only if $P$'s only eigenvalue of modulus one is $\lambda=1.$
Comment: Note that $p_0 P^n$ may converge even when $P^n$ does not.
Comment: @Ian Sure! The set of limits of $p_0 P^n$ over all probability vectors $p_0$ equals the set of invariant probability vectors, which is non-empty.


Printer installation problems under ubuntu 14.04

Question: I moved from 12.04 to 14.04 and I am no more able to print.
This is a network printer and if I try to print something the printer completely freezes (one need to restart it by unplugging the supply !).
The printer is a Konica Minolta BizHub C280.
I have tryed 3 different Ubuntu installations:
- Ubuntu 14.04 (64bits)
- Xubuntu 14.04 (64bits)
- Ubuntu 14.04 (32bits) [as my 12.04 was a 32bits)
I think the short term solution is to come back to 12.04 !
Comment: Did you try manually selecting different printer drivers? If your printer has multiple drivers, perhaps one of them is faulty.
Answer: When I moved to 14.04 I got problems with my Brother HL-5350DN.
Now I have installed it thru:
localhost for CUPS (C Unix Printing System)
<code>    http://localhost:631/
</code>
and it works just fine.
So try that instead by the Printers dialog.
/Göran


namespace definition changes mimetype

Question: i noticed strange mimetype behaviour when defining namespace (alias).whenever i define a namespace or an alias containing \input the mimetype of the php source file changes from text/x-php to text/x-tex.
A minimal example.php could look like this where the surroundings of \input doesn't matter.
<?php namespace \input; ?>

When running file --brief --mime-type example.php the mimetype text/x-tex is printed instead of the expected one text/x-php.
As soon as the backslash before input is removed the mimetype switches back to text/x-php.
Can anybody confirm this behaviour?
Does anybody know a reason why this is happening?
Does anybody got a fix/workaround for this except changing the namespace itself?
Comment: I don't see a reason of this automatic change except if your editor try to deduce itself the mime type from the content. There's probably a way to enforce it.
Comment: @CasimiretHippolyte i tried to change the namespace with `vim` and `nano`. with both editors i encountered this behaviour
Comment: Paul Crovella is right, the file utility probably tries a "best candidate list" to deduce the mime type from the content.
Answer: The file utility uses just some heuristics based on the file contents. In your case, it sees that

the file is a plain text file (no binary)
contains the string \input, which is a predefined macro in TeX

And it seems that somehow the \input=TeX takes precedence over <?php=PHP.
The file utility does not look at file extensions.
Also, this has nothing to do how you save the file or which editor you use. It is just the contents that matter for file.
However, this does not change how the PHP interpreter, webserver or browser handles your file.
(Somehow related: File on php showing HTML document)
Comment: From [the documentation](http://php.net/manual/en/intro.mime-magic.php): "This extension is derived from Apache mod_mime_magic, which is itself based on the `file` command […]"
Comment: the inbuilt php function `mime_content_type()` does evaluate to `text/x-tex` as well. so it simply invokes the `file` utility as well?
Comment: aight. thanks for pointing to a documentation. upvoted and marked as answered. thanks. so unless file is changing its precedence over the tags mentioned one needs to avoid using `\input` in namespace definitions.

namespace definition changes mimetype


Replace SQL Cursor with alternative to improve performance

Question: I'm trying to do some processing over the following Customer_Item view

CustomerId
Amount
ItemId
ItemPrice
IsActiveStore
Priority

1
1000
1
100
1
1

1
1000
2
200
1
2

1
1000
3
300
0
3

2
5000
4
4000
1
5

2
5000
5
1100
1
7

2
5000
6
500
1
9

For each customer, I want to subtract the prices of the related items, that are ordered by priority, from his amount, and update the status for each item accordingly
In case IsActiveStore is false or the amount reaches zero, then skip the item
Notes:

Priorities are not sequential, just ordered as shown for the second customer
If the price of any item ordered by priority exceeds the amount of the customer (after subtracting the previous items), then it will be skipped and the processing will continue for the rest of the priorities as shown for the second customer

So the customer table after updating should be as follows

CustomerId
Amount

1
700

2
500

And the items table after updating should be as follows

ItemId
ItemStatus

1
subtracted

2
subtracted

3
skipped

4
subtracted

5
skipped

6
subtracted

Now I'm doing this by looping over the customer with a cursor, and for each customer, I'm using another cursor to loop over the related items, this worked but it takes a long time for large data.
Is there any faster alternative to do the same processing efficiently?
Thanks in advance.
Comment: The problem with the cumulative sum is that whether or not an item is skipped is both dependent on and affects the cumulative sum and you can't create self referencing formula like that
Comment: If you show us your current attempt that would help us demonstrate a set based method.
Comment: I don't have time to look further, but I would research gaps-and-islands techniques using window functions. Also research cumulative sum using window functions. I think the solution will involve components of both.
Comment: @MartinSmith Yes the first priority will be skipped, and processing will not stop.
Comment: It seems they've since deleted that question then @DaleK . Though I would *hope* they could simplify their attempt to demonstrate their implementation.
Comment: "Now I'm doing this by looping over the customer with a cursor ...".  SQL is a set based languange.  You don't loop through your records.
Comment: @Merna - this is where you come back to us and let us know whether the answer below solved your problem.
Comment: What are the expected results if the price in the first row was `10,000`? Would CustomerId 1's first priority be skipped as over the `1,000` "Amount" and the `1,000` would go forward to be used on the Priority 2 item? Or would processing just stop there and all lower priority items be skipped? As there isn't an example in the data of this
Comment: Thanks @DaleK, I will read about the topics you mentioned, and sorry for the late response
Comment: @ThomA it will take a lot of work to simplify what I actually wrote as it is complex, and I tried before to post it but my question was deleted for that reason, I hope that the example and results desired are clear enough
Answer: You can solve it by a CTE:
WITH cte AS (
    SELECT  *
    FROM
    (
        VALUES  (1, 1000, 1, 100, 1, 1)
        ,   (1, 1000, 2, 200, 1, 2)
        ,   (1, 1000, 3, 300, 0, 3)
        ,   (2, 5000, 4, 1000, 1, 1)
        ,   (2, 5000, 5, 4000, 1, 2)
        ,   (2, 5000, 6, 500, 1, 3)
    ) t (CustomerId,Amount,ItemId,ItemPrice,IsActiveStore,Priority)
)
, cte2 AS (
    SELECT  customerid, CASE WHEN amount < itemprice * isActiveStore THEN 0 ELSE amount - itemprice * isActiveStore END AS amount_left, itemId
    ,   1 AS substracted
    ,   priority
    FROM    cte
    WHERE   priority = 1
    UNION ALL
    SELECT  c.customerid, CASE WHEN c2.amount_left < itemprice * isActiveStore THEN 0 ELSE amount_left - itemprice * isActiveStore END AS amount_left, c.itemid
    ,   CASE WHEN c2.amount_left > 0 AND isActiveStore = 1 THEN 1 ELSE 0 END
    ,   c.priority
    FROM    cte c
    INNER JOIN cte2 c2
        ON  c2.customerid = c.customerid
        AND c2.priority = c.priority - 1
    )
SELECT  customerid, min(amount_left) OVER(partition BY customerid), itemid, CASE substracted WHEN 1 THEN 'substracted' ELSE 'skipped' END
FROM    cte2
OPTION(MAXRECURSION 0)

Although I'm not sure if it will be faster than a cursor, at least not as long as priority isn't indexed correctly.
The CTE itself is pretty standard, you create an initial amount and then calculate the difference for each row.
Comment: Thanks @siggemannen for the answer, I think you assumed from my question that priority should start from 1 and it is sequential, I will update the question as it can be any number not necessarily sequential but still ordered. Sorry for the late response
Answer: This is one of those requirements that is in the annoying category that in principle it would be perfectly possible to do everything with a single scan of the data in order of CustomerId, Priority but in practice there is no SQL Syntax to express this (whether or not an item is skipped is both dependent on and affects the cumulative sum and you can't have a cumulative sum expression dependent on itself).
A cursor or similar iterative approach (perhaps in CLR) is quite possibly the best way of doing this kind of recursive cumulative sum calculation.
This is an example of what Itzik Ben Gan called "Progressive ordered calculations" in his omnibus feature request paper.
The *.doc only seems available on the wayback machine  (This specific connect request was closed as "Won't fix").
It is possible to salvage the recursive CTE approach to deal with non sequential Priority using a similar approach to here to allow the recursive part to still use an index seek but I extremely doubt that this will be any performance improvement.
WITH R AS
(
    -- Anchor
    SELECT CustomerId, ItemId, ItemPrice, Priority,
           RemainingAmount = IIF(IsActiveStore = 1 AND Amount >= ItemPrice, Amount-ItemPrice, Amount),
           ItemStatus = IIF(IsActiveStore = 1 AND Amount >= ItemPrice, 'subtracted', 'skipped')
    FROM
    (
    SELECT *,
        RN = ROW_NUMBER() OVER (PARTITION BY CustomerId ORDER BY Priority)
        FROM CustomerItem
    ) D
    WHERE D.RN = 1

    UNION ALL

    -- Recursive
    SELECT CustomerId, ItemId, ItemPrice, Priority,
           RemainingAmount = IIF(IsActiveStore = 1 AND RemainingAmount >= ItemPrice, RemainingAmount-ItemPrice, RemainingAmount),
           ItemStatus = IIF(IsActiveStore = 1 AND RemainingAmount >= ItemPrice, 'subtracted', 'skipped')
    FROM
    (
        SELECT
            C.*,
            R.RemainingAmount,
            R.ItemStatus,
            RN = ROW_NUMBER() OVER (PARTITION BY C.CustomerId ORDER BY C.Priority)
        FROM R
        JOIN CustomerItem AS C
            ON C.CustomerId = R.CustomerId AND C.Priority > R.Priority
    ) AS Q1
    WHERE
        Q1.rn = 1
)
SELECT
    *
FROM R
ORDER BY CustomerId, Priority

Fiddle
Comment: Thanks @Martin for the detailed answer, I'll try this recursive solution on the actual data and compare the performance with the cursor to see if there is any improvement or not
Answer: This is also a kind of cursor, since I don't see any other option but to iterate through the items that each customer wants, in order of priority, to detect when it reaches his limit.
It makes use of a temporary table to mark items not selectable during the loop (reusing isActiveStore). You'll have to see if there's any improvement in performance, beyond the test data.
if object_id('tempdb..#civ') is not null
    drop table #civ

select * into #civ from Customer_Item

-- exclude items with price beyond Amount
update #civ
set isActiveStore = 0
where ItemPrice > Amount

-- updating one record each time
set rowcount 1
declare @rc tinyint = 1
while @rc = 1
begin
    -- disabling item each time it exceeds the Amount
    update citt
    set isActiveStore = 0
    from
    (select isActiveStore
        ,   Amount
        , ( sum(ItemPrice * isActiveStore)
            over (partition by CustomerId
                      order by [Priority] )
          ) as SumPrices
    from #civ) citt
    where SumPrices > Amount

    set @rc = @@ROWCOUNT
end
set rowcount 0

-- Items table to update
select CustomerId, ItemId,
    case isActiveStore
        when 0 then 'Skipped' else 'Subtracted'
    end as NewItemStatus
from #civ

-- Customers table to update
select CustomerID, Amount
    , Amount - max(SumPrices) as NewAmount
from (
select CustomerId
    ,  Amount
    , ( sum(ItemPrice * isActiveStore)
        over (partition by CustomerId
                  order by [Priority] )
      ) as SumPrices
from #civ) citt
group by CustomerId, Amount

drop table #civ

db<>fiddle
Answer: I think you should ignore this view that you have. Looks like you need two UPDATE statements on the base tables.
The first needs to do a cumulative sum over the Item table, setting subtracted where the cumulative sum is <= Amount. Note that since you also want to set the IsActiveStore = 0 rows, you need to add it to the PARTITION BY otherwise the sum won't be correct.
WITH cte AS (
    SELECT
      i.*,
      c.Amount,
      SUM(i.ItemPrice) OVER (PARTITION BY i.CustomerId, i.IsActiveStore
        ORDER BY I.Priority ROWS UNBOUNDED PRECEDING) AS CumeSum
    FROM Item i
    JOIN Customer c ON c.CustomerId = i.CustomerId
)
UPDATE cte
SET ItemStatus = IIF(IsActiveStore = 0 OR CumeSum > Amount, 'skipped', 'subtracted');

Then you simply update the Customer table, grouping up all those Item rows and subtracting the total.
UPDATE c
SET Amount -= ISNULL(i.Total, 0)
FROM Customer c
CROSS APPLY (
    SELECT SUM(i.ItemPrice) AS Total
    FROM Item i
    WHERE c.CustomerId = i.CustomerId
      AND i.ItemStatus = 'subtracted'
    GROUP BY
      i.CustomerId
) i;

db<>fiddle
Comment: It doesn't address the issue that rows that are skipped shouldn't contribute to the cumulative sum https://dbfiddle.uk/kuw3YCMp - if a customer's priority 1 item is 10K and they only have 1K then they still might have budget for priority 2
Comment: Hmmm I had assumed the logic would just have been to stop at whatever point is too high in the cumulative sum. The edge cases are not clear in the question. I've fixed the null issue.
Comment: Thanks @Charlieface for the answer, the case  that Martin mentioned is right, I'll update my question to clarify this point


Using kwargs in functions

Question: I am trying to use kwargs in this way:
def calculator(**optional_values):
    if optional_value.get('maximum'):
       number = 15*value
    if optional_value.get('minimum):
       number = 5*value

so if i run the following:
   calculator(maximum=5)
it would do: 15*5

I am not sure how to accomplish this. Any pointers would be very helpful
Comment: "get" returns a result. First store it in "value" and if "value" isn't "None" use it.
Answer: Here is a working code for what you want to do :
def calculator(**optional_values):
    if 'maximum' in optional_values:
        return 15*optional_values.get("maximum")
    if 'minimum' in optional_values:
        return 5*optional_values.get("minimum")

print(calculator(maximum=5))

this outputs : 75 which is 15*5 as you wanted.

Using kwargs in functions


extract attributes values from an activerecord query object in rails 2.3

Question: In my controller I have a @attach object and when I inspect it, it has values as
[#<MessageAddlAttachment id: 80, reminder_id: 112, msg_attachment_file_name: "24.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 272368, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">, #<MessageAddlAttachment id: 81, reminder_id: 112, msg_attachment_file_name: "37.png", msg_attachment_content_type: "image/png", msg_attachment_file_size: 333986, created_at: "2013-10-10 12:04:37", updated_at: "2013-10-10 12:04:37">]

So now after some operation I need to create an entry in this MessageAddlAttachment table with different ids. How can I achieve it. I tried dup but it will have same ids. Please help
Answer: dup is your friend in rails 4. it will create a copy but removes the id value:
u = User.first
=> #<User id: 1, ...>
u.dup
=> #<User id: nil, ...>
u.dup.save
   (0.2ms)  begin transaction
...

Answer: Starting either rails 3.2 or 3.1, you want to use dup. Prior to that, you should use clone instead. That will give you new values for the id field; you might want to pay attention to what happens to your created_at and updated_at fields as well.
Another issue to watch out for is if you have any date fields with validations that say they must be after "today's date", they may have been valid when the original record was saved, but not when the new record is saved. How you resolve this will depend on your situation; you might want to disable validations completely while cloning, or adjust the values in the new records.
Comment: I used clone method but how do I avoid created_at and updated_at attributes to be cloned and save it with correct values
Comment: In my situation I wanted the records to have the original created_at values, so that's probably what you're seeing. If you want them updated, you'll probably have to explicitly set .created_at to Time.now and .save the record, which ought to update the .updated_at field for you.


How to share wireless Internet with Ubuntu?

Question:
Possible Duplicate:
How to share a wired internet connection via Wifi?

I have a PC which connects to the Internet via wifi. However, my ISP only allows one PC to connect to the Internet at the same time.
Also, I have a wireless router, so I want to connect this router to my laptop and share my Internet connection via this router.
Is there any way I can do that?
Comment: it's documented on the ubuntu documentation wiki here: https://help.ubuntu.com/community/Router ... if you run in to an issue while working through the guide edit to ask that specific question and i'll see if i can get you passed it.
Answer: It is very easy. You connect to the wireless network as normal. Then select the wired network connection, and in the IPv4 settings, select "Method: Shared with other computers".
Now your wireless connection will be shared on the wired one. Connect your router, and it will share it with other computers in your network.


Mysql query returns duplicate results for each record

Question: I am not a sql guru but I have three tables that I added a foreign key to each (maybe thats where the problem is)
|---------------------|    |---------------------|   |---------------------|
|   DISTINCT_DEALER   |    |  DISTINCT_CUSTOMER  |   |    CUSTOMER_SALES   |
|---------------------|    |---------------------|   |---------------------|
|      d_id   (pk)    |    |       d_id          |   |        d_id         |
|---------------------|    |---------------------|   |---------------------|
|    dealer_address   |    |     dealer_name     |   |   customer_number   |
|---------------------|    |---------------------|   |---------------------|
|    dealer_city      |    |   customer_number   |   |    total_sales      |
|---------------------|    |---------------------|   |---------------------|
|    dealer_state     |    |    customer_name    |
|---------------------|    |---------------------|
|    dealer_zip       |    |    customer_email   |
|---------------------|    |---------------------|

I have a FK for distinct_customers d_id ref on distinct_dealer d_id and a FK on customer sales on d_id referencing distinct_dealer d_id.
when I run this query below, it returns every record duplicate 54 times (number of total records for that one d_id.
select d.d_id, d.dealer_name, cs.total_sales from dship d
join cs_sales cs on d.d_id = cs.d_id order by d.d_id

It looks like its returning a record for each d_id, can someone see what I am doing wrong?
Answer: I think you want aggregation:
select d.d_id, d.dealer_name,
       sum(cs.total_sales)
from dship d join
     cs_sales cs
     on d.d_id = cs.d_id
group by d.d_id;

Comment: yes but I am also trying to bring in each sale per customer.  With that query, it sums the dealership sales per dealership.  What I want to do is list each Dealership with its customer name and each sale per customer.


Integral involving logarithm and cosine

Question: For $a,b>0$ I would like to compute the integral $$I=\int_0^{2\pi} -\log{\sqrt{a^2+b^2-2ab\cos{t}}}~dt.$$
Numerical computations suggest that $$I=\min\{-\log{a},-\log{b}\}.$$
How can I prove this? I tried to find the antiderivative using Mathematica, but the result looks awfull.
Have you seen such an integral? Some reference would be great!
Comment: $\cos 2\pi=\cos 0=1$ so this means if we substitute with the cosine rule we get the same index ${\sqrt{a^2+b^2-2ab}}$                 ,which implies our integral is zero if our anti derivative is even ,we shouls use this to show that $I=\in{ -\log a,-\log b}$...
$I=\int_{\sqrt{a^2+b^2-2ab}}^{\sqrt{a^2+b^2-2ab}}\frac{c\log c}{ab\sqrt{1-\frac{(a^2+b^2-c^2)^2}{4a^2b^2}}} dc$
Comment: $I=\text{min} \{-\log a,-\log b \}$
Comment: This question lacks important context such as where you encountered the integral and why it is of interest.
Comment: I tried to prove Newton's theorem in two dimensions, at some point I got stuck at this integral.
Answer: We have
$$I=\dfrac12\int_0^{2\pi} -\log(a^2+b^2-2ab\cos{t})dt=\int_0^{\pi} -\log(a^2+b^2-2ab\cos{t})dt$$
We then have
$$I=-2\pi\log(b) -\int_0^{\pi} \log((a/b)^2+1-2(a/b)\cos{t})dt$$
Let us call $a/b$ as $a$ from now on. Hence, we want to evaluate the integral
$$I(a) = \displaystyle \int_0^{\pi} \ln \left(1-2a \cos(x) + a^2\right) dx$$ Some preliminary results on $I(a)$. Note that we have $$I(a) = \underbrace{\displaystyle \int_0^{\pi} \ln \left(1+2a \cos(x) + a^2\right) dx}_{\spadesuit} = \overbrace{\dfrac12 \displaystyle \int_0^{2\pi} \ln \left(1-2a \cos(x) + a^2\right) dx}^{\clubsuit}$$ $(\spadesuit)$ can be seen by replacing $x \mapsto \pi-x$ and $(\clubsuit)$ can be obtained by splitting the integral from $0$ to $\pi$ and $\pi$ to $2 \pi$ and replacing $x$ by $\pi+x$ in the second integral.
Now let us move on to our computation of $I(a)$.
\begin{align}
I(a^2) & = \int_0^{\pi} \ln \left(1-2a^2 \cos(x) + a^4\right) dx = \dfrac12 \int_0^{2\pi} \ln \left(1-2a^2 \cos(x) + a^4\right) dx\\
& = \dfrac12 \int_0^{2\pi} \ln \left((1+a^2)^2-2a^2(1+ \cos(x))\right) dx = \dfrac12 \int_0^{2\pi} \ln \left((1+a^2)^2-4a^2 \cos^2(x/2)\right) dx\\
& = \dfrac12 \int_0^{2\pi} \ln \left(1+a^2-2a \cos(x/2)\right) dx + \dfrac12 \int_0^{2\pi} \ln \left(1+a^2+2a \cos(x/2)\right) dx
\end{align}
Now replace $x/2=t$ in both integrals above to get
\begin{align}
I(a^2) & = \int_0^{\pi} \ln \left(1+a^2-2a \cos(t)\right) dt + \int_0^{\pi} \ln \left(1+a^2+2a \cos(t)\right) dt = 2I(a)
\end{align}
Now for $a \in [0,1)$, this gives us that $I(a) = 0$. This is because we have $I(0) = 0$ and $$I(a) = \dfrac{I(a^{2^n})}{2^n}$$ Now let $n \to \infty$ and use continuity to conclude that $I(a) = 0$ for $a \in [0,1)$. Now lets get back to our original problem. Consider $a>1$. We have
\begin{align*}
I(1/a) & = \int_0^{\pi} \ln \left(1-\dfrac2{a} \cos(x) + \dfrac1{a^2}\right)dx\\
& = \int_0^{\pi} \ln(1-2a \cos(x) + a^2) dx - 2\int_0^{\pi} \ln(a)dx\\
& = I(a) - 2 \pi \ln(a)\\
& = 0  & \text{(Since $1/a < 1$, we have $I(1/a) = 0$)}
\end{align*}
Hence, we get that
$$I(a) = \begin{cases} 2 \pi \ln(a) & a \geq 1 \\ 0 & a \in [0,1] \end{cases}$$
Adapted from here
Answer: The term under the square root can be written as either $(ae^{it}-b)(ae^{-it}-b)$ or $(a-be^{it})(a-be^{-it})$.
You want to choose the one where neither factor crosses the negative real axis.  That is, you want to write
$$
a^2+b^2-2ab\cos t=(c-de^{it})(c-de^{-it}),
$$
where $c=\max(a,b)$ and $d=\min(a,b)$.  Then the integral becomes
$$
\int_{0}^{2\pi}-\log\sqrt{(c-de^{it})(c-de^{-it})}dt=-\frac{1}{2}\int_{0}^{2\pi}\log(c-de^{it})dt-\frac{1}{2}\int_{0}^{2\pi}\log(c-de^{-it})dt.
$$
Each term can be evaluated as a contour integral.  Letting $z=e^{it}$ in the first term, and $z=e^{-it}$ in the second, we have
$$
-\frac{1}{i}\int_{\Gamma}\frac{\log(c-dz)}{z}dz,
$$
where $\Gamma$ is the unit circle.  Because $c\ge d>0$, the contour avoids the branch cut, so the only contribution is from the pole at $z=0$:
$$
I=-{2\pi}\log c=-2\pi\log\max(a,b).
$$
This agrees with your result except for the factor of $2\pi$.

Integral involving logarithm and cosine


Load an image from an input stream in Python

Question: I am using Python Imaging Library to do some processing, and I'd like to feed my script with data through a pipe rather than passing a file name as an argument.
I've seen that Image.open can accept any file-like object besides a string as parameter. I've tried passing sys.stdin directly, but it seems that it is having some problems with seek (logically).
So, how can I wrap the stream into a buffer that provides all the file operations? (or other any suitable solution to read the image directly from stdin).
Answer: Use StringIO.
import StringIO
import sys

filelike = StringIO.StringIO(sys.stdin.read())

# Now use `filelike` as a regular open file, e.g.:
filelike.seek(2)
print filelike.read()

Comment: I had already find the solution and was about to auto-answer this very same, but thanks anyway! :-)


Calculate IP device total up and down time from table

Question: I want to calculate total UP and Down time of IP device from SQL table. I am inserting a row in a table after every connection up and down event of a particular IP device.
My sample table is :
create table connected (IP nvarchar (50), stat char(10), ts datetime);

insert into connected values
('10.0.0.1','down',cast('2022-09-13 4:00:00.000' as datetime)),
('10.0.0.2','down',cast('2022-09-13 6:30:00.000' as datetime)),
('10.0.0.1','up',cast('2022-09-13 4:30:00.000' as datetime)),
('10.0.0.2','up',cast('2022-09-13 6:55:00.000' as datetime)),
('10.0.0.3','down',cast('2022-09-13 18:00:00.000' as datetime)),
('10.0.0.1','down',cast('2022-09-13 6:00:00.000' as datetime)),
('10.0.0.1','up',cast('2022-09-13 6:20:00.000' as datetime));

There can be multiple events of a IP device in a single day but it is sure that if any particular ip device have entry of down then the next entry for that particular device be up.
Now I want two results

Device IP- and total up and down time between two dates.
For example :

Ip---------  Totalup time-------- Total Down Time
10.0.0.1----  1400min -------------- 50min
10.0.0.2------ 1415min---------------25min
10.0.0.3------1080min --------------60min ( this should be calculate based on current time)

Detailed entry for each device with total down time

IP-----------------Down Time ------------------ Up Time -------  Total DownTime
10.0.0.1-------13-09-2022 4:00:000 ----- 13-09-2022 4:30:000 ---------30min
10.0.0.1-------13-09-2022 6:00:000 ----- 13-09-2022 6:20:000 ---------20min
10.0.0.2-------13-09-2022 6:30:000 ----- 13-09-2022 6:55:000 ---------25min
10.0.0.3-------13-09-2022 18:00:000 ----- 13-09-2022 19:00:000 --------60min (based on current time because for 10.0.0.3 we dont have up event in the table)

Comment: The datetimes in the input sample is different than the datetimes in the output results, this is confusing!
Comment: Hi Ahmed, Thanks for replying. Actually , the output is with some sample date , please considered the actual date & time given in insert queries.
Comment: I don't understand the logic for `10.0.0.3------1080min --------------60min` where does 1080 come from?
Comment: @Charlieface , For 10.0.0.3 , It shows the result for particular 13th sep 2022 date . the device was down at 18:00 , so the uptime was 60min *18hrs = 1080 min is up time and when I am executing this query , it will calculate the downtime with that time.
Comment: So you are calculating each day separately, and assuming the device was up at `00:00:00`?
Comment: suppose , If I have to check on particular date i.e 13th september, what was the status of all IP devices then it should show the result based on 24hrs. If there is no down entry for particular IP device on that day , then it will be considered as 24hrs UP. And In case I select two dates , then accordingly it will show result like 1st sep to 30th sep.
Answer: You can use LEAD to calculate the next timestamp for each row, then simply aggregate the results.
SELECT
  c.IP,
  UpTime =   SUM(CASE WHEN c.stat = 'up'   THEN DATEDIFF(second, c.ts, c.NextTime) END) / 60,
  DownTime = SUM(CASE WHEN c.stat = 'down' THEN DATEDIFF(second, c.ts, c.NextTime) END) / 60
FROM (
    SELECT *,
      NextTime = LEAD(c.ts, 1, GETDATE()) OVER (PARTITION BY c.IP ORDER BY c.ts)
    FROM connected c
) c
GROUP BY
  c.IP;

db<>fiddle
Since the default given for LEAD is GETDATE() it will depend on your timezone.


UICollectionView cell starting margin

Question: I'm using a UICollectionView to display lottery numbers.
I want the cells of the collectionView to start after a custom spacing, and in that spacing i would like to display a Header, or a custom UIView of some kind.
now my collection view looks like this:
123
456
789
i would like it to look like this:
view12
345678
9.....
i'm thinking about using a custom layout, but the UICollectionViewFlowLayout serves my purpose.
is there any solution for this problem?
Answer: Solved.
since i only had to tweak the layout, just for a little bit, i decided to use a subclass of UICollectionViewFlowLayout.
this way, i can "play" with the layout as i wish, change the frame of headers/footers etc.
my solution works like this:
.h
<code>@interface MyUICollectionViewFlowLayout : UICollectionViewFlowLayout

@end
</code>
.m
<code>#define HEADER_VIEW_WIDTH 132
#define HEADER_VIEW_HEIGHT 44

@interface MyUICollectionViewFlowLayout ()

@end

@implementation MyUICollectionViewFlowLayout

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSMutableArray *allAttributes = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    for (UICollectionViewLayoutAttributes *attribute in allAttributes) {

// if it's a cell, change it's layout to be right after the Header, and in the same line.
        if (attribute.representedElementCategory == UICollectionElementCategoryCell) {

            switch (attribute.indexPath.row) {
                case 0:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH, 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 1:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 2:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 2 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 3:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 3 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 4:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 4 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 5:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 5 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
                case 6:
                    attribute.frame = CGRectMake(HEADER_VIEW_WIDTH + attribute.frame.size.width * 6 , 0, attribute.frame.size.width, attribute.frame.size.height);
                    break;
            // if it's a header view, move it to the same line as all the cells.
        } else if (attribute.representedElementCategory == UICollectionElementCategorySupplementaryView){

            attribute.frame = CGRectMake(0, 0 , HEADER_VIEW_WIDTH, HEADER_VIEW_HEIGHT);
        }
    }
    return allAttributes;
}

@end
</code>
i guess that instead of switch/case, i could have written some algorithm, but i prefer to leave optimization issues for later.

UICollectionView cell starting margin


Unbound type constructor error

Question: I have a problem with interlocked modules:
I want to refer to a type defined in the first module.
module type E = sig
    type event
end

type ev = Ev;;

module EE : E = struct type event = ev end;;

module  type StateType = functor (E : E ) ->  sig
    type event = E.event

    type state_t = {
        mutable event_success : event option;
    }

    val set_event_success : state_t -> event option -> unit
    val create : unit -> state_t
end

module State   : StateType =  functor (E : E) -> struct
    type event = E.event

    type  state_t = {
        mutable event_success : event option;
    }

    let create  ()  = {
        event_success = None;
    }

    let set_event_success s e = (s.event_success <- e;)
end

module S = State(struct type event = ev end);;

let s = S.create ();;

S.set_event_success s (Some(Ev));;

\- : unit = ()
So, it works.
module type  AgentType =
  functor (S: StateType) -> functor (E : E) ->
sig

  type event = E.event
  type state_t = S.state_t
end

I get this error:
Error: Unbound type constructor S.state_t

I don't understand why I get this error, since S is clearly set with the module StateType.
My goal is to do the following declaration:
module Ag = Agent ( State(struct type event = ev end)) (struct type event = ev end)

How can I do that?
Answer: That's because StateType is the type of a functor, not a module.
You should declare StateType as
module type StateType =
sig
  type event

  type state_t = {
    mutable event_success : event option;
  }

  val set_event_success : state_t -> event option -> unit

  val create : unit -> state_t
end

and  the functor State as
module State (E : E)  : (StateType with type event = E.event) =
struct
  type event = E.event

  type  state_t = {
    mutable event_success : event option;
  }

  let create  ()  = {
    event_success = None;
  }

  let set_event_success s e = (s.event_success <- e;)
end

How to solve this kind of problems:
Don't write functor types.
Instead write the signature of the output module and use with type to add type equations.
For Agent, the output signature would be be
module type AgentType =
sig
  type event
  type state_t
end

and the Agent functor would look like
module Agent (S : StateType) (E : E) : (AgentType with type event = E.event and type state_t = S.state_t) = …

Comment: It works with State module, but it doesn't solve the problem with Agent module
Comment: Just apply to `Agent` the same modifications that I applied to `State` (I have added some instructions to my answer).

Unbound type constructor error


Bootstrap carousel full width issue

Question: I am using bootstrap v 3.3.5's carousel with background images that need to be full width. I have set a min-height on the background images so that the full image shows. But there is a margin on left and right of the slides which I can't seem to be able to get rid of.
My HTML:

                            Ever wondered what goes into making a brake pad?

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut luctus congue ante sed sagittis.
                            Quisque ves tibulum lectus et posuere commodom.

                        View Case Study

                            Heading 2 Goes Here

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut luctus congue ante sed sagittis.
                            Quisque ves tibulum lectus et posuere commodom.

                        View Case Study

                            Heading 3 Goes Here

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut luctus congue ante sed sagittis.
                            Quisque ves tibulum lectus et posuere commodom.

                        View Case Study

                            Heading 4 Goes Here

                            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut luctus congue ante sed sagittis.
                            Quisque ves tibulum lectus et posuere commodom.

                        View Case Study

The CSS:
.carousel, .item {overflow: hidden;}
.carousel-inner .item {transition: 0.4s ease-in-out left;}
.banner .carousel-inner {margin: 0;}

.banner {
    margin-top: -40px;
    margin-bottom: -1px;
    position: relative;
}
.fox-img1 {
    width: 436px;
    height: 682px;
    background: url(../img/avatar.png) no-repeat;
    position: absolute;
    right: 0; top: 0;
    z-index: 99;
}
    .banner .item {
         min-height: 730px;
    }
        .item1 {background: url(../img/banner-img1b.jpg) top center no-repeat;}
        .item2 {background: url(../img/banner-img1b.jpg) top center no-repeat;}
        .item3 {background: url(../img/banner-img1b.jpg) top center no-repeat;}
        .item4 {background: url(../img/banner-img1b.jpg) top center no-repeat;}

I tried adding .banner {margin: 0!important; padding: 0!important} but it doesnt remove the margins on each side.
Answer: Bootstrap has default padding on the carousel.
#myCarousel{
  padding: 0px;
}

Please note that on mobile you may actually want this to prevent your captions from going to the edge of the screens on the device.  You can do this by just removing the padding on larger screens:
@media(min-width: 996px){
  #myCarousel{
    padding: 0px;
  }
}

Comment: works. since this is the first answer I shall accept this in 7 mins(after the waiting time)
Answer: Seems to work just fine with:
.banner{
    padding: 0;
}

Is your CSS generating properly? Or do you have a screen with over 2700px width?
Answer: You will actually get stunned to hear the solution....Just remove the

before the

and this works perfectly fine.When using Bootstrap Carousel try avoiding the container-fluid class

Bootstrap carousel full width issue


Issue with posting variable created with ajax

Question: This is a tough one.. I am attempting to use ajax for the first time. basically upon selecting an option from the first field, js and xml run a php script which creates the next dropdown based of of information it pulls from an SQL table. Surprisingly everything works pretty well, for my first attempt. the problem  comes when you run the final query the variable that should be posted over ($_POST['ports'];) evaluates to a single white space character, not the value selected in the  tag. time for the code:
html:

Enter port data to set how your table will look

<select style="width:150px;" onChange="showUser(this.value)">

<option value="">Select A Table Type</option>
<option value="option1">option1</option>
<option value="247">Custom</option>
</select>

javascript:
function showUser(str){
document.getElementById('hide').style.display='none';
document.getElementById('select2').innerHTML="";
if(str===""){
    document.getElementById('hide').style.display='none';
    document.getElementById('select2').innerHTML="";
    return;
}

if(str==="247"){
    document.getElementById('hide').style.display='block';
    return;
}

// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest){
    xmlhttp=new XMLHttpRequest();
}

// code for IE6, IE5
else{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

//set up return
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById("select2").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethtml.php?q="+str,true);
xmlhttp.send();
}

gethtml.php
//include connection
include 'log.php';

//get vars
$q=$_GET['q'];

//make the query
$sql = "SELECT DISTINCT Model
FROM tbl
WHERE Manufacturer = '".$q."'";

//make the new box
echo '<select name="ports" style="width:150px;">';
echo '<option>Select A Port Total</option>';
$i=1;
foreach($conn->query($sql) as $row) {
echo $row['Model'];
echo '<option value="'.$row['Model'].'">'.$row['Model'].'</option>';
$i++;
}
echo "</select>";

so, everything is sent to gethtml.php. the query runs correctly, the <select> box is there, however there seems to be an error with the <select> part of it, and i just cant figure out what that is. Here is a snippet from the submission php the runs after you submit the form that the <select> is messing up on.
echo "
";print_r($_POST);echo"
";

which outputs
Array
(
[ports] =>
)

I know you can't tell, but when i highlight that bit, there is a whitespace character there, i even ran it through an isset() to see it i was right and there is a character there.
here is an image of the xml created html when viewed with firebug:

Anyone have any ideas? This is very frustrating.. obviously, the firebug image is showing it not looking the way it should... if you guys need any more information please just ask
If its worth noting, im using chrome.
Answer: you are not posting your ajax request.
xmlhttp.open("GET","gethtml.php?q="+str,true);

you are sending it via get. in php, try print_r($_GET) instead of $_POST and check if you see the right value.
Comment: @JohnDoe try opening firebug/developer tools and look at the XMLHttpRequest. you can see the method you are using to send as well as the url and variables you are sending via post/get. This allows you to double check you are sending to the server what you expect.
Comment: Perhaps I'm not looking in the right places, but i cant seem to find any place that it will show me what im sending, all I get is a more in depth view of the html to php xml script.
Comment: what browser are you using?
Comment: on the page, press f12, go to the network tab. change the select and it should show the ajax request. you can see the url, method (and more) right there and if you click on the url you can see details of the request (post vars, response)
Comment: I think i found what we are looking for, when I submit it to the final php page, the developer panel actually shows the variables posted over, everything aperars to tranfer over INCLUDING the 12: ports:12 AND it is sent using the post method
Comment: Even the literal URL posted over carries the 12
Comment: Found my problem, i had two field with name ports somehow, and one, not being set, was clearing the other. Thanks for the pointers on the dev tools though.
Answer:     foreach($conn->query($sql) as $row) {
echo $row['Model'];
echo '<option value="'.$row['Model'].'">'.$row['Model'].'</option>';
$i++;
}

Look at line 2, above.
Comment: if it solved the problem..."...but not why it is posting over a whitespace rather than the value 12"
Comment: Nice catch, that explains why firebug was showing the 12 but not why it is posting over a whitespace rather than the value 12,


Adding Facebook Online Account - "application you are trying to use doesn't exist or has been disabled"

Question: I noticed on April 9 that Empathy wasn't connecting to Facebook Chat, so I opened Online Accounts, and it appears that I needed to authorize Ubuntu to access Facebook.  But then I couldn't do that - when I try, the web server at Facebook responds with
"Facebook
Error Accessing App
We're sorry, but the application you're trying to use doesn't exist or has been disabled."
I tried removing and adding the Facebook account again, and got the same result.
Does anyone know if Facebook shut down the authentication app due to the Heartbleed bug?  If so, any word on when it will be back up again?
Comment: 13.10.  All software has been updated.
Comment: I with the same problem.
Comment: What ubuntu version are you on?
Comment: Same really kinda annoying cause I use my other messenger accounts far less.
Comment: This bug is known and beeing fixed: See: https://bugs.launchpad.net/account-plugins/+bug/1304798
Answer: I also experienced the same problem. There is an update released for empathy which fixes this. Software Updater should do it, or check out some launchpad ppa for empathy
Comment: Now fixed in Ubuntu 14.04.


how to change screen brightness when entering background

Question: I have a 'low power' mode in my app that dims screen to 0 brightness. I'd like to restore the brightness when user backgrounds the app.  I am calling
<code>[UIScreen mainScreen].brightness = 1.0f;
</code>
in my UIApplicationDidEnterBackgroundNotification handler code, but it doesn't work. (my app doesn't have access to mainScreen at that moment anymore?)
is there a way to do this? I couldn't find anything that gives a WillEnterBackground effect.
Answer: Did you try putting the code in applicationWillResignActive? I was having the same problem, and moved my code from applicationDidEnterBackground to applicationWillResignActive, and it switched the screen brightness before moving the app to the background.
Comment: You may add some links to the documentation to complete the answer.


Query to get user info and list of roles in a single row

Question: I have been asked to develop a query on Postgresql 9.2, which I have only limited exposure to, that will return a users information (from the users table) along with their roles (from the role table - a user may have many roles) in a single row. What I have is:
[user table] --> [user_role table] <-- [role table]
users table: id, firstname, lastname, username, ... ;
user_role table: id, user_id (fk to user);
role_id (fk to role); role table: id, name;

What I need to get is:
users.firstname, users.lastname, users.username, users....(other user info),
role.name, role.name (one role name for each role a user has).

Comment: please add the *real* definitions. I don't read shorthand notation.
Answer: Something like this, I expect:
SELECT u.id, u.firstname, u.lastname, array_agg(r.name)
FROM user u
LEFT OUTER JOIN user_role ur ON (u.id = ur.user_id)
LEFT OUTER JOIN role r ON (ur.role_id = r.id)
GROUP BY u.id;

You might want string_agg instead of array_agg depending on desired output format.
It's untested since you didn't provide sample data. If you're on an old PostgreSQL version you will need to explicitly specify every column of user that appears in the SELECT list in the GROUP BY list too.
Note that the roles are returned in a single column. That's necessary; there's no support for dynamic width tables where different rows can have different widths. You can use pretty much any format you like for the result - delimited text, xml, json, hstore, array, etc.
Your user_role.id column is completely unnecessary and should probably be replaced with PRIMARY KEY(user_id, role_id) unless you're dealing with stupid ORMs that can't cope with composite primary keys.
Comment: Thany you worked great - did change array_agg to string_agg. Also thanks for the comment on user_role.id - this is not my database but I will take to comment to the user.


How to tell when a fraction does not end?

Question: Is there a way in math / programming to tell if a fraction (reciprocal in particular) does not end?
For example, 1/3 is 0.33 repeated, but 1/2 is just 0.5
Is there a way to find if 1/n for any natural number n is never ending?
Context:
Writing a program and want to find out if I need to round 1/n (round in my way rather than whatever the machine does) before adding it to another digit.
E.g Since 1/3 is never ending, the machine will probably cut off some of the 3's at the end, and 1 + 1/3 = 1.33333. I want to be able to catch that 1/3 is never ending (or if 1/n is Not never ending) so that when I add a "never ending" number to 1, I can round it in my own way (i.e. I can round 0.3 up to 0.5, rather than the computers way of rounding never ending reciprocals / fractions).
Comment: Hint: when you're doing long division algorithm, if a reminder repeats at any step, then the decimal form is going to be recurring. If you hit the reminder 0 at any step, the fraction is a proper fraction.
Answer: Hint: If a fraction in reduced form $\tfrac{a}{b}$ has a terminating decimal expansion, then $10^k\tfrac{a}{b}$ is an integer for sufficiently large $k$ (why is this?). Thus you can characterize the fractions with terminating decimal expansion solely in terms of $b$.


Files Shown in Terminal not Show on Desktop

Question: I have an issue where I am creating .cap files with aircrack-ng and am saving them to the desktop, but I can't see them. When I use the ls command in the terminal they show up, but just not on the graphical desktop view. I want to be able to see them on the desktop and not just through the terminal. Any help would be appreciated, thanks!
EDIT: Turns out I am not saving them to the desktop, but rather the /home/user/ directory. The hidden files show up when I press CTR + H, but they don't show up in the terminal; the only file showing up in the terminal when I use the ls command is the desktop (sorry for the topic edit). How can I get the hidden files to show up in the terminal as well?
Comment: What is your file manager?
Comment: What is the output of `ls -al ~/Desktop`? (Please [edit](http://askubuntu.com/posts/496787/edit) it into your question)
Comment: please post your ls list screen shot and your file manager
Comment: I wish there was a way to accept two answers because I asked two questions :/.
Answer: Files that start with a . are hidden from the graphical interface.
To view them, just open up your file browser and go to 'Edit'->'Preferences' and check 'Show hidden files and backup files'.
You can also toggle the hidden files using Ctrl+H
EDIT:
To get the hidden files to show up in terminal, use:
cd
ls -al

cd takes you back to your home folder while ls -al lists (the -l flag) all files (the -a flag) hidden or not.
Comment: Thank you for this information! It solved one of my two issues, my new one now edited to the same post. I would give this answer a plus if I could, but I don't have 15 reputation yet haha.
Answer: To view files list use ls command.
To view hidden files as well use ls -a or la commands.
Hidden files will have . before them.
Eg: you should use ls /home/user/ and for hidden files la /home/user/ for list view ls -al /home/user/
Comment: Although `la` doesn't work, `ls -a` does. This may be because this is an Ubuntu focused site and I'm using Kali Linux, but I don't know for sure. Thank you very much! This completes the second part of the answer to my questions :).
Comment: `ls ~` is the same as `ls /home/USER` by the way
Comment: yes its the same.


trouble with fixing elements in row in flutter

Question: look at the pic

I don't want  elements to change their positions especially in horizontal axis when their strings changed
I mean it should be like a table with  fixed columns.
can I do this just with row?
Comment: Can you include  [minimal-reproducible-example](https://stackoverflow.com/help/minimal-reproducible-example)
Answer: It's probably because you set a defined width for spacing.
You could use a combination of Flexible & Expanded widgets to wrap all the children in your Row.
That should align them correctly.

You can find the corresponding code here


Flutter Flame: Player Movement Stop after no key is pressed not working

Question: I've been trying to create player movement in my Flutter game. I want the player to stop moving if no movement key is pressed but the code below doesn't work:
import 'dart:async';
import 'package:farm_game/farm_lands.dart';
import 'package:flame/components.dart';
import 'package:flame/sprite.dart';
import 'package:flutter/src/services/raw_keyboard.dart';

enum PlayerState {
  idle,
  backIdle,
  leftIdle,
  rightIdle,
  walkFront,
  walkBack,
  walkLeft,
  walkRight
}

enum PlayerDirection {
  front,
  back,
  left,
  right,
  none
}

class Player extends SpriteAnimationGroupComponent
    with HasGameRef<FarmLands>, KeyboardHandler {
  late final SpriteSheet spriteSheet;
  final double stepTime = 0.3;

  PlayerDirection playerDirection = PlayerDirection.none;
  double moveSpeed = 50;
  Vector2 velocity = Vector2.zero();

  Player({position}): super(position: position);

  @override
  FutureOr<void> onLoad() {
    spriteSheet = SpriteSheet.fromColumnsAndRows(
      image: game.images.fromCache('characters/Character_Spritesheet.png'),
      columns: 4, // Number of columns in the sprite sheet
      rows: 4, // Number of rows in the sprite sheet
    );
    _loadAllAnimations();
    return super.onLoad();
  }

  @override
  void update(double dt) {
    _updatePlayerMovement(dt);
    super.update(dt);
  }

  @override
  bool onKeyEvent(RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isLeftKeyPressed = keysPressed.contains(LogicalKeyboardKey.keyA) ||
        keysPressed.contains(LogicalKeyboardKey.arrowLeft);
    final isRightKeyPressed = keysPressed.contains(LogicalKeyboardKey.keyD) ||
        keysPressed.contains(LogicalKeyboardKey.arrowRight);
    final isUpKeyPressed = keysPressed.contains(LogicalKeyboardKey.keyW) ||
        keysPressed.contains(LogicalKeyboardKey.arrowUp);
    final isDownKeyPressed = keysPressed.contains(LogicalKeyboardKey.keyS) ||
        keysPressed.contains(LogicalKeyboardKey.arrowDown);

    if (isLeftKeyPressed && isRightKeyPressed) {
      playerDirection = PlayerDirection.none;
    } else if (isUpKeyPressed && isDownKeyPressed) {
      playerDirection = PlayerDirection.none;
    } else if (isLeftKeyPressed) {
      playerDirection = PlayerDirection.left;
      print('left');
    } else if (isRightKeyPressed) {
      playerDirection = PlayerDirection.right;
      print('right');
    } else if (isUpKeyPressed) {
      playerDirection = PlayerDirection.back;
      print('back');
    } else if (isDownKeyPressed) {
      playerDirection = PlayerDirection.front;
      print('front');
    } else {
      playerDirection = PlayerDirection.none;
    }
    return super.onKeyEvent(event, keysPressed);
  }

  void _updatePlayerMovement(double dt){
    double dirX = 0.0;
    double dirY = 0.0;
    switch(playerDirection){
      case PlayerDirection.front:
        current = PlayerState.walkFront;
        dirY += moveSpeed;
        break;
      case PlayerDirection.back:
        current = PlayerState.walkBack;
        dirY -= moveSpeed;
        break;
      case PlayerDirection.left:
        current = PlayerState.walkLeft;
        dirX -= moveSpeed;
        break;
      case PlayerDirection.right:
        current = PlayerState.walkRight;
        dirX += moveSpeed;
        break;
      case PlayerDirection.none:
        current = PlayerState.idle;
        break;
      default:

    }
    velocity = Vector2(dirX, dirY);
    position += velocity * dt;
  }

  // Load all animations
  void _loadAllAnimations() {

    // Create sprite animations using the sprite sheet
    animations = {
      PlayerState.idle: spriteSheet.createAnimation(
          row: 0,
          stepTime: stepTime,
          from: 0,
          to: 2,
      ),
      PlayerState.backIdle: spriteSheet.createAnimation(
          row: 1,
          stepTime: stepTime,
          from: 0,
          to: 2
      ),
      PlayerState.leftIdle: spriteSheet.createAnimation(
          row: 2,
          stepTime: stepTime,
          from: 0,
          to: 2
      ),
      PlayerState.rightIdle: spriteSheet.createAnimation(
          row: 3,
          stepTime: stepTime,
          from: 0,
          to: 2
      ),
      PlayerState.walkFront: spriteSheet.createAnimation(
          row: 0,
          stepTime: stepTime,
          from: 2,
          to: 4
      ),
      PlayerState.walkBack: spriteSheet.createAnimation(
          row: 1,
          stepTime: stepTime,
          from: 2,
          to: 4
      ),
      PlayerState.walkLeft: spriteSheet.createAnimation(
          row: 2,
          stepTime: stepTime,
          from: 2,
          to: 4
      ),
      PlayerState.walkRight: spriteSheet.createAnimation(
          row: 3,
          stepTime: stepTime,
          from: 2,
          to: 4
      ),
    };
  }
}

Also, player movement keys are only available when I remove the else statement at the end. I'm sorry if this is a dumb question, I'm still new to Flutter and Flame.
I tried moving the PlayerDirection.none to higher parts of the code and also tried to add a boolean if keyup then PlayerDirection.none and else the movement keys are activated.
Answer: You can simplify that logic a bit and get it correctly working:
class Player extends SpriteAnimationGroupComponent
    with HasGameRef<FarmLands>, KeyboardHandler {
  late final SpriteSheet spriteSheet;
  final double stepTime = 0.3;

  double _speed = 50;
  final Vector2 _direction = Vector2.zero();

  Player({position}): super(position: position);

  @override
  FutureOr<void> onLoad() {
    ...
  }

  @override
  void update(double dt) {
    super.update(dt);
    final displacement = _direction.normalized() * _speed * dt;
    position.add(displacement);
  }

  @override
  bool onKeyEvent(RawKeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    final isKeyDown = event is RawKeyDownEvent;

    // Avoiding repeat event as we are interested only in
    // key up and key down event.
    if (!event.repeat) {
      if (event.logicalKey == LogicalKeyboardKey.keyA) {
        _direction.x += isKeyDown ? -1 : 1;
      } else if (event.logicalKey == LogicalKeyboardKey.keyD) {
        _direction.x += isKeyDown ? 1 : -1;
      } else if (event.logicalKey == LogicalKeyboardKey.keyW) {
        _direction.y += isKeyDown ? -1 : 1;
      } else if (event.logicalKey == LogicalKeyboardKey.keyS) {
        _direction.y += isKeyDown ? 1 : -1;
      }
    }

    return super.onKeyEvent(event, keysPressed);
  }

  // Load all animations
  ...
}

The code is extracted from this example:
https://examples.flame-engine.org/#/Input_Keyboard
Answer:
Quick update to Spydon's Answer code snippet this since Flame 1.16.0 was released
!event.repeat looks to have been removed, you just need to access it through
the KeyRepeatEvent subclass
  @override
  bool onKeyEvent(KeyEvent event, Set<LogicalKeyboardKey> keysPressed) {
    horizontalMovement = 0;
// Add this to access the repeat bool
    final isKeyRepeat = event is KeyRepeatEvent;
    final isKeyDown = event is KeyDownEvent;

// Avoiding repeat event as we are interested only in
// key up and key down event.
if (!isKeyRepeat) {
  if (event.logicalKey == LogicalKeyboardKey.keyA) {
    _direction.x += isKeyDown ? -1 : 1;
  } else if (event.logicalKey == LogicalKeyboardKey.keyD) {
    _direction.x += isKeyDown ? 1 : -1;
  } else if (event.logicalKey == LogicalKeyboardKey.keyW) {
    _direction.y += isKeyDown ? -1 : 1;
  } else if (event.logicalKey == LogicalKeyboardKey.keyS) {
    _direction.y += isKeyDown ? 1 : -1;
  }
}
return super.onKeyEvent(event, keysPressed);
}


How to change the heading for \tableofcontents in Latex?

Question: I've been trying to change the layout of my \tableofcontents in Latex for a while now and I can't find a solution. So the problem is, I have some chapters added before the table of contents. I managed to disable all headings for the frontmatter, but now the title of the last chapter is being shown.
I'm using the scrbook environment and nothing really seems to work. This is how I create my frontmatter in a seperate toc_lof_lot_lol.tex file.
\renewcommand{\contentsname}{Inhaltsverzeichnis}
\renewcommand{\listfigurename}{Abbildungsverzeichnis}
\renewcommand{\listtablename}{Tabellenverzeichnis}
\renewcommand{\listalgorithmname}{Pseudocodeverzeichnis}
\renewcommand{\lstlistlistingname}{Quelltextverzeichnis}

\tableofcontents

\listoffigures\thispagestyle{empty}
\clearpage{\pagestyle{empty}\cleardoublepage}
\listoftables\thispagestyle{empty}
\clearpage{\pagestyle{empty}\cleardoublepage}
\lstlistoflistings\thispagestyle{empty}
\clearpage{\pagestyle{empty}\cleardoublepage}

\setcounter{page}{1}

This is the content before the table of contents in 01_0_fundamental_stuff_root.tex
\chapter{Liste der Abkürzungen}
\thispagestyle{empty}
\begin{itemize}
    \item \textbf{A} - Text A
    \item \textbf{B} - Text B
    \item \textbf{V} - Text C
\end{itemize}
\clearpage

And this is my document structure
\begin{document}
\frontmatter
    \include{chapters/00_title/00_title}
    \include{chapters/01_fundamental_stuff/01_0_fundamental_stuff_root}
    \include{sources/toc_lof_lot_lol}
\mainmatter
    \doublespacing
    \include{...}
    ...
\backmatter
    \singlespacing
    ...
\end{document}

My Table of contents looks like this right now, but I either want to change the text in the heading to "Inhaltsverzeichnis" or simply delete the text in the heading completely
Answer: So I managed to create an invisible chapter before the table of contents, so the text in the heading changed to "Inhaltsverzeichnis"
I added this command before the beginning of the document
\makeatletter
\newcommand{\unchapter}[1]{%
  \begingroup
  \let\@makechapterhead\@gobble % make \@makechapterhead do nothing
  \chapter{#1}
  \endgroup
}
\makeatother

Then I changed the \tableofcontents command in the toc_lof_lot_lol.tex
\let\oldtableofcontents\tableofcontents
\makeatletter
\renewcommand{\tableofcontents}{%
\unchapter{Inhaltsverzeichnis}
  \oldtableofcontents%
}
\makeatother

\tableofcontents

Definitely not the correct way to go, but solved my problem.


Ambiguous error in Xcode 8 beta 6

Question: After updating to Xcode 8 beta 6, I'm getting the following error:

Value of type 'Any' has no member 'cgRectValue'

on the following block:
var tmpContentViewFrameOrigin: CGPoint?
var tmpCircleViewFrameOrigin: CGPoint?
var keyboardHasBeenShown:Bool = false

func keyboardWillShow(_ notification: Notification) {
    keyboardHasBeenShown = true
    if let userInfo = (notification as NSNotification).userInfo {
        if let beginKeyBoardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]!.cgRectValue.origin.y {
            if let endKeyBoardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.cgRectValue.origin.y {
                tmpContentViewFrameOrigin = self.contentView.frame.origin
                tmpCircleViewFrameOrigin = self.circleBG.frame.origin
                let newContentViewFrameY = beginKeyBoardFrame - endKeyBoardFrame - self.contentView.frame.origin.y
                let newBallViewFrameY = self.circleBG.frame.origin.y - newContentViewFrameY
                self.contentView.frame.origin.y -= newContentViewFrameY
                self.circleBG.frame.origin.y = newBallViewFrameY
            }
        }
    }
}

and these two lines specifically:
  if let beginKeyBoardFrame = userInfo[UIKeyboardFrameBeginUserInfoKey]!.cgRectValue.origin.y {
     if let endKeyBoardFrame = userInfo[UIKeyboardFrameEndUserInfoKey]?.cgRectValue.origin.y {

I may be missing something ever so simple... any suggestions?
Answer: cgRectValue is a property on the NSValue class. What you get out of the userInfo dictionary isn't known to be an NSValue, so you can't access NSValue properties on it.
For the compiler to let you use those properties, you need to let it know that you expect that value to be an NSValue:
if let beginKeyBoardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.origin.y {

(This didn't result in compiler errors before because dictionaries in imported Cocoa APIs bridged with a value type of AnyObject. AnyObject has some magic like the ObjC id type, in that the compiler will let you call any method/property on it—with the result wrapped in an Optional because it may not exist. Now that dictionaries have Any as their value type, you need to explicitly say what you expect the value type to be.)
Comment: wow, that makes sense. I was looking through the userInfo portion of the new doc's but couldn't sniff out anything that pointed to that. Thanks anyhow!

Ambiguous error in Xcode 8 beta 6


Here Routes SDK - How do I add a GeoPolygon to the AvoidanceOptions in order for the route to ignore certain specified areas when being calculated?

Question: I am using the explorer edition of the Here Routes SDK for Android. I am trying to add customizable polygons to a list of areas in which the route must avoid when being calculated.
I tried using avoidanceOptions.addAvoidArea(), but the method is not recognised and I cannot find documentation for it.
I have found avoidanceOptions.avoidAreas.add() in the documentation: "https://developer.here.com/documentation/android-sdk-explore/188.8.131.52/api_reference/com/here/sdk/routing/AvoidanceOptions.html#avoidAreas",
but avoidAreas is a List. I need to use a GeoPolygon as I cannot be limited to rectangles.
Has the feature of avoiding polygons been removed and is there perhaps a different way to accomplish this task?
I did intially try to use avoidanceOptions.avoidAreas.add() using a GeoPolygon, but that did not work as it was expecting a GeoBox. I was expecting the polygon to be added to the list of areas to avoid when the route is calculated. I added this last paragraph because Stack Overflow was asking me to elaborate. I don't really know what else to say. This is my first question.
Answer: Usage example of AvoidanceOptions for areas:
GeoCoordinates southWest = new GeoCoordinates(southWest.latitude, southWest.longitude);
GeoCoordinates northEast = new GeoCoordinates(northEast.latitude, northEast.longitude);

carOptions.avoidanceOptions.avoidAreas.add(new GeoBox(southWest, northEast));

See also this question.
Answer: Unfortunately, SDK 4.x doesn't allow to calculate route avoidance by polygon but only by rectangle(i.e. GeoBox)
Therefore workaround is to:

split polygon to many rectangles and this is geometry task.

Or use HERE Map Attributes API v8 + custom function "isPointInPolygon" to get segmentIds which you can then use in avoidanceOptions (carOptions.avoidanceOptions.segments.add(new SegmentReference()) - see little explanation bellow at the bottom

split polygon to many rectangles:
Several relevant algorithms and libraries that may help you with your task of splitting a polygon into smaller rectangles. Here's a summary:

Polygon Splitting: The polygon-splitter JavaScript library can be used to split a polygon into smaller parts using a line. This library works with various types of polygons including concave polygons, polygons with holes, and multi-part geometries【 https://github.com/rowanwins/polygon-splitter 】.

Fitting Rectangles in a Circle: A Stack Overflow answer provides a JavaScript function for fitting as many squares as possible into a circle. This approach could potentially be adapted to work with polygons, but it would likely require significant modifications【 Placing rectangles inside a circle properly 】.

Dividing a Polygon into Rectangles: A question was posed on the Computer Science Stack Exchange about dividing a polygon into as few rectangles as possible. Although there was no definitive solution provided, it was suggested that the problem might involve an acceptable level of non-polygon area to be covered by rectangles【 https://cs.stackexchange.com/questions/146085/algorithm-for-dividing-a-polygon-into-rectangles 】. The original poster later found a Wikipedia article on Polygon Covering, which might provide further insights.

Please note that the feasibility and complexity of this task could vary greatly depending on the specifics of your use case, such as the shapes of the polygons and the constraints on the rectangles.

Or use HERE Map Attributes API v8 + custom function "isPointInPolygon"...:

Calculate first tileIds for every vertices of your polygon utilizing formula(https://developer.here.com/documentation/content-map-attributes/dev_guide/topics/here-map-content.html):

tile size = 180° / 2^level [degree]

tileY = trunc((latitude  +  90°) / tile size)

tileX = trunc((longitude + 180°) / tile size)

tileID = tileY * 2 * (2^level) + tileX
Where the level is always "road functional class" + 8 E.g. the layer containing the functional class 2 (= roughly second level) roads has tiling level 10.
And you need to calculate tileIds for every Functional class (from 1 to 5)

For all tileIds you can get segmentIds send request like https://smap.hereapi.com/v8/maps/attributes?in=tile%3A430628%2C27537700%2C27537701%2C110158410&layers=ROAD_GEOM_FC1%2CROAD_GEOM_FC4%2CROAD_GEOM_FC4%2CROAD_GEOM_FC5&apikey=yourapikey

In response you can see field TOPOLOGY_ID - this is your segmentId

You need now to check all coordinates of geometries if they in your polygon utilize this example: http://jsfiddle.net/m1ey7p2h/1/
function isPointInPolygon(testPoint, polygPoints) {
let result = false;
let j = polygPoints.length - 1;
for(i=0,len=j+1; i<len; i++){
let p = polygPoints[i];
let lP = polygPoints[j];
if(p.y < testPoint.y && lP.y >= testPoint.y || lP.y < testPoint.y && p.y >= testPoint.y){
if((p.x + (testPoint.y - p.y) / (lP.y - p.y) * (lP.x - p.x)) < testPoint.x){
result = !result;
}
}
j = i;
}
return result;
}


How to get parameters of calling class

Question: I have one class that creates an instance of another class.  Is it possible for the second class to retrieve parameters from the calling class.
For example
Class_A {
    protected $myArray = array('item 1', 'item2', 'item3')

    public function __construct()
    {
        $nextClass = new ClassB();
        echo $nextClass->countArrayItems();
    }
}

Class_B {
    public function countArrayItems()
    {
        return count(Class_A->myArray);
    }
}

$newClass = new Class_A;

Answer: You could pass a reference to your Class_A instance to your Class_B constructor:
Class_A {
    public $myArray = array('item 1', 'item2', 'item3')

    public function __construct()
    {
        $nextClass = new Class_B($this);
        echo $nextClass->countArrayItems();
    }
}

Class_B {
    public function __construct($classA_instance) {
        $this->classA_instance = $classA_instance;
    }
    public function countArrayItems()
    {
        return count($this->classA_instance->myArray);
    }
}

$newClass = new Class_A;

(as noted by @chris, Class_A->myArray needs to be public)
Comment: I would further define an interface and force the class instances to match it. `function __construct(ClassA $classA) {...}`
Comment: I agree this would be the way to go here. This pattern is known as http://en.wikipedia.org/wiki/Dependency_injection
Answer: Only if you pass the instance of class A to class B
Class_A {
    protected $myArray = array('item 1', 'item2', 'item3')

    public function __construct()
    {
        $nextClass = new ClassB();
        echo $nextClass->countArrayItems($this);
    }
}

Class_B {
    public function countArrayItems($callingClass)
    {
        return count($callingClass->myArray);
    }
}

$newClass = new Class_A;

How to get parameters of calling class