Proof by induction using factorials

Question: Prove by induction that:
There are exactly $n-k+1\choose{k}$ choices for choosing k numbers from the set {1,,,,n} with no two numbers adjacent.
I have no idea :( I thought I would start with base case n=1, k=1 then assume true for n but then not at all sure for last step.
Answer: Not what you seem to be looking for, but...
Call your numbers $1 \le a_1 < a_2 < \ldots < a_k \le n$, and define auxiliary variables $x_0$ through $x_k$, where:
$\begin{align}
    1 + x_0       &= a_1 \\
  a_1 + x_1 + 2   &= a_2 \\
                  &\ldots \\
  a_{k - 1} + x_{k - 1} + 2 &= a_k \\
  a_k + x_k &= n
\end{align}$
Note that for all $i$ we have $x_i \ge 0$, and furthermore by adding up all equations:
$\begin{align}
   x_0 + x_1 + \dotsb + x_k + 2 k - 1 = n
\end{align}$
So you are all set up, by the typical stars-and-bars argument this has
$$
\binom{(n - 2 k + 1) + (k + 1) - 1}{(k + 1) - 1}
  = \binom{n - k + 1}{k}
$$
solutions.
Added later: For stars-and-bars here, if you have $x_1 + \dotsb + x_k = n$, imagine you have $n$ stars ($*$) to be distributed among $k$ buckets (the $x_i$), separated by $k - 1$ bars ($|$). This is  string of $n + k$ places in all, and $k - 1$ of those are to be taken by the bars. Thus
$$\binom{n + k - 1}{k - 1}$$
possibilities in all.
Comment: oh no you are right sorry
Comment: I get it now, it comes from the bars and stars explanation. Thank you so much for your help. You are a star :)
Comment: where you have added up all the equations should it not be 2k+1?
Comment: I understand until bars and stars, why do we add k on the top line and how did you get k+1-1?
Comment: @CamMack, edited adding the explanation
Comment: In your solution you have (n-2k+1) + (k+1) - 1.
Comment: I do not understand in your final part to the solution it says
Comment: Sorry I hit enter too soon, the k+1 comes from x0 to xk, where does the minus 1 come from? @vonbrand
Answer: Here is a combinatorial proof of the formula:
Place $n - k$ red balls in a row.  This creates $n - k + 1$ gaps, consisting of $n - k - 1$ gaps between successive balls and the two ends of the row.  If $k \leq n - k + 1$, we can select $k$ of these $n - k + 1$ gaps in which to place $k$ blue balls.  We can now number the balls from left to right. Therefore, there are $$\binom{n - k + 1}{k}$$ ways to select $k$ numbers from the set $\{1, 2, \ldots, n\}$ so that no two consecutive numbers are adjacent.
Answer: I prefer a combinatorial explanation, but you can prove it by a double induction as follows. For $k\ge 1$ let $P(k)$ be the statement that the set $[n]=\{1,\ldots,n\}$ has $\binom{n-k+1}k$ acceptable $k$-subsets for each $n\ge 1$. This is clearly true for $k=1$, since $\binom{n-1+1}1=n$, and every $1$-element subset of $[n]$ is acceptable.
Now suppose that $k>1$, and that $P(\ell)$ is true for $1\le\ell<k$; we'll prove $P(k)$ by induction on $n$. That is, we'll prove by induction on $n$ that $[n]$ has $\binom{n-k+1}k$ acceptable $k$-subsets for each $n\ge 1$.
This is certainly true for $n=1$: $\binom{n-k+1}k=\binom{-k}k=0$, and $\{1\}$ certainly has no acceptable $k$-element subset when $k>1$.
For the induction step let $n>1$, and assume as induction hypothesis that $[m]$ has $\binom{m-k+1}k$ acceptable $k$-subsets for $1\le m<n$. We want to show that $[n]$ has $\binom{n-k+1}k$ acceptable $k$-subsets.
We'll split the acceptable $k$-subsets of $[n]$ into two types, those that contain the number $n$ and those that do not. It's easier to count the second type, so I'll start with it.

$A$ is an acceptable $k$-subset of $[n]$ that does not contain $n$ if and only if $A$ is an acceptable $k$-subset of $[n-1]$; by the induction hypothesis on $n$ there are $\binom{(n-1)-k+1}k=\binom{n-k}k$ such sets.
$A$ is an acceptable $k$-subset of $[n]$ that contains $n$ if and only if $A\setminus\{n\}$ is an acceptable $(k-1)$-subset of $[n-1]$ that does not contain the number $n-1$, i.e., if and only if $A\setminus\{n\}$ is an acceptable $(k-1)$-subset of $[n-2]$. By the induction hypothesis on $k$ there are $\binom{(n-2)-(k-1)+1}{k-1}=\binom{n-k}{k-1}$ such sets.

Thus, the total number of acceptable $k$-subsets of $[n]$ is
$$\binom{n-k}k+\binom{n-k}{k-1}=\binom{n-k+1}k$$
by Pascal's identity. It follows that $[n]$ has $\binom{n-k+1}k$ acceptable $k$-subsets for all $n\ge 1$, i.e., that $P(k)$ is true. This completes the induction step of the induction on $k$, and we can therefore conclude that $P(k)$ is true for all $k\ge 1$.

Proof by induction using factorials


R: Greenhouse-Geisser in Anova from car package

Question: i have a question concerning the output from {car} Anova. I want to run a simple 2x2 repeated measures ANOVA using the multivariate approach. I can run the (modified) example from the Anova {car} help page:
phase <- factor(rep(c("pretest", "posttest", "followup"), c(5, 5, 5)),
                levels=c("pretest", "posttest", "followup"))
hour <- ordered(rep(1:5, 3))
idata <- data.frame(phase, hour)
idata

mod.ok <- lm(cbind(pre.1, pre.2, pre.3, pre.4, pre.5,
                post.1, post.2, post.3, post.4, post.5,
                fup.1, fup.2, fup.3, fup.4, fup.5) ~  1,
            data=OBrienKaiser)

(av.ok <- Anova(mod.ok, idata=idata, idesign=~phase*hour) )
b<-summary(av.ok)

Which gives the following (shortened) output
Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

                SS num Df Error SS den Df        F    Pr(>F)
(Intercept) 7260.0      1   603.33     15 180.4972 9.100e-10 ***
phase        167.5      2   169.17     30  14.8522 3.286e-05 ***
hour         106.3      4    73.71     60  21.6309 4.360e-11 ***
phase:hour    11.1      8   122.92    120   1.3525    0.2245
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Mauchly Tests for Sphericity

        Test statistic  p-value
phase             0.70470 0.086304
hour              0.11516 0.000718
phase:hour        0.01139 0.027376

Greenhouse-Geisser and Huynh-Feldt Corrections
for Departure from Sphericity

            GG eps Pr(>F[GG])
phase      0.77202  0.0001891 ***
hour       0.49842  1.578e-06 ***
phase:hour 0.51297  0.2602357
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

            HF eps Pr(>F[HF])
phase      0.84367  0.0001089 ***
hour       0.57470  3.161e-07 ***
phase:hour 0.73031  0.2439922
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

However, with my data (see below) the Greenhouse-Geisser output is missing:
    h2 <-
structure(list(A1neg = c(-8.427556992, 1.20452559, -14.331842422,
-10.428559303, 1.750265002, 9.388166428, 0.790130436, -1.592002392,
0.539065838, -3.758603573, 8.391399384), B1neg = c(-12.188085556,
-1.964554906, -12.247328758, -7.326891422, -0.961694896, -1.048453212,
-4.225459576, 0.173920691, 1.876976371, -9.11947155, -1.706287026
), A1pos = c(-0.660317183, 3.498036146, 22.003242493, 19.905063629,
-3.124288321, 11.968006134, 5.838645935, 5.140467644, 5.154311657,
2.298083067, 1.164232969), B1pos = c(-12.805168152, -1.550003886,
45.990013123, 15.915545464, -1.67797184, 7.565258026, 10.635170937,
12.769438744, 11.738276482, 4.544145107, 0.230011433)), .Names = c("A1neg",
"B1neg", "A1pos", "B1pos"), class = "data.frame", row.names = c("1",
"11", "21", "31", "41", "51", "61", "71", "81", "91", "101"))

condition <- ordered(rep(c("A", "B"), c(2)),
                 levels=c("A", "B"))
reg <- factor(rep(c("neg", "pos"), c(2,2)),
            levels=c("neg", "pos"))
idata<-data.frame(condition, reg)
idata

mod.ok<-lm(cbind( A1neg,B1neg,A1pos,B1pos) ~ 1, data=h2)
(av.ok<-Anova(mod.ok, idata=idata, idesign=~condition*reg))
summary(av.ok)

This gives:
Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

                SS num Df Error SS den Df      F  Pr(>F)
(Intercept)    233.35      1   995.14     10 2.3449 0.15669
condition        3.32      1   373.00     10 0.0891 0.77143
reg           1220.66      1  2135.77     10 5.7153 0.03791 *
condition:reg   62.48      1   176.90     10 3.5318 0.08963 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
>

Do you have any ideas, what went wrong?
Answer: Nothing went wrong. The program did exactly what it was meant to do. It's because you only have a 2x2 factorial design in your example. Mauchly's test for sphericity compares variances of differences between levels of repeated measures factors. Another way of looking at it is the covariance matrix in the repeated measures design. If you have a 2x2 design, there is only one covariance, look at the following variance-covariance matrix (where $A1$ and $A2$ are the repeated measurements):
$$
\left( \begin{array}{ccc}
Var(A1) & Cov(A1, A2)  \\
Cov(A2, A1)  & Var(A2)  \end{array} \right)
$$
There is only one covariance (covariance is symmetric), namely $Cov(A1,A2)=Cov(A2,A1)$. Hence, there is only one variance of the difference $Var(A1-A2)$. So: in a 2x2 design, the sphericity assumption is always met. That's why the function summary.Anova.mlm doesn't calculate Mauchly's test and no Greenhouse-Geisser corrections are given in the output. Here is a very good explanation of sphericity and your problem is also mentioned (section "Complications").
Look what happens if we add another level to your example (I made up the data for "C"):
h2 <- structure(list(A1neg = c(-8.427556992, 1.20452559, -14.331842422,
                               -10.428559303, 1.750265002, 9.388166428, 0.790130436, -1.592002392,
                               0.539065838, -3.758603573, 8.391399384),
                     B1neg = c(-12.188085556,
                               -1.964554906, -12.247328758, -7.326891422, -0.961694896, -1.048453212,
                               -4.225459576, 0.173920691, 1.876976371, -9.11947155, -1.706287026),
                     C1neg = c(1.750265002, 0.539065838, 1.20452559, 8.391399384, -3.758603573,
                               -7.326891422, 0.790130436, -9.11947155, -1.592002392, -12.188085556,
                               -10.428559303),
                     A1pos = c(-0.660317183, 3.498036146, 22.003242493, 19.905063629,
                               -3.124288321, 11.968006134, 5.838645935, 5.140467644, 5.154311657,
                               2.298083067, 1.164232969),
                     B1pos = c(-12.805168152, -1.550003886,
                               45.990013123, 15.915545464, -1.67797184, 7.565258026, 10.635170937,
                               12.769438744, 11.738276482, 4.544145107, 0.230011433),
                     C1pos= c(-1.550003886, 1.164232969, 11.738276482, 5.838645935, -12.805168152,
                              -0.660317183, 22.003242493, 19.905063629, 0.230011433, 7.565258026,
                              5.154311657)),

                .Names = c("A1neg",
                           "B1neg",
                           "C1neg",
                           "A1pos",
                           "B1pos",
                           "C1pos"),
                class = "data.frame", row.names = c("1",
                                                    "11", "21", "31", "41", "51", "61", "71", "81", "91", "101"))

condition <- ordered(rep(c("A", "B", "C"), c(2)),
                     levels=c("A", "B", "C"))
reg <- factor(rep(c("neg", "pos"), c(3,3)),
              levels=c("neg", "pos"))
idata<-data.frame(condition, reg)
idata

mod.ok<-lm(cbind(A1neg,B1neg,C1neg, A1pos,B1pos,C1pos) ~ 1, data=h2)
(av.ok<-Anova(mod.ok, idata=idata, idesign=~condition*reg))
summary(av.ok)

Now the output shows Mauchly's test and the Greenhouse-Geisser correction.
Univariate Type III Repeated-Measures ANOVA Assuming Sphericity

                   SS num Df Error SS den Df      F  Pr(>F)
(Intercept)    248.91      1  1158.47     10 2.1486 0.17342
condition       20.52      2   875.91     20 0.2342 0.79333
reg           1571.69      1  1789.74     10 8.7817 0.01421 *
condition:reg   82.27      2  1244.02     20 0.6613 0.52710
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Mauchly Tests for Sphericity

              Test statistic p-value
condition            0.97043 0.87365
condition:reg        0.48792 0.03959

Greenhouse-Geisser and Huynh-Feldt Corrections
 for Departure from Sphericity

               GG eps Pr(>F[GG])
condition     0.97128     0.7872
condition:reg 0.66134     0.4719

               HF eps Pr(>F[HF])
condition     1.20188     0.7933
condition:reg 0.72312     0.4838

Comment: Perfect, thanks a lot for the explanation and for providing the link.
Comment: @RubenReal You're welcome. Glad I could help.


Iterating through UITextViews within a tableview using Swift

Question: I'm currently learning how to build apps entirely programatically and have hit a bit of a wall in the process.
My app is going to be a fairly simple form that the user can fill in and it will generate a PDF at the end containing the information. For the basic information I have a tableview containing a set of UITextfields and have no problem iterating through them and extracting the data into an array of strings.
For the next section the user needed to input a lot more text so I have used UITextviews within the tableview. What I want to be able to do is extract the text inputted and save it to an array of strings that is used to create my customer object. The code that does this is as follows:
func createGoals() {
   for section in 0..<secondTableView.numberOfSections {

        for row in 0..<secondTableView.numberOfRows(inSection: section) {

            let indexPath = NSIndexPath(row: row, section: section)
            let thisCell = secondTableView.cellForRow(at: indexPath as IndexPath) as! mySecondCell
                if thisCell.textview.text == "Enter Goals" {
                print("NO CONTENT IN FIELD")
                let ac = UIAlertController(title: "But...But...", message: "If you have no goals, how can you progress?!", preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
                break
                }  else {
                    print("I MADE IT")
                    print("\(thisCell.textview.text!)")
                    newClient.goalArray.append(thisCell.textview.text)
                    print(newClient.goalArray)
                    }
        }
    }

}

But when this runs I get the error message "unexpectedly found nil while unwrapping an Optional value" and it particularly highlights this line:
let thisCell = secondTableView.cellForRow(at: indexPath as IndexPath) as! mySecondCell

This code is almost identical to how I iterate through the UITextfields successfully, all thats changed is the variables attached and as far as I can see there are no optionals.
Also if I don't fill in the UITextviews it will show the UIAlertController, it only seems to have a problem when I remove the placeholder and fill in the UITextviews.
Does anyone have any ideas as to why this is happening? I can provide more of my code if needed.
Comment: Debugger is telling you that secondTableView does not contains any cell at the row you passed. Verifying the row count of secondTableView should help.
Comment: I've just tried in the debugger and it is returning 4 rows in section 0 which is as expected. The rows are definitely there, so could my for loop somehow miss one?
Comment: `mySecondCell` seems an instance, not a class. You need to get the cell as a class type ie. `let thisCell = secondTableView.cellForRow(at: indexPath as IndexPath) as! MyCellSubclass` or even better using a guard `guard let thisCell = secondTableView.cellForRow(at: indexPath as IndexPath) as? mySecondCell else { return }`
Answer: here you are loading cell in iteration. so issue is caused because you are going to load/access cell which is not visible.
here you should not load cell out side of cellForRowAtIndexPath.
Reason: UITableView is reusing cell with reusableCellIdentifier.
here you need to save values in array or dictionary when textfield-didEndEditing called (textfield delegate method).
and for validation check you can use saved value from array/dictionary.
Comment: Ok brilliant I will try it that way and see.
Just out of interest is there any reason that loading the cell within the iteration works perfectly when iterating through textFields but not when using textViews?
Comment: if it is working with textFields then it should work with textViews when it it not weak.

if you iterate tableview.visiblecells  you will not get above issue. but here your task is not complete. so for getting modified values from textviews/Textfields you need to save it on didEndEditing.

still there is issue, please check category/extenstion Or super class.
Answer: Here is your optional
as! mySecondCell

Obviously, thisCell isn't a mySecondCell
Check if you did register the correct class
EDIT
You shouldn't call delegate method by yourself
Comment: Oh I didn't realise that still counted as an optional I thought forced downcasts were different. Here is how I have registered it, I'm pretty sure it's right?

Within VDL:
    'secondTableView.delegate = self
        secondTableView.dataSource = self
        secondTableView.register(mySecondCell.self, forCellReuseIdentifier: "secondCellID")',

Also in the cellForRow:

    'if tableView == self.secondTableView {
            let bCell = secondTableView.dequeueReusableCell(withIdentifier: "secondCellID", for: indexPath) as! mySecondCell',

This is the correct way to register right?
Comment: You might be right. I didn't pay attention to where you were using this piece of code. You should read Kalpesh jetani's answer. He's right, you can't call delegate method by yourself


How to ensure uniqueness in manytomany fields in Django

Question: So say you have models like following:
class User(models.Model):

class Tag(models.Model):
    text = models.CharField(unique=True)

class Subscription(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)
    class Meta:
        unique_together = (("owner", "tags"),)

class Post(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)

From the above, you can see that users can have subscriptions based on the tags. Ideally you want to ensure that each set of subscriptions for a user is unique? that's why i added unique_together to the meta class. But i'm getting this error:
Subscription: (models.E013) 'unique_together' refers to a ManyToManyField 'tags', but ManyToManyFields are not permitted in 'unique_together'.

Any ideas? Thx.
Answer: You don't need to specify unique_together. The ManyToManyField in Django is unique by default. Try adding the same relationship twice and you will see you have only one record.
There is a useful Django Snippet for this which I've modified for your example:
from django.db import models
from django.db.models.signals import m2m_changed
from django.dispatch import receiver
from django.db.utils import IntegrityError

class User(models.Model):
    pass

class Tag(models.Model):
    text = models.CharField(unique=True)

class Subscription(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)
    class Meta:
        unique_together = (("owner", "tags"),)

class Post(models.Model):
    owner = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag)

@receiver(m2m_changed, sender=Subscription.tags.through)
def verify_uniqueness(sender, **kwargs):
    subscription = kwargs.get('instance', None)
    action = kwargs.get('action', None)
    tags = kwargs.get('pk_set', None)

    if action == 'pre_add':
        for tag in tags:
            if Subscription.objects.filter(owner=subscription.owner).filter(tag=tag):
                raise IntegrityError('Subscription with owner %s already exists for tag %s' % (subscription.owner, tag))

Comment: This doesn't answer the question as the OP needs uniqueness of the `User` and set of `tags` through the `Subscription` model
Comment: Ah, I misread the question. Thanks for pointing that out. I've updated the answer.
Comment: Thanks for the replies! i think this is in the right direction of what I want. :)
there's a nuance here tho. it's not the duplicated tag i care about. i want to ensure the set is unique. So when i want to insert a new set of tags in subscription, it would be nice to figure out if the new set is unique, and only insert the new set if that's the case.
Comment: For anyone trying to use this, I don't think this is thread safe. As an example, if you have multiple "gunicorn" processes you can't be sure that this solution works for two concurrent requests. If that is not the case for you then its a good solution. Otherwise I suggest using `through` in ManyToManyField and in the middle table handle uniqueness using `unique_together`


Handling long running tasks in pika / RabbitMQ

Question: We're trying to set up a basic directed queue system where a producer will generate several tasks and one or more consumers will grab a task at a time, process it, and acknowledge the message.
The problem is, the processing can take 10-20 minutes, and we're not responding to messages at that time, causing the server to disconnect us.
Here's some pseudo code for our consumer:
#!/usr/bin/env python
import pika
import time

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)
print ' [*] Waiting for messages. To exit press CTRL+C'

def callback(ch, method, properties, body):
    long_running_task(connection)
    ch.basic_ack(delivery_tag = method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                      queue='task_queue')

channel.start_consuming()

After the first task completes, an exception is thrown somewhere deep inside of BlockingConnection, complaining that the socket was reset. In addition, the RabbitMQ logs show that the consumer was disconnected for not responding in time (why it resets the connection rather than sending a FIN is strange, but we won't worry about that).
We searched around a lot because we believed this was the normal use case for RabbitMQ (having a lot of long running tasks that should be split up among many consumers), but it seems like nobody else really had this issue. Finally we stumbled upon a thread where it was recommended to use heartbeats and to spawn the long_running_task() in a separate thread.
So the code has become:
#!/usr/bin/env python
import pika
import time
import threading

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='localhost',
        heartbeat_interval=20))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)
print ' [*] Waiting for messages. To exit press CTRL+C'

def thread_func(ch, method, body):
    long_running_task(connection)
    ch.basic_ack(delivery_tag = method.delivery_tag)

def callback(ch, method, properties, body):
    threading.Thread(target=thread_func, args=(ch, method, body)).start()

channel.basic_qos(prefetch_count=1)
channel.basic_consume(callback,
                      queue='task_queue')

channel.start_consuming()

And this seems to work, but it's very messy. Are we sure that the ch object is thread safe? In addition, imagine that long_running_task() is using that connection parameter to add a task to a new queue (i.e. the first part of this long process is done, let's send the task on to the second part). So, the thread is using the connection object. Is that thread safe?
More to the point, what's the preferred way of doing this? I feel like this is very messy and possibly not thread safe, so maybe we're not doing it right. Thanks!
Comment: I am having the same problem. The docs says pika connection is not thread safe https://pika.readthedocs.org/en/latest/faq.html
Answer: For now, your best bet is to turn off heartbeats, this will keep RabbitMQ from closing the connection if you're blocking for too long. I am experimenting with pika's core connection management and IO loop running in a background thread but it's not stable enough to release.
In pika v1.1.0 this is ConnectionParameters(heartbeat=0)
Comment: Pika `0.12.0` has a better solution, please see [this answer](https://stackoverflow.com/a/52951933/1466825)
Comment: As @Gavin mentioned the best bet as of now is to turn off the heartbeat in pika while setting up the connection.

`connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', virtual_host='TestVirtualHost', credentials=credentials, heartbeat_interval=0, port=5672))`
Comment: Thanks, It works. If its still not working for you. Note that `heartbeat` parameter should be set to both peers (consumer and producer). That's what happened in my case.
Comment: Set `ConnectionParameters(heartbeat=0)` is safe. Because when you have killed this process, the connection is automatically closed immediately. You can go http://rabbit_mq_server:15672/#/connections to verify it.
Answer: Please don't disable heartbeats!
As of Pika 0.12.0, please use the technique described in this example code to run your long-running task on a separate thread and then acknowledge the message from that thread.
Comment: Why is it a bad thing to disable heartbeats?
Comment: This is the best & correct solution. Thanks @LukeBakken.
Comment: Neither RabbitMQ nor your application will detect a lost TCP connection until the next operation is attempted on that connection.
Comment: I get that, but depending on the use case, that's not necessarily a bad thing. In my case I'd rather have an error when trying to ack a message because the connection was lost, than having an error when trying to ack a message because the connection was closed due to my processing taking too long. That's why a general warning not to disable heartbeats seems unjustified IMO. It all depends on the use case, so I believe it would be more productive to say why you maybe should consider not disabling them instead of going "disabling = bad" without any further information.
Comment: @LukeBakken Is there any way to use this method with channel.basic_get? I need my consumer to consume one message, acknowledge it and then die/quit, I can get it to consume only one message with basic_get, but then I cannot get it to acknowledge the (long-running) message.
Comment: If there are a large number of items queued up and the average time to process each one is very high, then the spawning an individual thread for processing a item would lead to an explosion of active threads which finally ends up in OOM error. I have experienced this.
Comment: Stackoverflow answers should be self-contained. In addition to linking to example code, include the example code inline.
Answer: I encounter the same problem you had.
My solution is:

ture off the heartbeat on the server side
evaluate the maximum time the task can possible take
set the client heartbeat timeout to the time got from step2

Why this?
As i test with the following cases:

case one

server heartbeat turn on, 1800s
client unset

I still get error when task running for a very long time -- >1800

case two

turn off server heartbeat
turn off client heartbeat

There is no error on client side, except one problem--when the client crashes(my os restart on some faults), the tcp connection still can be seen at the Rabbitmq Management plugin. And it is confusing.

case three

turn off server heartbeat
turn on client heartbeat, set it to the foresee maximum run time

In this case, i can dynamic change every heatbeat on indivitual client. In fact, i set heartbeat on the machines crashed frequently.Moreover, i can see offline machine through the Rabbitmq Manangement plugin.
Environment
OS: centos x86_64
pika: 0.9.13
rabbitmq: 3.3.1
Comment: You could try something like this:

`params = pika.ConnectionParameters(host=self.__host, port=self.__port, credentials=credentials, heartbeat_interval=)`
Comment: how do you turn on client heartbeat?  can't find anything about how to do it.
Comment: I should have tried your approach first, saved me tons of headache and hairs. thank you for your helpful insight.
Answer:
You can periodic call connection.process_data_events() in your long_running_task(connection), this function will send heartbeat to server when it is been called, and keep the pika client away from close.
Set the heartbeat value greater than call connection.process_data_events() period in your pika BlockingConnection.
Comment: `connection.process_data_events()` help me
Comment: My long-running tasks were largely waiting/sleeping, so this helped a ton. I'm rather surprised how buried and non-intuitive "please tell the server I'm still alive" functionality is in pika, but glad to have finally found it.
Answer: Don't disable heartbeat.
The best solution is to run the task in a separate thread and , set the prefetch_count to 1 so that the consumer only gets 1 unacknowledged message
using something like this channel.basic_qos(prefetch_count=1)

https://github.com/pika/pika/issues/753#issuecomment-318124510
https://www.rabbitmq.com/consumer-prefetch.html
Answer: You can also set up a new thread, and process the message in this new thread, and call .sleep on the connection while this thread is alive to prevent missing heartbeats. Here is a sample code block taken from @gmr in github, and a link to the issue for future reference.
import re
import json
import threading

from google.cloud import bigquery
import pandas as pd
import pika
from unidecode import unidecode

def process_export(url, tablename):
    df = pd.read_csv(csvURL, encoding="utf-8")
    print("read in the csv")
    columns = list(df)
    ascii_only_name = [unidecode(name) for name in columns]
    cleaned_column_names = [re.sub("[^a-zA-Z0-9_ ]", "", name) for name in ascii_only_name]
    underscored_names = [name.replace(" ", "_") for name in cleaned_column_names]
    valid_gbq_tablename = "test." + tablename
    df.columns = underscored_names

    # try:
    df.to_gbq(valid_gbq_tablename, "some_project", if_exists="append", verbose=True, chunksize=10000)
    # print("Finished Exporting")
    # except Exception as error:
    #     print("unable to export due to: ")
    #     print(error)
    #     print()

def data_handler(channel, method, properties, body):
    body = json.loads(body)

    thread = threading.Thread(target=process_export, args=(body["csvURL"], body["tablename"]))
    thread.start()
    while thread.is_alive():  # Loop while the thread is processing
        channel._connection.sleep(1.0)
    print('Back from thread')
    channel.basic_ack(delivery_tag=method.delivery_tag)

def main():
    params = pika.ConnectionParameters(host='localhost', heartbeat=60)
    connection = pika.BlockingConnection(params)
    channel = connection.channel()
    channel.queue_declare(queue="some_queue", durable=True)
    channel.basic_qos(prefetch_count=1)
    channel.basic_consume(data_handler, queue="some_queue")
    try:
        channel.start_consuming()
    except KeyboardInterrupt:
        channel.stop_consuming()
    channel.close()

if __name__ == '__main__':
    main()

The link:
https://github.com/pika/pika/issues/930#issuecomment-360333837
Comment: Please refer to the solution provided by Luke Bakken. It's Thread Safe & refers to an official example from pika documentation.
Answer: Here's one more simple way to handle this with threads. Particularly useful if the consumer app should not consume another job until the current job is finished. The ack can be sent any time- in this case I choose to send it only when the job is done (the thread is no longer alive).
Start the long-running process in its own thread, and then monitor that thread in a loop with calls to channel.process_data_events(). Keep the reference to the connection object in the main thread, since it is not threadsafe. Essentially:
import time
import pika
from threading import Thread
from functools import partial

rmqconn = pika.BlockingConnection( ... )
rmqchan = rmqconn.channel()
rmqchan.basic_consume(
    queue='test',
    on_message_callback=partial(launch_process,rmqconn)
)
rmqchan.start_consuming()

def launch_process(conn,ch,method,properties,body):
    runthread = Thread(target=run_process,args=body)
    runthread.start()
    while runthread.is_alive():
        time.sleep(2)
        conn.process_data_events()
    ch.basic_ack(delivery_tag=method.delivery_tag)

def run_process(body):
    #do the long-running thing
    time.sleep(10)


Proof of normal equation in regression using tensor notation

Question: I'm struggling with a proof of the normal equation, so I posted a question which hopefully will get resolved soon. However, I mentioned there that I'm uncomfortable with the proofs dealing with matrix calculus, particularly when it comes to derivatives of product of vectors or product of matrices and vectors.  Furthermore, there are a couple of "layout conventions" which are not even used consistently. Because of this, I thought I could get rid of all that insanity by using tensor notation instead.
In relation to the normal equation question, I would be very interested in looking at a proof of this equation (here you can see the context):
$$\beta = (X^{T}X)^{-1}X^{T}{\bf{y}}$$
using tensor notation.
And as a more general request, I'd like to get an advice on the issue of dealing with matrix calculus and derivatives. Particularly, I want to hear about your approach when you have to calculate something of this kind given the inconsistencies in notations and non-intuitive nature of some identities. Do you consult Wikipedia or some handbook every time you want to calculate a derivative of some product of vectors or matrices? Do you memorize some recurrent identities? Do you know an alternative procedure?
Comment: Offhand I'm familiar with at least a half dozen conventions that could validly be called "tensor notation."  One of them is infamously called the ["debauch of indices"](http://books.google.com/books?id=_pNwvEu-dloC&pg=PA69&dq=debauch+of+indices+Cartan+geometrie+des+espaces+de+riemann&hl=en&sa=X&ei=mFdaUYX_K7LA4APO34DwAw&ved=0CDEQ6AEwAA#v=onepage&q=debauch%20of%20indices%20Cartan%20geometrie%20des%20espaces%20de%20riemann&f=false): I hope that's not the one you mean! But what exactly do you want?
Comment: That document uses at least two notations. Notice how quickly the author abandons the multiple-subscript notation for the simpler and clearer vector-matrix notation.  Following that procedure yourself is already pretty good advice--if you get tied up tracking subscripts, you will lose sight of what's really going on.
Comment: I didn't know there are so many conventions. I had in mind something like this: https://docs.google.com/viewer?url=http%3A%2F%2Fwww.atmos.washington.edu%2F~dennis%2FMatrixCalculus.pdf in page 4.
Comment: That is actually true. I don't know what you mean by "the author abandons the multiple-subscript notation for the simpler and clearer vector-matrix notation", though. Which part are you referring to?
Comment: At the beginning, equation (1)--a partially written-out array--, equation (2)--the "$[a_{ij}]$" notation--, and the symbol "$A$" at the end of the subsequent paragraph all refer to the same mathematical object. That's three notations right there. Throughout the rest of the document, the first notation is used rarely (eqs (24) and (67) only) and occasionally in abbreviated (block-matrix) form, as in equation (19); the second notation is almost as rarely used (as in equation (13)); and the third notation--which has no subscripts--is used hundreds of times.
Comment: I think the second notation is used to prove the non-intuitive identities of matrix calculus (using the notation without indexes)
Comment: @RobertSmith in your link page4, I see a Jacobian but no 'tensor'
Comment: @cc Starts in page 4. The propositions that follow are good examples.
Comment: @RobertSmith I see the term "partitioned matrices" (still not "tensor") but I guess it's similar
Comment: @cc A matrix is a especial case of a second order tensor. Maybe you're confusing tensors with the idea of tensor notation (using indexes, operations of contraction, etc)
Answer: A "modern" (post-1900) view of tensors is a geometric one.  Perhaps the clearest notation would therefore be a figure, because the "normal equations" are nothing more than a familiar, ages-old theorem of plane geometry!
As a point of departure, let's begin with an expression from your previous question.  The setting is Ordinary least squares (OLS).  The data are the "design matrix" $(x_{i,j})$, $1 \le i \le n$, $1 \le j \le p$ of "independent variables" and a vector of values of the "dependent variable" $y = (y_i)$, $1 \le i \le n$; each dependent value $y_i$ is associated with the $p$-tuple of independent values $(x_{i,1}, x_{i,2}, \ldots, x_{i,p}).$
OLS aims to find a vector $\beta = (\beta_1, \beta_2, \ldots, \beta_p)$ minimizing the sum of squares of residuals
$$\sum_{i=1}^n\left(y_i - \sum_{j=1}^p \left(x_{i,j}\beta_j\right)\right)^2.$$
Geometrically, the inner sum of products represents the application of the linear transformation determined by the matrix $x = (x_{i,j})$ to the $p$-vector $\beta$.  As such we conceive of $x$ as representing a map $x: \mathbb{R}^p\to \mathbb{R}^n$.  The outer sum is the usual Pythagorean formula for the Euclidean distance.  Geometrically, then,

OLS seeks a vector $\hat\beta \in \mathbb{R}^p$ for which $x\hat\beta\in \mathbb{R}^n$ is as close to $y$ as possible.

The test of this is to take any other vector $\beta'\in \mathbb{R}^p$ and to compare distances within the triangle formed by the three points $y$, $x\hat\beta$, and $x\beta'$:

According to Euclid, three (distinct) points determine a plane, so the figure is utterly faithful: all our work is done within this plane.
We also know from Euclid that the ray $y - x\hat\beta$ must be perpendicular to the ray $x\beta' - x\hat\beta$.  (This is the heart of the matter; in making this observation, we are really done and all that remains is to write down an equation expressing this perpendicularity.)  Modern geometry has several notations for perpendicularity, which involves the (usual) "dot product" or positive-definite linear form (a "tensor of type $(2,0)$" if you wish).  I will write it as $\langle\ ,\ \rangle$, whence we have deduced
$$\langle x\beta', y-x\hat\beta\rangle = 0$$
for all $\beta\in\mathbb{R}^p$.  Because the usual dot product of two vectors in $\mathbb{R}^n$ is
$$\langle u, v\rangle = u^\intercal v,$$
the preceding may be written
$$\beta'^\intercal x^\intercal (y - x\hat\beta) = 0.$$
Geometrically, this says that the linear transformation from $\mathbb{R}^{p*}\to\mathbb{R}^n$ defined by applying $x^\intercal (y - x\hat\beta)$ to $\beta'^\intercal$ is the zero transformation, whence its matrix representation must be identically zero:
$$x^\intercal (y - x\hat\beta) = 0.$$
We are done; the conventional notation
$$\hat\beta = \left(x^\intercal x\right)^{-}\left(x^\intercal y\right)$$
(where "$\left(\right)^{-}$" represents a generalized inverse) is merely an algebraically suggestive way of stating the same thing.  Most computations do not actually compute the (generalized) inverse but instead solve the preceding equation directly.

If, as an educational exercise, you really, really want to write things out in coordinates, then I would recommend adopting coordinates appropriate to this configuration.  Choosing an orthonormal basis for $\mathbb{R}^n$ adapted to the plane determined by $y$ and $x\beta'$ for some arbitrary $\beta'$ allows you to forget the remaining $n-2$ coordinates, because they will be constantly $0$.  Whence $y$ can be written $(\eta_1, \eta_2)$, $x$ can be written $(\xi_1, \xi_2)$, and $\beta'$ can be considered a number.  We seek to minimize
$$\sum_{i=1}^n\left(y_i - \sum_{j=1}^p \left(x_{i,j}\beta_j\right)\right)^2=\left(\eta_1 - \xi_1 \beta\right)^2 + \left(\eta_2 - \xi_2 \beta\right)^2.$$
OLS claims that this is achieved for
$$\hat\beta =  \left(x^\intercal x\right)^{-}\left(x^\intercal y\right)=\left(\xi_1^2 + \xi_2^2\right)^{-1}\left(\xi_1 \eta_1 + \xi_2 \eta_2\right)$$
provided $\xi_1^2 + \xi_2^2 \ne 0$.  An elementary way to show this is to expand the former expression into powers of $\beta$ and apply the Quadratic Formula.
Comment: Thanks! I was aware of the geometric proof but I'm more interested in a proof actively using tensors in order to get the terms of $\beta$
Comment: This proof *does* use tensors!
Comment: It could be but I have found that here I get more relevant answers on these topics than in math.stackexchange
Comment: Yes, but the tensors are not central to the proof. Basically, I want to look at the proof because I'd like to get a taste of how to deal with the derivative to minimize the error function in tensor notation.
Comment: That might be a question for the math site rather than here.
Comment: Questions that are purely about mathematical techniques, such as how to take derivatives or manipulate indices, are not on topic here.  The trick is to edit your question to keep it focused on matters of statistical interest, but if that cannot be done, we will migrate the question for you.
Comment: I think it's pretty relevant here since the question deals with linear regression and the request for advice is much more relevant here than in math.stackexchange (you know, mathematicians are comfortable with tensors but in a more abstract setting so they don't have to struggle with this kind of calculation.)
Answer: The proof for the normal equation (in matrix notation):
Let $J$ be the cost function for the linear regression given by
$$
\begin{aligned}
J &= \vert\vert {\bf X}{\bf w} - {\bf t}\vert\vert^2\\
  &= \left({\bf X}{\bf w} - {\bf t}\right)^T\left({\bf X}{\bf w} - {\bf t}\right)\\
 &= \left({\bf w}^T{\bf X}^T - {\bf t}^T\right)\left({\bf X}{\bf w} - {\bf t}\right)\\
&= {\bf w}^T{\bf X}^T{\bf X}{\bf w} - 2{\bf w}^T{\bf X}^T{\bf t}-{\bf t}^T{\bf t}\\
&= \text{Tr}\left({\bf w}{\bf w}^T{\bf X}^T{\bf X}\right)- 2{\bf w}^T{\bf X}^T{\bf t}-{\bf t}^T{\bf t}\\
\end{aligned}
$$
Noting that $\frac{\partial \text{Tr}(AB)}{A} = B^T$, and $\frac{\partial}{\partial {\bf x}}{\bf x}^T{\bf a} ={\bf a}$. We get
$$
\begin{aligned}
\frac{\partial J}{\partial {\bf w}} &= \frac{\partial}{\partial {\bf w}}\left( \text{Tr}\left({\bf w}{\bf w}^T{\bf X}^T{\bf X}\right)- 2{\bf w}^T{\bf X}^T{\bf t}-{\bf t}^T{\bf t}\right)\\
&= ({\bf X}^T{\bf X})\frac{\partial {\bf w}{\bf w}^T}{{\bf w}} - 2{\bf X}^T{\bf t}\\
&= ({\bf X}^T{\bf X})2{\bf w} - 2{\bf X}^T{\bf t}\\
\end{aligned}
$$
Setting this last value to $\bf 0$ and solving for ${\bf w}$ we get:
$$
{\bf w} =({\bf X}^T{\bf X})^{-1}{\bf X}^T{\bf t}
$$

As we can see from the proof above, there exists a consistent layout conventions in dealing with matrix calculus, the same way that there exist a layout convention in calculus under the real line. The key to understand matrix derivatives, as with derivatives for functions $f:\mathbb{R}\to\mathbb{R}$ is practice. Take a look at the Matrix Cookbook for further reference.


Exact sequences of Modules

Question: For $A$-modules and homomorphisms
$0\to M′\stackrel{u}{\to}M\stackrel{v}{\to}M′′\to 0$
is exact iff for all A-modules N, the sequence
$0 \to Hom(M′′,N)\stackrel{\bar{v}}{\to} Hom(M,N)\stackrel{\bar{u}}{\to} Hom(M′,N)$
is exact.
How $\bar{u}$ and $\bar{v}$ are defined ?
How do I prove that the sequence is exact at Hom(M′′,N) and Hom(M′,N)?
thanks for any help or hints
Comment: $\bar v$ maps a $\phi:M''\to N$ to the composition $v\cdot \phi:M\to N$.
Comment: The claim is wrong. Correct and a trivial consequence of the universal properties is the following: $M' \to M \to M'' \to 0$ is exact iff for all $N$ we have that $0 \to \hom(M'',N) \to \hom(M,N) \to \hom(M',N)$ is exact.
Comment: thats wrong it should map it to  ϕ . v
Comment: @navigetor23: Unless I am mistaken, this is asking about the sequence at a different point than the other ($\mathrm{Hom}(M,N)$ instead of $\mathrm{Hom}(M'',N)$ and $\mathrm{Hom}(M',N)$).
Answer: Writing composition from left to right, $\bar v$ maps $\phi\mapsto v\cdot \phi$, similarly for $\bar u$.
For exactness, you need to show that $\ker\bar u={\rm im\,}\bar v$ and that $\bar v$ is injective.
For example, the injectivity follows because $v$ is epimorphism, so
$v\cdot\phi= 0$ implies $\phi=0$.
Comment: Thanks for the help, got it
Comment: how to prove exactness at Hom(M,N) ?

Exact sequences of Modules


Inserting information in database with PHP

Question: I'm a beginner and I am trying to learn PHP and SQL. I've written the code below so I can insert data into my database but I do not understand why it is not working. It loads and everything but when I click on the "Sign Up" button, it does nothing. Can someone help me figure it out?
<?php include 'config.php'; ?>

<?php
        if(isset($_POST['submit'])) {
        $username = $_POST['username'];
        $password = $_POST['password'];

            $query = "INSERT INTO users1(username,password) VALUES ('$username','$password')";
            $result = mysqli_query($con,$query) or die ("problem inserting new product into database");
        }
    ?>

<!DOCTYPE html>

<title>Sign Up</title>

Sign Up

Enter your data to register

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">

    Username<input type="text" name="username" placeholder="Enter your username" autofocus required">

     Password: <input type="password" name="pass" class="info" placeholder="Enter your Password" required >

    <button class="lbutton" type="submit" value="Submit">Sign Up</button>

Already registered? Login

Comment: Your button needs `name="submit"`
Comment: If you're just starting out, **now** would be a good time to look up [how to prevent SQL injection in PHP](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) and [password hashing](http://php.net/manual/en/function.password-hash.php) before bad habits set in ;)
Comment: I'll definitely look it up
Comment: On a side note, your labels need a `for` attribute
Answer: First of all
If form redirects you to the same page you can leave action parameter empty: action=""
Secondly
You check if variable $_POST['submit'] exists but none of your elements in form has name submit so it will never exist. Html form sends variables to array $_POST using names of fields as keys. If name is not given it is a number.
What to do
Add name="submit" to your submit button and that should work.
Change name="pass" to name="password" in your password input or change in php $_POST['password'] to $_POST['pass'].
Also close your form (</form>). Modern browsers close it automaticly but it is still incorrect.
Additional hints
Accessing $_POST directly is not a good practice. Here is a better solution: $username = filter_input(INPUT_POST, 'username') instead of $username = $_POST['username']
It is also a good idea to use filter_var function when inserting variables to SQL query.
Example: $username = filter_var(FILTER_SANITIZE_STRING, $username)
Answer: Try to close the form.
  <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"
  method="POST">

 Username<input type="text" name="username"
 placeholder="Enter your username" autofocus required">

 Password: <input type="password"
name="pass" class="info" placeholder="Enter your Password" required >

 <button class="lbutton" type="submit" value="Submit">Sign Up</button>

Keni nje adrese? Futu

</form>

Comment: It can't. There is no field with `name='submit'`
Answer: If you are  doing this way, the submit button should have a name, which will include it in the post array.
<button class="lbutton" type="submit" name="submit" value="Submit">Sign Up</button>

On th form submit, post array is created for all the elements inside the form having a valid name attribute.
You also need to close <form></form>


Espaço e cor entre ViewCell num ListView

Question: Gostaria de ajuda pois não estou conseguindo deixar da maneira que espero, há espaço a mais entre as cores. O cinza é o fundo que coloquei e o amarelo está sendo preenchido pelo Binding. A linha vermelha é um BoxView que quero utilizar pra fazer a repartição entre eles. O cinza entre eles não deve aparecer.

Segue o código:

    <ListView x:Name="lstLeilao"
              ItemTapped="OnTapLance"
              HasUnevenRows="True"
              BackgroundColor="LightGray">
        <ListView.ItemTemplate>

            <DataTemplate>
                <ViewCell>
                    <StackLayout>
                        <StackLayout BackgroundColor="{Binding COR}"
                                     Margin="0">

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>

                            <StackLayout Orientation="Horizontal">

                            </StackLayout>
                        </StackLayout>

                        <StackLayout>
                            <BoxView BackgroundColor="Red"
                                     HeightRequest="1"
                                     Margin="0"/>
                        </StackLayout>

                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

</StackLayout>

Comment: Coloque  `SeparatorVisibility="None"` abaixo do `HasUnevenRows="true"` na sua listview e veja se resolve
Comment: Que pena, não foi, mas agradeço.
Answer: O StackLayout tem um Spacing padrão de 6 dip. É justamente esse espaçamento entre os itens que está aparecendo cinza na sua tela: é o espaço entre os seu stack que contém os dados paresentados e o outro stack que contém o BoxView.
Uma das formas de resolver é removendo o Spacing do StackLayout onde os itens em questão estão apresentando o 'problema':
<ViewCell>
    <StackLayout Spacing="0">
        <StackLayout BackgroundColor="{Binding COR}"
                     Margin="0">

        </StackLayout>

        <StackLayout>
            <BoxView BackgroundColor="Red"
                     HeightRequest="1"
                     Margin="0"/>
        </StackLayout>

    </StackLayout>
</ViewCell>

Dica sobre o seu layout:
Você está usando vários StackLayouts aninhados, algumas vezes desnecessáriamente como é o caso do BoxView. Quanto mais elementos você inclui (pricipalmente falando de ListView, que vai renderizar isso várias vezes), maior será o efeito sobre a performance do aplicativo.
Sugiro que você veja o vídeo e leia essas dicas sobre performance com Xamarin.Forms, me ajudou bastante e acredito que possa te ajudar também.
Comment: @DeividSouza na própria `ViewCell` você também tem 2 `StackLayouts`. o que tem a cor de fundo já poderia zer a raiz, e o `BoxView` ficaria dentro dele (você não teria o problema do `Spacing`). Esse link que eu mencionei [está disponível em português também](https://docs.microsoft.com/pt-br/xamarin/xamarin-forms/deploy-test/performance), e no vídeo você pode configurar para exibir legendas com auto-tradução para português. A tradução não é das melhores, mas já lhe ofecere algum conhecimento mais acessível.
Comment: Encontrei um texto explicando exatamente referente à performance do Xamarin em português, muito bom: http://www.macoratti.net/17/01/xamforms_dicas1.htm
Comment: Caramba, que aula de resposta. Deu certo. Você acredita que apenas no BoxView errei em colocar StackLayout? Poxa, adoraria demais assistir ao vídeo, mas não sei praticamente nada do inglês, que vontade de chorar ahaha
Comment: Ótimo. Estou lendo por essa auto-tradução mesmo ao menos pra quebrar um galho. Onde você postará o conteúdo que está traduzindo?
Comment: Pode me passar como encontro seu canal? Queria acompanhar. No texto que me passou aprendi muito mesmo quanto a layout, agradeço.


How does ssh port forwarding work exactly

Question: I have the following setup:
One machine with sshd running (local) behind a router (router) and a second host (remote) tries to access local through the internet and the router via ssh.
Therefor: Port forwarding router:22 -> local:22 (and router as gateway for local) . Works perfectly fine.
If I try to create a ssh tunnel from remote to local as follows:
ssh -L 1234:R:12345 user@R

this will only work if I also redirect router:1234 -> local:1234.
My understanding was, that ssh will tunnel all the traffic trough its connection on port 22. But it seems, that this is not the case. Am I doing something wrong? Is there any possibility to tunnel all the traffic through a single connection?
Comment: There are multiple good answers below, I also wrote a blog post a while back covering this, so you may check it out.  Oh, it was 11 years ago! https://dmitry.khlebnikov.net/2010/12/10/ssh-port-forwarding-intermediate/
Answer: Your question was a little unclear to me, so I'm going to specify what I assumed and then try and help you with your problem. You are at the computer 'remote' which is SSH'ing to 'local' and this part works fine. If this is the case we no longer need to worry about router.
Continuing my assumptions, 'local' has a service running on it on port 12345 that you would like to access from 'remote' without opening additional ports on your router. What you would want to do is use the following command from 'remote':
ssh -L 1234:localhost:12345 user@router's_ip

To connect to the service you would then access it through localhost:1234.
The way the port forwarding syntax works is: {local_port}:{proxy_dest}:{proxy_port}
local_port is the port that will open on the client machine you are connecting from, to access it you would use localhost:local_port
proxy_dest is the host you would like to connect to from the perspective of the server you are SSH'ing into
proxy_port is the port on the remote system that you would like to connect to.
Answer: An answer to the second part of your question.  You can use the dynamic proxy feature of later versions of SSH to forward all traffic with a couple of caveats.
The applications you are using on your client must support SOCKS proxies.
The OpenSSH only supports a SOCKS4 style proxy.
The syntax used is:
ssh -D user@remotehost
Answer: I think that you're wanting:

To ssh from remote to local
and forward port 1234 on remote to port 12345 on local

You seem to be indicating that local sits behind NAT happening on router - this would be why you need to set up the portforward so that router:22 forwards internally to local:22
If I've understood this correctly, the commandline you want to use on remote is actually:
ssh -L 1234:local:12345 user@router
The key here is that although this is a local portforward (-L == local) the resolution of the hostname (ie, local in this case - the second parameter in the 1234:local:12345 list) happens on the destination machine - which in this case is local.
In your example, you had 1234:router:12345 - which means that traffic goes down the ssh tunnel from remote to local; then is routed from local to router - and as you've said, this requires yet another portforward to get the traffic back to local.

An alternative would be to ssh from local to remote, using ssh -R 1234:local:12345. This wouldn't need the portforward on router, but you'd still have 1234 on remote forward to 12345 on local. The obvious downside to this is that you can't initiate this connection from remote, as you have no way of reaching local.


What are some specific reasons NOT to share a users database table between sites?

Question: I'm building a site for a client, and surprise! Turns out they're using a shared users table between multiple Drupal 7 sites (completely different code bases, different config, etc). I'm only supposed to be working on the one new site, but obviously this new wrinkle has me considering how these other sites will mess me up.
In my heart of hearts I know this is a terrible, very bad, no good idea. I don't want to launch a new site with this timebomb lurking under the hood. But I can only think of one scenario where things go hideously wrong. Deleting users could lead to major complications.
Other than that, what are specific scenarios that you have faced, or that you could think of arising when sharing a users table between Drupal sites?
Comment: The "delete problem" would work something like this: (1) Create users Alice (uid 3) and Bob (uid 4). (2) add "favorite color" field to site A (3) set "Auburn" to Alice's favorite color and "Brown" for Bob's. (4) Delete Alice and Bob from site B (Problem:) Favorite color values persist in field tables for Site A. When users Chuck and Dave get created, and uids 3 and 4 get re-used, Chuck and Dave will inherit Alice and Bob's favorite colors.
Answer: Almost any problem you see will be similar to content cache problems on a Drupal site.
The database represents your site's canonical state. Sharing a user table between 2 different sites means canonical user data reads/write can become invalid without each site knowing it, since they aren't coordinating their actions.
For example, Site A is doing a bulk operation (e.g. add Role X to all selected users) on users. It loads all users from a DB query into memory, changes a property on each user object, then executes a save to the DB. Meanwhile, Site B has a user who wants to update his email. He visits his user page, updates his email only to see it change back a few minutes later because Site A, still working through its bulk operation, has an old version of the user account and saved it after he updated his email.
Depending on the size of your site, just like with content caching, this invalid state problem might never show up. If Site A & B represent 2 different sub-sections (e.g. a blog site & commerce site) with users seldom using both, the scenario where the user state becoming invalid might never happen. But as your site grows (i.e. the number of user DB transactions) this invalid state problem will likely show up eventually.
Comment: This is a great example that I didn't think of. I'm not looking for an enumeration of *all possible problems*, but would like to hear this sort of theoretical problem or specific problems that people have experienced. Thank you.


Gaussian prior favors values closest to zero?

Question: I am reading an article on Bayesian Logistic Regression, where they're using Logistic Regression, imposing a Gaussian prior (with mean = 0) on its parameters. They state that a Gaussian prior favors the values of the parameters to be near zero, but not exactly zero.
My question: if the mean is zero, how could it favor the parameters not being exactly zero?
The article I'm referring to is this (Section 3).
Thanks.
Answer: It appears to me that what is meant is simply that although the probability that the parameter is near $0$ is high, the probability that it is exactly $0$ is $0$.
Comment: Thanks @MichaelHardy, but - why? They're talking about estimating parameters, I think that's considered to be a discrete distribution.
Comment: @Cheshie : A Gaussian distribution is _not_ a discrete distribution, regardless of whether it's used in interval estimation of parameters or for any other purpose and regardless of whether it's a prior or posterior distribution.
Comment: Oops... I guess you're right. Thanks so much! :)


Session time out very short in hosting environment? Test for the loss of sessions?

Question: My sessions timeouts are very short on my hosting environment, some times even 2 seconds and they timeout.
The sessions are reset if the user continues to use the website, unless the session = null and the count is 0.
The sessions should time out after 20min and then redirect the user to the log in page
The code for this is below:
protected override void OnInit(EventArgs e)
{
    if (this.Session != null && this.Session.Count > 0)
    {
        string email = (string)this.Session["Email"];
        int practiceId = (int)this.Session["PracticeId"];
        int practitionerId = (int)this.Session["PractitionerId"];

        this.ClientScript.RegisterHiddenField("loggedInUserName", email);
        this.ClientScript.RegisterHiddenField("practiceId", practiceId.ToString());
        this.ClientScript.RegisterHiddenField("practitionerId", practitionerId.ToString());
    }
    else
    {
        this.Session.Abandon();
        Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", ""));
        Response.Redirect("~/Default.aspx");
    }

    base.OnInit(e);
}

Does anyone know why my session timeout could be so short?
When using my site sometime i can move around for 2-5 minutes with no timeout and other time 10s in i get a time out. What could cause session being lost, are they any ways to avoid or test for the loss of sessions?
Thanks in advance.
Answer: I assume you are overriding the init function for the page, but potentially abandoning the session on every page load could cause more issues than it solves.  I would check for the existence of the session inside the master page:
protected void Page_Init(object sender, EventArgs e)
{
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    {
        // user is not logged in
        string ReturnUrl = HttpContext.Current.Request.Url.PathAndQuery;
        string RedirectUrl = "/Login.aspx";
        if (!String.IsNullOrEmpty(ReturnUrl))
        {
            RedirectUrl += "?ReturnUrl=" + Server.UrlEncode(ReturnUrl);
        }
        Response.Redirect(RedirectUrl);
    }
}

If this is in the master page it will check on each request (made to an aspx page that inherits from the master) that will redirect the user to the login page.
If your app is sharing an application pool, you might be sharing the cookie id with another application:
<authentication mode="Forms">
    <forms loginUrl="~/Login.aspx" timeout="60" name="MY_COOOKIE_NAME" slidingExpiration="true" />
</authentication>
<sessionState timeout="60" />

The MY COOKIE NAME will identify the cookies your app uses, other apps might have the default cookie name, so your sessions although apparently authenticated don't belongto the app as they are getting overwritten by a different app. The sliding expiration means that your session time will be extended everytime you visit a page.
Also, check that the machineKey config element is present, this made my sessions more stable:
<machineKey
validationKey="random_validation_key"
decryptionKey="random_decryption_key"
validation="SHA1" decryption="AES" />


Iterated Function System Definition

Question: I am attempting to learn more about set-theory, specifically in application to the iterated function system (IFS). Would you please explain the following set formula in English:
$\{f_i : X \rightarrow X | i = 1, 2, ..., N\}, N \in \mathbb{N}$
I understand $X$ is a set, but to the right of the arrow, does this mean it implies a new set $X$ is dependent on $i$ (how does this work?)? I am also confused about $f_i$ - how is the function dependent on $i$?
If you could recommend some reading material, please do.
Thanks.
Comment: The notation $f_i:X\to X$ simply means that $f_i$ is a function defined on $X$ and taking values on (the same) $X$. (There is no "new" $X$.) That we have $f_i$ for $1,\dots,N$ simply means that we have $N$ functions. The set $\{f_i:X\to X\mid i=1,2,\dots,N\}$ is therefore a set consisting of $N$ functions, each of them from $X$ to itself. For example, say $X=\mathbb R$, $N=2$, $f_1:\mathbb R\to\mathbb R$ is the function $\displaystyle f_1(x)=\frac x3$, and $f_2:\mathbb R\to\mathbb R$ is the function $\displaystyle f(x)=\frac x3+\frac23$. (This system is related to the Cantor set.)
Comment: Now, note that there are additional requirements, as mentioned at the link: $X$ is not just an arbitrary set, but rather a complete metric space, and each $f_i$ must be a contraction.
Comment: By the way, this has nothing to do with set theory. It is a good starting point for the theory of fractals, though.
Comment: Would the third function be: $f_3(x) = \frac{x}{3} + \left( \frac{2}{3} + \frac{\frac{x}{3} + \frac{2}{3}}{3}\right)$?
Comment: @Biff Not necessarily. The *only* requirement for $f_3$ is that it be a function mapping $X$ to itself.
Comment: @Dan Christensen Understood. However, if the set were to fulfill the requirements of the Cantor set, would that be $f_3(x)$?
Comment: There is no $f_3$ in my example. I even said that $N=2$.
Answer: $\{f_i : X \rightarrow X | i = 1, 2, ..., N\}, N \in \mathbb{N}$ is just a set of $N$ functions, namely the functions $f_1, f_2, ... , f_N$. And each one of them maps $X$ to itself.
Comment: The only implicit assumption is that $f(x)$ is somehow *defined* and that, as you said, each one maps $X$ to itself?
Comment: @Biff There is no $f(x)$ here. The subscripts are part of the names of each of the $N$ functions. Instead, you would have $f_1(x)$ or $f_2(x)$, etc.
Comment: You would have to provide a starting function though, correct? In other words, it would always be $f_1(x)$.
Comment: I wouldn't call it a "starting function." $f_2$ isn't somehow dependent on or determined by $f_1$. We are not talking about recursively defined functions here.
Comment: Oh, I see. If it were to be a fractal, however, would that be the case?
Comment: Don't get confused. This has nothing to do with fractals.
Comment: I do realize that the functions could be completely arbitrary, but I was interested in distinguishing how IFSs are used with fractals.
Comment: @Biff The connection with fractals is probably too subtle for you to fully understand right now: If $X$ is a complete metric space, and all the $f_i$ are contractions, we can define a map $F$ on the space $K(X)$ of compact subsets of $X$, endowed with the Hausdorff metric, by setting $F(C)=\bigcup_{i\le N}f_i(C)$ for each nonempty compact set $C\subseteq X$. It happens that $F:K(X)\to K(X)$ is again a contraction, so by a theorem of Banach it has a unique fixed point, which is a compact set (a subset of $X$). This set is what we would call the fractal associated with the IFS you began with.

Iterated Function System Definition


Tomcat 7 start failed with srpingboot

Question: I have a spring-boot app (Tomcat 7, Jdk 1.8, maven) that I try to run (It is not a embedded tomcat) and I got several issues like :
 Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.AbstractMethodError: org.springframework.boot.context.config.ConfigFileApplicationListener.supportsSourceType(Ljava/lang/Class;)Z
    at org.springframework.context.event.GenericApplicationListenerAdapter.supportsSourceType(GenericApplicationListenerAdapter.java:79)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.supportsEvent(AbstractApplicationEventMulticaster.java:289)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.retrieveApplicationListeners(AbstractApplicationEventMulticaster.java:221)
    at org.springframework.context.event.AbstractApplicationEventMulticaster.getApplicationListeners(AbstractApplicationEventMulticaster.java:192)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:128)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:122)
    at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:75)
    at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
    at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:347)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:306)
    at ep.OWebApplicationInitializer.main(OWebApplicationInitializer.java:14)

What's wrong ?
My class main :
@SpringBootApplication
public class OWebApplicationInitializer extends SpringBootServletInitializer  {
    public static void main(String[] args) {
        new SpringApplication(OWebApplicationInitializer.class).run(args);
    }

}

And my pom like that :
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

Someone have idea with this issue ?
Comment: `AbstractMethodError` usually means you are executing (in the server) against different library version than the one you used when compiling.  In the library used for compiling the method was concrete, while in the server's library it is abstract.
Comment: Why are you excluding the tomcat dependency? Did you add your own?
Comment: Yes I add mine .. Tomcat 7 (mandatory for my projeect) .. but I use the last version of springboot ..may be it is the cause of issue ?
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
Answer: You have mismatched versions of your dependencies on the classpath.
<parent>
<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.0.RELEASE</version>
        <relativePath/>
    </parent>

And use Tomcat 8.
Comment: I have a pom parent where I defined it .. ´´
org.springframework.boot
spring-boot-starter-parent
2.1.4.RELEASE
  .. I use for the moment tomcat  7
Comment: Please refer the System requirements :
https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/html/getting-started-system-requirements.html

https://docs.spring.io/spring-boot/docs/1.5.1.RELEASE/reference/html/getting-started-system-requirements.html

Check Tomcat Requirements for Servlet versions :
http://tomcat.apache.org/whichversion.html
Comment: Thanks so much ... I use springboot 1.4.6 and my tomcat run now ... thxxxxx
Answer: You can override SpringBootServletInitializer's configure:
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    return builder.sources(OWebApplicationInitializer.class);
}

Comment: Why would he do that? How does your answer solve the problem?

Tomcat 7 start failed with srpingboot


Minimal polynomial $\mu_A(x)$

Question: I have a matrix $A=\begin{bmatrix}1&3&0\\1&-1&0\\0&-2&1\end{bmatrix}$.  The characteristic polynomial, $\chi_A(x)=0=\det(\lambda{I}-A)$ so
$$\det{(\lambda{I}-A)}=(\lambda-1)[(\lambda^2-1)-3]=(\lambda-1)(\lambda-2)(\lambda+2)=\lambda^3-\lambda^2-4\lambda+4$$
So the minimal polynomial, $\mu_A(x)$ must be a product of the linear factors of $\chi_A(x)$, so my candidates are
$$x-1,x-2,x+2,x^2+x-2,x^2-3x+2,x^2-4, \chi_A(x)$$
Calculating, $A^2=\begin{bmatrix}4&0&0\\0&4&0\\-2&0&1\end{bmatrix}$.
Clearly, none of the linear factors can be $\mu_A(x)$.  Since $A^2\neq 4I$, it can't be $x^2-4.$  That leaves $\chi_A(x)$, or the remaining two quadratics.  But by my calculation, neither work.  That leaves $\chi_A(x)=\mu_A(x)$.  Is there a way to discover this fact without just running through all the polynomial operators?  Or did I make a mistake and is one of the quadratics actually $\mu_A(x)$?
Comment: If $\lambda$ is an eigenvalue of $A$, what about $\mu_A(\lambda)$?
Answer: Hint: In this case the characteristic polynomial consists only of distinct linear factors, AND EVERY linear factor of the characteristic polynomial must be a factor of the minimum polynomial (ah, gave it away)
Comment: For $n$ *distinct eigenvalues*, yes. But not in general.
Comment: It has been a while since I studied minimal polynomials and operators.  So because both conditions are met, it is always t he case that characteristic = minimal...
Comment: Well, the characteristic polynomial is always degree $n$, so if it only consists of (distinct) linear factors, then we will naturally have $n$ distinct eigenvalues.
Comment: okay - improved the wording...
Answer: Here's a quicker way:  use the fact that $A$ has $3$ distinct eigenvalues.  Since $\mu_A(x)$ is a polynomial such that $\mu_A(A) = 0$, we must have
$\mu_A(\lambda) = 0$ for any eigenvalue $\lambda$ of $A$; this follows from the fact that $Av = \lambda v$ with $v \ne 0$ implies that $q(A)v = q(\lambda) v$ for any polynomial $q(x)$.  Since there are three distinct eigenvalues, it follows that $\deg \mu_A(x) \ge 3$.  But then we must have $\mu_A(x) = \chi_A(x)$, since $\chi_A(A) = 0$ and $\deg \chi_A(x) = 3$.
Note:  I think it is worth pointing out that this result generalizes to arbitrary dimension $n$ and also holds over any field, at least in the event that the number of distinct eigenvalues of $A$ is $n$.  End of Note.
Hope this helps.  Cheerio,
and as always,
Fiat Lux!!!

Minimal polynomial $\mu_A(x)$


Finding two sequences from certain conditions.

Question: $t_n=(n+4)t_{n-1}-4nt_{n-2}+(4n-8)t_{n-3}$ holds for $n\geq 3$. Certain terms starting from $t_0$ are $2,3,6,14,40,...$ (three more terms are given I didn't write). Find $a_n,b_n$ such that they are well known sequences such that $t_n=a_n+b_n$.$$\text{Attempt}$$ I couldn't do anything as the only thing given is a recursion. Tried some basic manipulation with it  but it didn't help. When I saw the solution it stated that some $\text{guess work }$ reveals the sequences are $n!,2^n$. I know certain terms of sequences like $n,n^2,n^3,n^2+n,n!,2^n$. Pascals triangle (all independently). There are many combination of those.I personally can't tell the start of the sequence $n!+2^n$ without some arithmetic. So wanted to know if there was an elegant way of solving it dodging this guess work.
Comment: what are $a_n,b_n$?  Are they supposed to be related to the recurrence relation for $t_n$ somehow?
Comment: I have edited the question
Answer: The obvious first guess is an $n!$ somewhere, because the coefficients on the RHS has an extra $n$ (i.e., $\underbrace{n}_{t_{n-1}}-\underbrace{4n}_{t_{n-2}}+\underbrace{4n}_{t_{n-3}}=n$.  This is a feature of all such polynomial-coefficient equations as long as there is the largest nontrivial degree appears with $t_{n-1}$ and isn't cancelled by other coefficients that a solution has to grow like $\prod p(n)$).  Then a naive subtraction yields the guess $t_n=n!+2^n$.
And you can prove this formula satisfies the recurrence relation:
\begin{align*}\require{color}
RHS & = (n+4)[(n-1)!+2^{n-1}] - 4n[(n-2)!+2^{n-2}] + (4n-8)[(n-3)!+2^{n-3}]\\
&=n!+{\color{red}4(n-1)!}+({\color{blue}n}+4)2^{n-1} - {\color{red}4n(n-2)!}-{\color{blue}n2^n} + {\color{red}4(n-2)!}+({\color{blue}n}-2)2^{n-1}\\
&=n!+2^n=LHS
\end{align*}


Problema na busca utilizando o queryset do Django na hora de editar

Question: Fico grado pela ajuda, pois não estou conseguindo realizar essa busca,
mesmo realizando a busca, me retorna o id certo (id_setor e id_empresa) porém o Django não reconhece ou estou fazendo algo errado.
Erro "The QuerySet value for an exact lookup must be limited to one result using slicing"
Views
@login_required(login_url='/login/')
def ed_ramal(request):
    id_ramal = request.GET.get('id')
    id_setor = Ramais.objects.filter(id=id_ramal).values('setor_ramais')
    id_empresa = Ramais.objects.filter(id=id_ramal).values('empresa_ramais')

    if id_ramal:
        ed_ramal = Ramais.objects.filter(id=id_ramal).values('ramal')
        i_resp = Ramais.objects.filter(id=id_ramal).values('nome_resp')
        i_mail = Ramais.objects.filter(id=id_ramal).values('email')
        setor = Setores.objects.filter(id=id_setor[0]['setor_ramais'])
        empresa= Empresas.objects.filter(id=id_empresa[0]['empresa_ramais'])
        dados = {'ramal': ed_ramal, 'responsavel': i_resp, 'email': i_mail, 'setores': setor, 'empresas': empresa}
    else:
        empresa = Empresas.objects.all()
        setor = Setores.objects.all()
        dados = {'empresas': empresa, 'setores': setor}
    return render(request, 'ramal.html', dados)

Models
    class Ramais(models.Model):
        ramal = models.CharField(max_length=4, verbose_name='Ramal')
        nome_resp = models.CharField(max_length=30, verbose_name='Responsavél')
        email = models.EmailField(max_length=60)
        setor_ramais = models.ForeignKey(Setores, on_delete= models.DO_NOTHING, verbose_name='Setor')
        empresa_ramais = models.ForeignKey(Empresas,on_delete= models.DO_NOTHING, verbose_name='Empresa')
        data_criacao = models.DateTimeField(auto_now=True)

        class Meta:
            db_table = 'ramais'

        def __str__(self):
            return self.ramal + str(self.setor_ramais)+ str(self.empresa_ramais)

Código Html antes de editar:
{% extends "parciais/base.html" %}
{% block content %}

           <form class="form-inline" method="GET">
                <input class="form-control mr-sm-2 "type="text" name="search" id="buscar">
                <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Consulta</button>
           </form>

LISTA DE RAMAIS

                        RAMAL
                        RESPONSAVÉL
                        SETOR
                        EMPRESA
                        {% if request.user.is_authenticated %}
                            EDIÇÃO

                                <button type="button" class="btn btn-light">ADICIONAR</button>

                        {% endif %}

                           {% for i in ramais %}

                                {{i.ramal}}
                                {{ i.nome_resp | upper }}
                                {{ i.setor_ramais | upper }}
                                {{ i.empresa_ramais }}
                                {% if request.user.is_authenticated %}

                                         <button type="button" class="btn btn-warning">EDITAR</button>
                                        <!/a>

                                         <button type="button" class="btn btn-danger">EXCLUIR</button>

                                {% endif %}

                           {% endfor %}

                      {% for pagina in ramais.paginator.page_range %}
                        {% if ramais.number == pagina %}

{{ pagina }}

                        {% else %}

{{ pagina }}

                        {% endif %}
                      {% endfor %}

                <button type="button" onclick="window.print()" class="btn btn-outline-secondary">Imprimir</button>

{% endblock %}

Codigo HTML de edição / adicionar
{% extends "parciais/base.html" %}

{% block content %}
{% load static %}
    <link rel= "stylesheet" type="text/css" href= "{% static '/bootstrap/css/bootstrap.min.css' %}" >
    <link rel= "stylesheet" type="text/css" href= "{% static '/style.css' %}" >

RAMAL

        <form action="submit" method="POST">{% csrf_token %}
         <input type="number" name="id_ramal" value="{{ i.id }}">

                  Ramal:
                  <input type="number" name="ramal" class="form-control" value="{{ i.ramal  }}"  >

                  Responsável:
                  <input type="text" name="responsavel"  class="form-control" value="{{ i.nome_resp }}" >

                    Email:
                    <input type="email" name="email"  class="form-control" value="{{ i.emal }}">

                      Setor:
                      <select id="inputState" name="setor" class="form-control">
                        {% for s in setores %}
                            <option  value="{{ s.id }}" name="pk_setor">{{ s.setor }}</option>
                        {% endfor %}
                      </select>

                            <button type="button" class="btn btn-info">ADICIONAR</button>

                      Empresa:
                      <select id="inputState01" name="empresa"  class="form-control">
                        {% for e in empresas %}
                            <option  value="{{ e.id }}" name="pk_empresa">{{ e.nome_emp }}</option>
                        {% endfor %}
                      </select>

            <button type="submit" class="btn btn-success">SALVAR</button>

                <button type="button" class="btn btn-danger">CANCELAR</button>

        </form>

{% endblock %}

Código completo no meu GitHub: https://github.com/cristianpaes/RAMAIS
Answer: com o filter obténs um queryset, logo o resultado não é id, para id_sector e id_empresa, utiliza algo assim:
@login_required(login_url='/login/')
    def ed_ramal(request):

        id_ramal = request.GET.get('id')
        id_setor = Ramais.objects.filter(id=id_ramal).values('setor_ramais')
        id_empresa = Ramais.objects.filter(id=id_ramal).values('empresa_ramais')

        if id_ramal:
            ramal = Ramais.objects.filter(id=id_ramal)
            setor = Setores.objects.filter(id=id_setor[0]['setor_ramais'])
            empresa= Empresas.objects.filter(id=id_empresa[0]['empresa_ramais'])
            dados = {'empresas': empresa, 'setores': setor, 'ramal':ramal}

        else:
            empresa = Empresas.objects.all()
            setor = Setores.objects.all()
            dados = {'empresas': empresa, 'setores': setor}
        return render(request, 'ramal.html', dados)

Comment: Fiz a alteração que informou, porém ainda continua dando erro de tipo. TypeError: Field 'id' expected a number but got {'setor_ramais': 1}.
Comment: Fix a correção, valida agora.
Comment: Agora deu outro erro: 'Setores' object is not iterable.
Comment: Agora deduzo que tenhas outro problema no html ao iterar os 'setores', estas a ver aquele HTML, **que não partilhaste**. Não podem esperar ajuda sem partilham aqui o código.
Comment: Coloquei o HTML onde pego o ID e tem meu github, para verificar todos os html e codigos completos. Só não consigo resolver isso.
Comment: Corrigi no código que partilhei, no teu HTML não tem problema, mas sim na função **ed_ramal**, como não tinha acesso a esse código não podia perceber como apresentas no template. Qual aqui o problema, não podes passar para um for loop no template uma e uma só instancia do Objeto Setores ou Empresas, (este último iria dar erro a serguir após corrigir o de Setores), é o que acontece ao fazer *.objects.get(), tens de utilizar o *.filter(), desta forma o ORM de Django retorna um QuerySet desse objeto e iterável, mesmo sendo só um, não sei se é este o objetivo com o if id_ramal:. ter um dropdown.
Comment: Muito obrigado. Funcionou e era coisa boba. Estou aprendendo e acontece isso.
Comment: Pode me ajudar, a trazer os valores do Ramal, responsável e email. E teria como deixar interativo o setores e Empresa? a minha ideia seria trocar caso a pessoa seja transferida.
Comment: Penso que deverias fechar esta questão, e abrir nova, a tua dúvida aqui ficou resolvida. Coloca o código e detalha muito bem o problema, "a minha ideia seria trocar caso a pessoa seja transferida", só isto não chega. Tenta ser o mais objetivo possível.


Counting number of unique combinations

Question: I came across a programming challenge recently and I'm wondering if there's a closed-form solution to this.
There is a strip with squares of unit length each. The strip's total length is N (i.e. there are N squares). You have M painters of length K units each. You can paint over the squares with these painters however many times you want. How many unique combinations can you make?
Ex. N = 3, M = 2, K = 2 gives 6 unique combinations
(000 , 111, 011, 100, 001, 110)
I currently have a brute-force algorithm to solve this, but I'm sure there has to be a more elegant solution.
I am not a student and this is not a homework question. I just do these for fun.
Answer: The possible combinations are precisely the ones containing $K$ consecutive squares of the same color.
These are the only ones possible, because the last time you paint, you create such a strip. To see that all of them are possible, we can use the following algorithm.
Suppose that we have a sequence of colors $a_1, a_2, \dots, a_N$ with $a_{i+1} = a_{i+2} = \dots = a_{i+K}$ for some $i$. Then:

First, make sure that colors $a_1, a_2, \dots, a_i$ are correct, in that order. To do this, color the interval $[1,K]$ with color $a_1$, then the interval $[2,K+1]$ with color $a_2$, and so on, until you color the interval $[i,i+K-1]$ with color $a_i$.
Second, make sure that colors $a_N, a_{N-1}, \dots, a_{i+K+1}$ are correct, in that order. To do this, color the interval $[N-K+1,N]$ with color $a_N$, then the interval $[N-K,N-1]$ with color $a_{N-1}$, and so on, until you color the interval $[i+1,i+K+1]$ with color $a_{i+K+1}$.
Finally, color the interval $[i+1,I+K]$ with the color that all $K$ of these squares are supposed to have.

This gives us a characterization of the possible combinations; counting them is a bit harder.
There is a recursive formula for impossible combinations. Fix $M,K$ and let $c_N$ be the number of impossible combinations of length $N$. (So, the number we actually want - the number of possible combinations - is $M^N - c_N$.) For $N=1,2,\dots,K-1$, we have $c_N = M^N$. For $N \ge K$, we have
$$
   c_N = (M-1) \left(c_{N-1} + c_{N-2} + \dots + c_{N-K+1}\right)
$$
by breaking it up into cases: some number between $1$ and $K-1$ of the rightmost squares have the same color (but no more than that many), and they have one of the $M-1$ possible colors that are not equal to the color that comes before them.
This generally doesn't have a nice closed form. Some special cases do:

When $K=2$, we have $c_1 = M$ and $c_N = (M-1) c_{N-1}$ when $N \ge 2$, so $c_N = M(M-1)^{N-1}$.
When $M=2$ and $K=3$, we have $c_1 = 2$, $c_2 = 4$ and $c_N = c_{N-1} + c_{N-2}$ when $N \ge 3$, which is the Fibonacci number recurrence. Here, $c_N = 2F_{N+1}$, where we take the Fibonacci numbers to begin $F_1 = 1, F_2 =1, F_3 = 2, \dots$.
Comment: +1 nice answer but i think there is a minor mistake: Basically you are saying if $N < K$ then all $M^N$ patterns are impossible, right?  Then for $M=2, K=3$ we should have $c_2 = 2^2 = 4$.  So the $c_N$ are still twice the Fibonnaci numbers but maybe now the $(N+1)$th one?  Depends on how your start the Fibs.  :)
Comment: Yeah, an upper bound on the number of impossible configurations is $M^N (1 - \frac1{M^{K-1}})^{N/K}$ (just by looking at $N/K$ disjoint blocks of length $K$) which is $(M-\epsilon)^N$.
Comment: Wow, interesting! Thank you. I was really hoping that there would be a more elegant or a closed-form expression because my brute-force approach for doing this is kind of slow and messy.
Comment: @antkam Thanks for spotting this! Fixed :)
Comment: For $M=2$ and general $K$, does the recurrence have a general solution? If $K=2$ then $c_N$ grows as $\phi^N$, and for general $K$ it would seem $c_N$ grows as $\lambda_K^N$ right? But my gut feel also tells me $\lambda_K \to 2$ for large $K$. So out of $2^N$ patterns something like $(2-\epsilon)^N$ are impossible...?
Comment: For general $K$, we're looking at generalizations like the Tribonacci numbers and so forth (which I think is what you mean?). Possibly with different initial conditions, but the largest root of the characteristic polynomial will still determine the growth.
Comment: ah, thanks for the name!  Tribonacci.  and then Tetranacci, etc. (according to wiki & OEIS).  thanks!  my other observation was simply the largest root $\lambda_K \to 2$ for large $K$, which is (in retrospect) not surprising, so nothing to see there.
Comment: So, if I were to construct an algorithm to calculate the number of unique combinations for a given (N, M, K), there is presumably no better way to solve it other than brute force?
Comment: @user34801 What? No, the recursion I gave is going to be way better than that. Even without tricks to speed up the recursion, you can find $c_N$ in just $N$ steps.
Comment: Oh okay, maybe I misunderstood your answer? I thought the recursion formula is for combinations that are not allowed, not for the number of unique combinations?
Comment: Oh! Yes, but you know the total number of combinations, it's $M^N$. So $M^N - c_N$ gives you the number you want.
Comment: Hi Misha, oh okay! Of course, I was being slow! Thanks so much :) I'm going to try implementing this method now.

Counting number of unique combinations


Rotation animation with custom view

Question: I have a custom View, IndicatorView, which is essentially a triangle that orients itself according to a specified angle of a circle with a radius equal to the triangle's length. The angle the triangle points to is frequently updated and I would like to animate between these two positions similar to how a hand on a clock moves. Below is an illustration of my custom view (not drawn proportionally or to scale; drawn according to the Android View coordinate plane):

In the IndicatorView class, I draw the triangle using a Path object and three PointF objects:
@Override
protected void onDraw(Canvas canvas){
    path = new Path();
    path.setFillType(Path.FillType.EVEN_ODD);
    //a, b, and c are PointF objects
    path.moveTo(a.x, a.y);
    path.lineTo(b.x, b.y);
    path.lineTo(c.x, c.y);
    path.close();
    canvas.drawPath(path, paint);
}

To calculate the different points, given the angle, I use parametric equations:
public void showAngle(){
    //x = centerX + radius * cos(angle)
    //y = centerY + radius * sin(angle)
    //TODO sloppy; tidy up / optimize once finished
    //centerX, centerY, length, and bottomWidth are all values
    //calculated in onSizeChanged
    a = new PointF((float) (centerX + (length * Math.cos(angle))), (float) (centerY + (length * Math.sin(angle))));
    //perpendicular bilateral radius
    double pRadius = bottomWidth / 2;
    //perpendicular angle plus or minus 90 degrees depending on point
    float pAngle = angle - 90;
    pAngle = (pAngle < 0) ? 360 - Math.abs(pAngle) : pAngle;
    pAngle = (pAngle > 360) ? pAngle % 360 : pAngle;
    b = new PointF((float) (centerX + (pRadius * Math.cos(pAngle))), (float) (centerY + (pRadius * Math.sin(pAngle))));
    pAngle = angle + 90;
    pAngle = (pAngle < 0) ? 360 - Math.abs(pAngle) : pAngle;
    pAngle = (pAngle > 360) ? pAngle % 360 : pAngle;
    c = new PointF((float) (centerX + (pRadius * Math.cos(pAngle))), (float) (centerY + pRadius * Math.sin(pAngle)));
    invalidate();
}

When I have a new angle, I use an ObjectAnimator to animate between the two angles. I place an AnimatorUpdateListener on the ObjectAnimator and call my showAngle() method in my IndicatorView using the intermediate values specified from the Animator:
public void updateAngle(float newAngle){
    //don't animate to an angle if the previous angle is the same
    if(view.getAngle() != newAngle){
        if(anim != null && anim.isRunning()){
            anim.cancel();
        }
        anim = ObjectAnimator.ofFloat(view, "angle", view.getAngle(), newAngle);
        anim.setDuration(duration);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if(view != null){
                    view.showAngle();
                }
            }
        });
    }
}

However, this code produces some strange and unexpected behavior:

The width size of the triangle changes somewhat drastically. This could be due to casting between different types but it shouldn't be that dramatic.
The point of the triangle never stops at the specified angle. Instead it just keeps moving in a circle.
The angle seems to dictate the animations speed rather than where the triangle should stop.
Sometimes it seems as though there are numerous triangles on the screen. This could be due to the speed, perhaps it's moving very fast.

Obviously, somewhere along the line my calculations must be incorrect, though, I'm struggling to find out where I went wrong. Question(s): Is there a more efficient way of getting my custom view to animate rotation to a given angle? If I am approaching this correctly, where am I going wrong?
Answer: So, the solution to my problem was rather simple but simple enough to be overlooked. The angle field that was being used for the calculations was in degrees and it just had to be converted to radians in order for it to work with the sin and cos methods.
Change all PointF instantiations, for instance:
a = new PointF((float) (centerX + (length * Math.cos(angle))), (float) (centerY + (length * Math.sin(angle))));

to use the angle in radians:
a = new PointF((float) (centerX + (length * Math.cos(Math.toRadians(angle))),
        (float) (centerY + (length * Math.sin(Math.toRadians(angle)))));

Also, part of the problem was due to sound constantly being analyzed and the View being updated before the previous animation had time to render a few frames. This led to the IndicatorView hardly moving when the angle was being updated often and when it was not it would quickly move to its destination. This happens because the previous animation is canceled before another animation is set (which is necessary to prevent a delay). This is a tricky problem to fix but one optimization I found was to avoid starting a new animation if the current angle and the previous angle were relatively close to each other.
Hopefully this will be useful for someone stuck with a similar problem. This was all part of a guitar tuner project I was working on and the source can be found on GitHub.

Rotation animation with custom view


How to dynamically set directives in php.ini from our php code?

Question: How do we dynamically set directives in php.ini from our code? We were asked this question in our exam. Is this a trick question? I thought we can't set directives directly like that and it requires restarting of Apache server.
Thanks in advance:)
Answer: The answer is probably ini_set() that changes a PHP.ini setting for the duration of the current script.
There is no way to change php.ini's settings themselves from within PHP code (except of course some horrible construction that acquires root privileges, alters php.ini, and restarts the server, but that's hardly what the test was about).


Signin with facebook

Question: In my code I check the account status from users table if it is 1 then shows the detail of user. By default the value of account status is 1. When i run the code that condition doesn't work. Here is my code. Please Help. Thanks in advance.
public function signInFacebook(SignInFacebookUser $request)
{
    if($profile_picture = $request->hasFile('profile_picture')) {
        $profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
        $request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
        $profile_picture = 'Storage/ProfileImages/'.$profile_picture;
    } else {
        $profile_picture = NULL;
    }

    try {
        $user = User::updateOrCreate([
            'facebook_id' => $request->input('facebook_id'),
        ],
        [
            'name' => $request->input('name'),
            'surname' => $request->input('surname'),
            'date_of_birth' => $request->input('date_of_birth'),
            'email' => $request->input('email'),
            'city' => $request->input('city'),
            'university' => $request->input('university'),
            'profile_picture' => $profile_picture,
        ]);

    } catch (QueryException $e) {
            $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
            return response()->json(['message' => 'Duplicate Entry']);
        }
    }

    $token = JWTAuth::fromUser($user);

    if($user->account_status == 1) {
        $userDetail = $user->where('id', $user->id)->first();
        return response()->json(['token' => $token, 'user' => $userDetail], 200);
    }
    else {
        return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
    }
}

Answer: Here is the changing I done in my code and it works.
public function signInFacebook(SignInFacebookUser $request)
{
    if($profile_picture = $request->hasFile('profile_picture')) {
        $profile_picture = time().'.'.$request->profile_picture->getClientOriginalExtension();
        $request->profile_picture->move(public_path('Storage/ProfileImages'), $profile_picture);
        $profile_picture = 'Storage/ProfileImages/'.$profile_picture;
    } else {
        $profile_picture = NULL;
    }

    try {
        $user = User::updateOrCreate([
            'facebook_id' => $request->input('facebook_id'),
        ],
        [
            'name' => $request->input('name'),
            'surname' => $request->input('surname'),
            'date_of_birth' => $request->input('date_of_birth'),
            'email' => $request->input('email'),
            'city' => $request->input('city'),
            'university' => $request->input('university'),
            'profile_picture' => $profile_picture,
        ]);
    } catch (QueryException $e) {
            $errorCode = $e->errorInfo[1];
        if($errorCode == 1062){
            return response()->json(['message' => 'Duplicate Entry']);
        }
    }

    if(!$user) {
        return response()->json(['message' => 'failed to signin with facebook'], 200);
    }

    $userDetail = $user->where('id', $user->id)->first();

    if ($userDetail->account_status == 1) {
        $token = JWTAuth::fromUser($user);
        return response()->json(['token' => $token, 'user' => $userDetail], 200);
    } else {
        return response()->json(['message' => 'you are not active on app, contact to support team'], 200);
    }
}

Signin with facebook


Explicit Isomorphism between $O(3,3)$ and $GL(4, \mathbb{R})$

Question: I have seen it stated that $O(3,3) \cong GL(4, \mathbb{R})$, but I have never seen the isomorphism explicitly defined. Does anyone know what the isomorphism is or where I might be able to find it?
Any insight is appreciated!
Answer: That can not be right: the dimension of the orthogonal groups in $m$ dimensions is $\frac{1}{2}m(m-1)$, which implies that $O(3, 3)$ is $15$-dimensional. $GL(4, \mathbb{R})$ on the other hand is $16$-dimensional.