How to apply style on a segmented button in EXT JS

Question: I would like to create menu like the one in the left figure below. I think that segmented button would be most appropriate for that, but I encountered some problems with applying styles (I also tried radio button, but it is even harder to apply style).

app.js
Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.create('Ext.button.Segmented', {
            renderTo: Ext.getBody(),
            allowMultiple: false,
            vertical: true,
            items: [{
                text: 'Option 1',
                cls: 'btn',
            }, {
                text: 'Option 2',
                cls: 'btn',
                pressed: true
            }, {
                text: 'Option 3',
                cls: 'btn',
            }],
            listeners: {
                toggle: function (container, button, pressed) {
                    alert("User toggled the '" + button.getText() + "' button: " + (pressed ? 'on' : 'off'));
                }
            }
        });
    }
});

app.scss
.btn {
    position: relative;
    display: inline-block;
    padding: 20px 80px;
    margin: 15px 30px;
    border: none;
    background: #f2f2f2;
    cursor: pointer;
    font-size: inherit;
    font-weight: light;
    letter-spacing: 1px;
    color: inherit;
    transition: all 0.3s ease 0s;
    border-radius: 24px;
}
.btn:after {
    content: "";
    position: absolute;
    transition: all 0.3s ease 0s;
    z-index: -1;
}
.btn:hover,
.btn:focus {
  color: #f8f8f8;
}

When I apply border-radius to segmented button it rounds the corners of he whole group of buttons, and not of it's children. How to apply style on children buttons separately?
The other problem associated with using buttons is that I cannot have two text fields like in the figure (Text & Val).
Comment: EXT JS version ?
Comment: @Jone version 7
Answer:

Ext.application({
    name: 'Fiddle',

    launch: function () {
        Ext.create('Ext.button.Segmented', {
            renderTo: Ext.getBody(),
            allowMultiple: false,
            vertical: true,
            items: [{
                text: 'Text3 Val3',
                cls: 'btn',
            }, {
                text: 'Text3 Val3',
                cls: 'btn',
                pressed: true
            }, {
                text: 'Text3 Val3',
                cls: 'btn active',
            }],
            listeners: {
                toggle: function (container, button, pressed) {
                    alert("User toggled the '" + button.getText() + "' button: " + (pressed ? 'on' : 'off'));
                }
            }
        });
    }
});
.btn {
    display: inline-block;
    padding: 20px;
    width: 230px;
    margin: 15px 30px;
    border: 1px solid #fff;
    background: #fff !important;
    font-weight: light;
    transition: all 0.3s ease 0s;
    border-radius: 30px !important;
    box-shadow: 0 0px 5px rgb(0 0 0 / 13%), 0 -1px 0px rgb(0 0 0 / 2%);
}

.btn span {color: #000;}
.btn .x-btn-inner {display: block;  width: 100%;}
.btn .x-btn-inner span {font-weight: bold;float: right;}

.btn.x-btn-menu-active, .btn.x-btn-pressed, .btn.x-btn-over {background: #fff !important; border: 1px solid #2ec9c8 !important;}
Comment: plz check again


django url email argument doesn't work

Question: I'm trying to pass an email trough a URL and I'm receiving this error:

The current URL, email@example.com/, didn't match any of these.

my urls.py is:
from django.conf.urls import *

urlpatterns = patterns('fback.views',

url(r'^$', 'index', name='index'),
url(r'^fback/(?P<email>\t+)/$', 'vedi_dettagli', name='vedi'),
#url(r'^fback/dettagli', 'vedi_dettagli', name='vedialtro'),

)

the views.py is:
def vedi_dettagli(request, email):
vedi = get_object_or_404(Societa, email='email')
response = render_to_response('fback/dettagli.html', RequestContext(request, locals()))
return response

Can anybody see what's wrong?
Answer: try
url(r'^fback/(?P<email>\w+)/$', 'vedi_dettagli', name='vedi'),

also:
def vedi_dettagli(request, email):
    vedi = get_object_or_404(Societa, email=email) ####<< not 'email'
    response = render_to_response('fback/dettagli.html', RequestContext(request, locals()))
    return response

django url email argument doesn't work


Chamar class="button" em vez de id="download"

Question: Como faço para esse script funcionar com class="button" em vez de id="download"?
codigo js
 var downloadButton = document.getElementById("download");
 var counter = 10;
 var newElement = document.createElement("p");
 newElement.innerHTML = "You can download the file in 10 seconds.";
 var id;

 downloadButton.parentNode.replaceChild(newElement, downloadButton);

 id = setInterval(function() {
counter--;
if(counter < 0) {
    newElement.parentNode.replaceChild(downloadButton, newElement);
    clearInterval(id);
} else {
    newElement.innerHTML = "You can download the file in " +
 counter.toString() + " seconds.";
 }
 }, 1000);

Answer: Altere na primeira linha:
var downloadButton = document.querySelector(".button");

Se só houver um elemento com essa classe, vai dar tudo certo. Mas se houver mais de um, vai dar tudo errado.
Answer: Altere a primeira linha para:
var downloadButton = document.getElementsByClassName("button")[0];

Considerando que o botão é o primeiro da classe .button. Mesmo que haja outros com a mesma classe, apenas ele será selecionado.
Comment: Cara, muito obrigado, eu já tinha colocado o document.getElementsByClassName mas não coloquei o [0], dai ele não funcionou, agora está funcionando de boa, vlw :D


Tizen doesn't recognize Google Chrome

Question: I just bought a Samsung gear 2 neo and wanted to create my own watch. So this means I am new to Tizen development.
I installed the Tizen IDE and the SDK but for some reason after following -a part- this tutorial (http://www.slideshare.net/badaindonesia/professional-tizen-application-development) Tizen won't run my projects because it can't find Google Chrome on the specified location. This problem occures when I try to run a Tizen web application as a Tizen web simulator app. When i try to launch it as a Tizen web app it says Could not find emulator or device but that isn't my current target.
The specific message is Google Chrome could not be found (C:\Program Files(x86)\Google\Chrome\Application\Chrome.exe).  Please install Google Chrome and specify the Google Chrome program location in Window->Preferences under "Tizen SDK/Web/Simulator".
I have tried changing the location to C:\Program Files(x86)\Google\Chrome\Application\ But this wouldn't help either. Yes, i have entered the correct location since i have manually located the chrome.exe to.
The only thing which might be wrong is that I am using the Windows 7 64 bit installer while I am on a Windows 8 64 bit desktop pc.
Comment: Try with `C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`
Comment: Do you mean no caps on the chrome.exe part?
I'll try it this evening ;)
Comment: No (path names are case-insensitive in Windows), `Chrome` folder after `Application` in the path.
Comment: Ohh my bad, I did actually use that path to chrome, typo in the question, sorry. -> edited it.
Answer: I have experienced a similar bug. Maybe this will help you/future developers:
My problem was that the Chrome app wouldn't open while pressing debug. I subsequently tried it with the Visual Studio Tizen extension: same problem.
The fix: I dove into the extension code and found that changing the chrome path via the option "Change Chrome path" doesn't actually change your chrome path.
What does? Going into "C:\Users\[USERNAME]\.vscode\extensions\tizenweb.wappl-1.1.2\lib\constants.js" and changing Constants.CHROME_PATH to your chrome path (for the operating system you are using).
I have not found a solution for the Tizen app, though I would recommend using the VScode extension anyway.
Answer: I had the same problem. Though not exactly a solution, I found a workaround.

Start the Web Simulator from Start Menu
Enter the location of your index.html file in the address field and press Enter
Don't forget to add file:/// in the front.

There you go!!
Comment: Somehow I can't even open the web simulator itself, system still can't find the right path to Chrome (image is in Dutch -> http://imageshack.com/a/img538/9044/ynidE4.png)

Tizen doesn't recognize Google Chrome


Como remover todas as Classes de um elemento usando jQuery?

Question: Ao invés de eu remover todas as classes individualmente utilizando o remove class:
$("#div").removeClass('classe')
Para cada classe que um elemento possa ter, existe alguma função que pode ser chamada e remover todas as classes em um elemento?
Necessito disto em jQuery ou em Javascript.
Answer: $("#div").removeClass();

Chamar removeClass sem parâmetros removerá todas as classes do item.
Você também pode usar (mas não é necessariamente recomendado, o caminho correto é aquele acima):
$("#div").removeAttr('class');
$("#div").attr('class', '');
$('#div')[0].className = '';

Se você não tivesse jQuery, então isso seria praticamente sua única opção:
document.getElementById('div').className = '';

Answer: Basta você utilizar o método removeClass sem parâmetros:
$("#div").removeClass();

Documentação


Rules to create an autoresponder for a Webform submission?

Question: I need to create a Rule to create a autoresponder email for a Webform submission.
This is: the webform has only the "email" field. When the form is submitted the rule should fetch the the 'email account' entered in the email form field and send an email to that account. That's all.
I already enabled the Webform Rules module but I see to way to fetch the email value from the rule I created.
What am I missing here?
Answer: You do have access to all labels and all values of any field of a webform, ie:

[data:MachineFieldName-title] contains the Label of a field with machine name MachineFieldName.
[data:MachineFieldName-value] contains the Value of a field with machine name MachineFieldName

So in your case, you should be able to get it to work using something like [data:email-id] (assuming that's what corresponds to the "email field" in your case).
For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

the 1st attempt relates to using "Entity has field" (which doesn't work for Webform)
the 2nd attempt explains what to do in case of Webform.

The above is a good start, but not sufficient to achieve your goal (= "When the form is submitted the rule should fetch the 'email account' entered in the email form field", as in your question).
However, you can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your [data:EmailAccountField-value-raw] (and with an appropriate data type). I'm assuming your eMail field in your webform has a machine name like EmailAccountField (adapt to fit your machine name).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).

PS: I'm assuming this question is about D7.


Collatz Conjecture and non-trivial cycles

Question: Consider
$$n \rightarrow ... \rightarrow an+b$$
to be a sequence of natural numbers to which we apply $3n+1$ or $\frac{n}{2}$ operations.
This sequence is called a cycle, if and only if $an+b=2n$.
(one can define it as $an+b=\frac{n-1}{3}$ as well, but it is the same thing, just shifted to other place)
If we use operations above and rewrite the necessary condition of a cycle, we get its general form
$$
\frac{3^k}{2^l}n+\frac{3^{k-1}}{2^{l_1}}+\frac{3^{k-2}}{2^{l_2}}+...+\frac{1}{2^{l_k}}=2n,
$$
where $l \geq l_1 \geq l_2 \geq ... \geq l_k \geq 0$ are natural numbers, including $k$.
Let's define $m=2 \cdot 2^l$ and $m_k=2 \cdot 2^{l_k}$, so we get the final form:
$$
\frac{3^k}{2^m}n+\frac{3^{k-1}}{2^{m_1}}+\frac{3^{k-2}}{2^{m_2}}+...+\frac{1}{2^{m_k}}=n
$$
and $\frac{3^k}{2^m} \in (0; 1)$.
$\mathbf Question:$ Is there any progress on solving such exponential diophantine equations?
From the first look it feels like a solid approach to the cycle problem, but perhaps it's way more difficult complication than it seems.
By intuition, can you think of a reason why only $n=1;2$ would be the solutions to this problem? Why $n=3$ has no solution?
$\mathbf Edit:$ To make things more clear, $n \rightarrow ... \rightarrow an+b$ sequence precisely follows the Collatz Conjecture and its procedure (when and which operation to apply). Also the question is mainly aimed at the constructed diophantine equation and its behaviour.
Comment: Hmm, would you mind to specify the comparision/basic status with "progress"? Of course there's progress since the 1970ies, for instance, that if a cycles is *n* steps long, its smallest element must be at least so-and-so, or if the smallest possible element is (must be) at least a certain value, then the length of the cycle must be at least so-and-so. (Crandall 78, Elihaou ??) If the type of the cycle is restricted to be "circuit" (or "1-cycle") then there is no solution (Steiner, 76; Simons since 2000 strong improvements) So do you mean "progress *from that*" or something else?
Comment: (...) btw. just to avoid misunderstanding: the math behind the proofs has been diophantine, in the end plus transcendence n.thy. (diophantine approximation to logarithms). I've once looked for the cycles of the generalized Collatz $mx+1$, and to have a chance at all to solve any solvable small subproblem I asked for the 2-step-cycle $b=(ma+1)/2^A \to a=(mb+1)/2^B$ restricted to $a=1$ ;-) Difficult enough for an amateur, but for *this* there was a solution, see my Q&A here in MSE and solution in MO https://mathoverflow.net/q/374382/7710 . (So as well a small progress...)
Answer: If we allow ourselves to apply $n_{i+1} = 3n_i + 1$ even when $2 \mid n_i$, then we can find other cycles, for instance:
$$4 \xrightarrow{*} 13 \rightarrow 40 \rightarrow 20 \rightarrow 10 \rightarrow 5 \rightarrow 16 \rightarrow 8$$
However, there is no solution to $3m+1 = 2^j \cdot 3k$ in the integers. That means there's no way to get to $6$ except from $12$, and no way to get there but from $24$, etc. Similarly, you can only get to $9$ from $18$, etc. So no $2^j \cdot 3k$ can never be a solution to this cycle.
I'm not sure anything other than multiples of $3$ are excluded from this "wonky" Collatz cycle, though cycles will get big. If we start with $5 \xrightarrow{*} 16 \xrightarrow{*} 49$, after another $20$ or so (standard) steps, we get to $10$.
But this only answers your final question; I know of no progress on that sort of Diophantine equation.
Comment: My edit was for a typo (a missing word). "However there is $no$ solution ..."
Comment: Excellent catch, thank you.
Comment: Great observation about multiples of 3. I know that I didn't specify good enough, but the last part of my question was in the context of the diophantine equation: Can we get any intuition why equation fails for some $n$? If we can find a reason to that, then maybe other $n$ follow similar conclusions. Or in the best case, we could see why $n=1; 2$ solutions are in some way special.
Answer: In case you start your question from simplest state, then I can show you a "progress" in proving of nonexistence of (nontrivial) 2-step and 3-step cycle, and from this method an extension to a handful of more $n$.
I write the transformation on odd $a$ such that $ b = {3a+1\over 2^A}$ with $A = \nu_2(3a+1)$, so $a$ and $b$ are both odd, and $A$ contains the number of steps of division-by-2.
1-step cycle

Now look at a $1$-step cycle:
$$ a = { 3a+1 \over 2^A} \tag {1.1}$$
rewrite
$$ 2^A = { 3a+1 \over a} = 3+ {1 \over a} \tag {1.2}$$
With simple diophantine arguments we see that we can only have the cycle with $a=1$ and $A=2$ and no others.

2-step cycle

Now look at a $2$-step cycle:
$$ b = { 3a+1 \over 2^A} \to a = { 3b+1 \over 2^B}  \tag {2.1}$$
rewrite
$$ 2^{A+B} = { 3a+1 \over a} \cdot {3b+ 1 \over b} \\
= (3+{ 1 \over a})\cdot(3+{1 \over b}) \tag {2.2}$$
With still simple diophantine arguments we see that we can only have the cycle with $a=b=1$ and $A=B=2$ and no others (the rhs can only be in the interval $9 \ldots 16$ and $16=4^2$ is the only perfect power of $2$ in this interval and thus in both parentheses the fraction must equal $1$).

3-step cycle

In the same way we look at a $3$-step cycle. But here, we get that the rhs could become a power of $2$ which is not $4^3=64$, but larger than $3^3=27$ namely $32=2^5$.
Here we introduce the additional diophantine arguments, that

the elements $a,b,c$ cannot be $1$,
and must be $\pm 1 \pmod 6$
and must be pariwise different

so can at least be $(a,b,c)=(5,7,11)$. Inserting this in the rhs gives something smaller than $32$ and increasing any of the $(a,b,c)$ would furtherly decrease the rhs below $32$.
This shows by diophantine arguments only, that a nontrivial $3$-step cycle cannot exist.

In that way we can try other $n$ for the $n$-step-cycle and it is easy to generate a list for $n$ up to -say- $200$ for which the cycle cannot exist - purely based on diophantine arguments.
(I hope I didn't misread the intention of your question)


method called in document.m on closing of document

Question: i use - (void)windowControllerDidLoadNib:(NSWindowController *)aController to see when a document has been loaded in a document based application. But what method should I use to see when a document is beeing closed? i would like to save the content of a textbox to the NSUserDefaults but i am unable to find a method that is called whenever the document is closing. i searched the web and also trough the methods that appear as hint in xcode but without luck! any help appreciated!
thanks
Answer: I observe NSApplicationWillTerminateNotification and override the [NSDocument close] method to perform document clean-up ([NSDocument close] isn't called when the app terminates!)
MyDocument.h:
@interface MyDocument : NSDocument
{
    BOOL _cleanedUp;    // BOOL to avoid over-cleaning up
    ...
}

@end

MyDocument.m:
// Private Methods
@implementation MyDocument ()

- (void)_cleanup;

@end

@implementation MyDocument

- (id)init
{
    self = [super init];
    if (self != nil)
    {
        _cleanedUp = NO;

        // Observe NSApplication close notification
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(_cleanup)
                                                     name:NSApplicationWillTerminateNotification
                                                   object:nil];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    // I'm using ARC so there is nothing else to do here
}

- (void)_cleanup
{
    if (!_cleanedUp)
    {
        _cleanedUp = YES;
        logdbg(@"Cleaning-up");

        // Do my clean-up
    }
}

- (void)close
{
    logdbg(@"Closing");

    [self _cleanup];

    [super close];
}

Comment: thanks, what do you mean "isnt called when the app terminates"? is there no native method to execute something on closing of a document?!?!
Comment: Yes, and that is `[NSDocument close]`, but as I say if the user just quits the app it isn't called (for some reason), which is unsatisfactory for my needs.
Comment: oh ok, thanks for your comment! this instad is called everytime when a document is closed and when the application is closed.. right?
Comment: Does this break state restoration? If I have some documents open and quit your app on Lion or Mountain Lion, will those documents still be reopened the next time I launch your app?
Comment: No I don't see why it would; it's for cleaning up document resources (in my case closing a database).
Comment: I meant responding to `NSApplicationWillTerminateNotification` by closing all the documents. Is state restoration still able to record the set of open documents at quit, either by doing that before you get notified and close them all or by them still being "open enough" (in whatever way it needs them to be) when the state-save happens?
Comment: As I say, I don't see why, as the document isn't closed in response to the notification; it's just used to clean-up without changing the document status.  However I can't say that I've explicitly tested it.
Comment: `- (void)close`: '*This method may not always be called.*'.  https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSDocument_Class/Reference/Reference.html#//apple_ref/occ/instm/NSDocument/close


Any way to delay PaintComponent?

Question: I've read through lots of the threads on paintComponent here, most of which making the point that it either is never or almost never necessary (or possible) to choose when paintComponent is called.
In my program, however, sometimes (only sometimes) paintComponent gets called before some of the objects it needs to paint have finished initializing or even sometimes before they've been created, triggering warnings- JOptionPane pop-ups, which surprisingly do not show any of the text they were hard-coded to display in their "message" area. I've read in other places that it's something to do with the EDT, and I've looked into some parts of that but I'm just getting confused. If the main purpose of the EDT is to update the gui, and by default pretty much everything will run in the EDT, then could I tell the program to run all the initialization and update functions in a different thread(s), which I somehow forcibly make run before the EDT runs?
What I'd ideally like to have happen is for paintComponent to wait until a certain point in my code to be run (after a bunch of update functions, regardless of what happens to the screen. After it does get called, it is followed by a pause in which relatively little is going on ( I had been using Thread.sleep() inside a while loop ) and which lasts until the user clicks something - at which point all the necessary functions are run again, followed by paintComponent afterwards, then the sleep() while loop, etc.
From what I understand, I think what I want isn't really possible, so my question is: Do you guys have any ideas of how to get around this?
EDIT:
So essentially the program is a college course planner, intended to make it easier for someone to plan out by semester all the courses they have to take before graduation, move those courses around (if possible), and see how all the courses are connected (prerequisites and such). When the program starts, it loads the list of necessary courses from a text file, then loads info about each course from a bunch of individual text files, and arranges them according to their prerequisites. Courses with no prerequisites go in the first semester, courses whose prerequisites have all been added to the first semester get added to the second, and so on until all the courses have been added. When paintComponent runs, it calls a function that assume all of each course's prerequisites exist on the schedule, and if it finds otherwise, it throws an error and displays a JOptionPane message box. When this happens during a normal run of the program (like if I manually add a course before adding its prerequisites), that all works and displays correctly. But sometimes that message box pops up when only some of the courses have been loaded (meaning control is still in the main constructor) and when it does so, the actual string message doesn't show up - only the actual pane, title and ok button do. Heres the line where I display the error box, so you can know that I'm not trying to display a string variable which has the potential of being empty.

JOptionPane.showMessageDialog(this,
                        "Course couldn't be loaded, partially >loaded\ncourses have been removed.",
                        "Error",
                        JOptionPane.OK_OPTION);

It is the "Course couldn't...been removed." part that doesn't get displayed. This is the only JOptionPane I display with the title "Error".
This post mentioned what sounds like the same thing happening, except I'm not using any of the things that poster had to fix. So possibly it's irrelevant but I'll add it just in case. JOptionPane.showMessageDialog() shows but without any message?
But to step back a bit, because that box popped up before all the courses had been added, it means that paintComponent was somehow called in the middle of the relevant JPanel's constructor, before a bunch of things had been initialized. I added a bunch of println() statements to make sure that that is true. Is it normal for that to happen, and if so, is there a way to fix it without simply using Andrew Thompson's advice?
After thinking though it a bit, I think that because the project is 3200 lines long and relies to a huge extent on text files, I'm really not sure how to ( or if I can) make a SSCCE for it..
If any specific pieces would be helpful I'll gladly add those but if this problem isn't clearly some standard issue I'm getting wrong, then I'll just add that flag and keep looking for bugs.
Thanks for your help
Comment: `paintComponent gets called before some of the objects it needs to paint have finished initializing` - such as? Give concrete examples. I've never had a problem. `JOptionPane pop-ups, which surprisingly do not show any of the text they were hard-coded to display in their "message" area.` - never seen anything like that. The problem is probably the structure of your code. Post your [SSCCE](http://sscce.org/) demonstrating the problem.
Answer: Declare a flag as a class attribute. Check it in the paint method.  Change it at the end of the initialization.
<code>class XandYandZ extends JComponent {

  boolean initializationFinished = false;

  public XandYandZ() {
    // long initialisation..
    initializationFinished = true;
  }

  public void paintComponent(Graphics g) {
    if (!initializationFinished) return;
    // .. paint ..
</code>
Comment: Well now I feel dumb. I'll probably just do this, but I would like to understand why my code is doing what it is, if possible. It just doesn't seem like a known thing, paintComponent being called before everything inside has finished initializing. Though I guess I don't know why paintComponent would wait. Is this a standard issue or is this just hiding bugs in my code?
Thanks:)
Comment: *"or is this just hiding bugs in my code?"*  For more detailed help, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example).  I suspect @camickr has identified a design flaw.  To best advise on the fix, we'd need more detail of what it is.  And for that, I prefer to let the code (MCVE) do the talking..
Comment: You're right, my question assumes you know my code (sorry, I keep forgetting other people don't!)
I'll add more about it to the main post.

Any way to delay PaintComponent?


Is there a difference between a Markov Kernel and a Transition Kernel?

Question: I have been reading some literature on particle filters and it seems that the definition of a Markov Kernel and a Transition Kernel seem to be the same. However, I was wondering if these two terms when used in literature are the same thing. Does anyone know the parlance here? Thanks.
Answer: $P(x,A)$ is a Markov kernel ($x \in X$ and $A \in \mathcal{B}(X)$) if

for each $A$, $P(\cdot,A)$ is non-negative and measurable, and
for each $x$, $P(x,\cdot)$ is a probability measure.

When people drop the "Markov" part, I take it to mean either

we're losing non-negativity when considering $P$ as a function in the first argument, or
It's a measure in the second argument, but not necessarily a probability  measure (e.g. $P(x,X) \le 1$ or $P(x,X) > 1$).
Comment: When you mention the dropping of the Markov part, do you mean a transition kernel or just a kernel by itself?
Comment: @user321627 stochastic/Markov/transition all mean the same thing to me. When people say Kernel by itself, they might mean the general way. And this all depends on the context; it wouldn't be unlikely that someone just says kernel when they are talking about a Markov chain
Comment: @user321627 if youre looking at pfilters im pretty certain you mean Markov/transition kernel
Comment: Markov is commonly associated with a "memoryless" property (e.g. [here](https://stats.stackexchange.com/tags/markov-process/info))


How to enter IV in logistic Regression for testing significance

Question: for my thesis I need to build a logistic regression model and test the significance of several indicators on a certain outcome, that is testing if the independent variables has a significant effect on the dependent variable.
For the first try, I entered all the IV simultaneously, resulting in a significant LLR p-Value, but some of the IV dont have a significant p-Value or dont have the effect on the AV that I was expecting. Obviously some Variables are some sort of confounders. Therefore I came up with trying to build seperate models for each IV. Each model had the effect that I was expecting of the IV and were also significant but I'm not sure if this would be the correct proceeding for testing the indicators, as I think any valid Information that is entered to the blank constant regression model is somehow significant.
I'm not so much interested in what indicator is the best for predicting the outcome (which would yield in a forced entry of the IV to the model) but as I mentioned I just want to know if the indicators are signifcant concerning the AV.
What would your suggestion be in this particular case?
Comment: Are you looking for a joint test of significance for all your indicators?
Comment: Regarding the prior formulated hypotheses, I want to check for the significance for every indicator independently, so I assume that I'm not looking for a joint test (actually not sure what this is).
Comment: In which model(s)? The bivariate regressions with one indicator each are restricted versions of the multiple regression model with all indicator variables included, under the maintained hypothesis that all but the included indicator are insignificant. If the results of the multiple regression do not meet your expectations, you should check whether your regression is otherwise misspecified.
Comment: Not just "insignificant' but conditional on the effect being exactly zero.
Answer: In the field of medical research it is quite common to present the coefficients from the full model (with a confidence interval) alongside the coefficients (and confidence interval) from the series of bivariate models. This is sometimes extended to a set of intermediate models using theoretically justified subsets of the predictor variables (so one might first add the demographic variables). If your predictor variables fall into several theoretically justified subsets you could consider fitting the full model and then checking the effect of dropping each subset using a LRT. What is best depends strongly on (a) the underlying science (b) publication practice in your discipline. In any event you want to avoid automatic variable selection methods.
Comment: In my humble opinion this represents not so good statistical practice and results in very hard to interpret estimates.  Just stick with the full model.
Comment: How does an unadjusted estimate with unknown confounding give you any useful information?  Unadjusted estimates are very hard to interpret and may be misleading.  They also sidetrack the reader from the important issues and create confusion in the minds of readers.
Comment: @Frank I agree the full model is and should be the primary interest but sometimes it is hard to understand and the other suggestions help to disentangle.


Exchange 2013, flow messages to a third-party smtp

Question: I plan to use a SMTP Archiving feature in my archiving solution (non Microsoft). I wish to send a BCC copy of every message to a particular SMTP server (installed on archiving software). In Exchange 2003 there was a BCC journaling feature that could be enabled in a registry. Is  there any way to direct all messages, external and internal, to a third-party SMTP server on Exchange 2013/2016? On that separate SMTP server I have an archiving software that can capture and archive incomming messages. I'm not able to use standard Exchange Journaling, since I have no licenses to integrate my currect archiving solution (non Microsoft) with a Journal Mailbox.
Any ideas? How to configure it in Exchange?
Answer: You can achieve this using transport rules that are applied to messages.
add a new transport rule that adds an additional recipient (bcc).
Comment: That is a good idea, thank you. Now I am wondering about something else. My archiving server is a separate SMTP server (not only a recipient). How to make Exchange to send the message both, to MBX server and to Archive Server. Shoud it be a separate (sub)domain with additional MX records in DNS?
Comment: How about Shadow redundancy? [link] https://technet.microsoft.com/en-us/library/dd351027(v=exchg.150).aspx
Comment: in my understanding shadow redundancy is just intended to have a temp copy of a mail to reduce chances of losing a mail after having it accepted via smtp.
to provide a transparent mechanism in between you may setup a smarthost on sending that offers message duplication - which is in general much more complicated than using the bcc copy (if this is sufficent for your needs)
Comment: No need to add additional DNS records etc.
Setup a specific Send Connector for the sub domain. So archive.example.com. Then configure the Send Connector to use a smart host and enter the IP address/DNS name of the other server.

Although why not just configure journaling within Exchange and have the address set correctly? No need to BCC, that is what journaling is designed to do.
Comment: I can configure journaling in Exchange, but I thought that Journal Reports need to be send only to an Exchange Mailobx (not any entered e-mail address). Can I enter ANY e-mail address for Journal Reports? Even from another domain or subdomain?
Comment: Finely I used Database Journaling, poited it external contact and send connector to direct messages to a specified SMTP host.


what is the meaning of this Logical operators combination in C

Question: i know that -> is a pointer |= is OR.
what is the logical meaning of such line?
TIMER0->ROUTELOC0 |= TIMER_ROUTELOC0_CC0LOC_LOC15
Answer: |= does not mean OR. | means OR.
|= is similar to +=, that is
A |= B is the equivalent of A = A | B
So to answer your question:
It looks like TIMER0 is a structure with a member ROUTELOC0. The above expression is setting the ROUTELOC0 as the result when ROUTELOC0 is ORed with TIMER_ROUTELOC0_CC0LOC_LOC15
Answer: You're ORing in (setting) a value to a register. Your processor has a TIMER0 with a register ROUTELOC0. It likely has a bit that is "CC0LOC_LOC15"
I recommend looking at the data sheet for your processor to figure out what that means specifically.
Comment: This is my code, Why Are we using OR for Setting route to Location?

// Set route to Location 15 and enable
  // TIM0_CC0 #15 is PC10
  TIMER0->ROUTELOC0 |=  TIMER_ROUTELOC0_CC0LOC_LOC15;

  TIMER0->ROUTEPEN |= TIMER_ROUTEPEN_CC0PEN;
Comment: You use OR because you don't want to mess with any of the other bits in the register. If you were just setting it (`TIMER0->ROUTELOC0 = TIMER_ROUTELOC0_CC0LOC_LOC15;`), you'd clear all the other bits in the register inadvertently. As to why you're setting it, I don't know what processor you're using, so I can't tell you that.
Answer: The -> is the structure dereference operator, and |= is the bitwise OR assignment operator (compound assignment).
The compound assignment:
x |= y ;

is equavilent to:
x = x | y ;

It is important here to understand that bitwise-OR (|) is distinct from boolean-OR (||).  It is used here to set specific bits in x leaving other bits unset.
For example, to set the two least significant bits of x to 1:
    x: 10100000
    y: 00000011
      ---------
  x|y: 10100011


getOrElse for an Option(null) does not return a None type or the default value when null in Scala

Question: I am trying to initialize a list in Spark using scala, from a column of data. The value in some of the rows can be empty, and in some rows it's filled. So I am making my list of type Option[String]. But, when I access the elements in it, scala returns a Some for each element, including empty values, even if they have been initialized using Option(null). This means that when I try to get the value as getOrElse("0"), it prints Some() if the value should have been "0". In code, this is what I am doing:
val columnsToRead: List[String] = List("__id", "device");

val selectedColumnsDataset: Array[List[(String, Option[String])]] =
    dataset.map(s => {columnsToUseForCorrelation
    .map(t => (t, Option(s.getAs[String](t))))
}).collect();

I confirmed that the expression s.getAs[String](t) returns a null if t isn't in the row, by writing this alternate map
val selectedColumnsDataset2: Array[List[(String, Option[String])]] =
    dataset.map(s => {columnsToUseForCorrelation
    .map(t => (t, s.getAs[String](t)))
    .map(t => (t._1, if (t._2 == null) Option(null) else Option(t._2)))
}).collect();

Both of these expressions return the same output, so I think I am doing it correctly. The problem I  face is when I try to print out the values in here. One thing I have to do first is to convert the list to a wrappedarray, which I don't understand where the implicit conversion happens, but it throws an exception if I do a map on the lists. This is my code for printing out those values:
    val selectedColumnsParsed = selectedColumnsDataset.asInstanceOf[Array[mutable.WrappedArray.ofRef[(String, Option[String])]]];

    selectedColumnsParsed.foreach(s => {
        s.foreach(t => {
        println(t._2.getOrElse("0"), t._2)
        })
    })

The output I get from these is
(440,Some(440))
(157,Some(157))
(441,Some(441))
(,Some())
(,Some())
(443,Some(443))
(,Some())

The empty values show that they are empty, so they should have been casted automatically to a None type, but instead they are a Some type, and I don't understand how they aren't Some(null) as they should be. The strings look like they are empty of length 0, but calling isEmpty in the println statements throws a null pointer exception, so that means that the getOrElse should return the default value 0, but it does not do that. What is the proper way to initialize the Option type so that a null is matched to a None type?
Comment: It looks good to me. `Option(null)` should return `None`. Have you tried `s.getAs[Option[String]](t)`?
Answer:
The value in some of the rows can be empty

Empty (blank) is not the same as null:
"".isEmpty
// Boolean = true

"" == null
// Boolean = false

so consequently Option of empty string, is not None:
Option("")
// Option[String] = Some()

One thing I have to do first is to convert the list to a wrappedarray, which I don't understand where the implicit conversion happens,

This happens because data stored in Dataset is encoded. We don't depend on specific implementation, but on interfaces. Here you should really use Seq.
To keep things clean, I would go with something simpler:
import org.apache.spark.sql.functions._

val columnsToRead: List[String] = List("__id", "device");
val dataset = Seq(
  ("foo", null, 0),  // Here we expect None
  ("bar", "", -1),   // Here we expect Some("")
  ("xyz", "zyx", 1)
).toDF("__id", "device", "some_val")

dataset
  .select(array(columnsToRead map col: _*))
  .as[Seq[Option[String]]]
  .map(columnsToRead.zip(_))
  .collect.foreach(println)
// List((__id,Some(foo)), (device,None))
// List((__id,Some(bar)), (device,Some()))
// List((__id,Some(xyz)), (device,Some(zyx)))

or
dataset
  .select(columnsToRead map(c => struct(lit(c), col(c))): _*)
  .as[((String, Option[String]), (String, Option[String]))]
  .collect.foreach(println)

// ((__id,Some(foo)),(device,None))
// ((__id,Some(bar)),(device,Some()))
// ((__id,Some(xyz)),(device,Some(zyx)))

If you want blank strings to be None you'll have to handle this explicitly.


Displaying settings internally represented with sections in Android Listview

Question: I'm writing an application for iOS and Android in parallell and I am facing a small problem.
I am displaying a list of settings to the user and the settings data is internally represented in settings for section, like this:
Section
    Section object
    Section object
Section
    Section object

etc.
In iOS, when the user clicks a setting object, or when the system wants to paint the view for it, it calls a method with an NSIndexPath object. For example:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

and the sections are handled automatically.
In Android, the listviews are "flattened", lacking better terminology. So that a method is called only with a row index:
public Object getItem(int position);

Now it is actually a quite hard problem to solve trying to represet sections directly in the Adapter (MySettingsAdapter extends BaseAdapter).
Right now this problem is solved by flattening the entire underlaying data structure, but it's a lot of duplicated code for almost nothing. The nicer solution I can think of is to do something like the following in my MySettingsAdapter:
class MySettingsAdapter extends BaseAdapter {
    MyInternalDataStructure settingsData;
    int sections;
    int rowsForSection[sections];

    public MySettingsAdapter (MyInternalDataStructure settingsData) {
        this.settingsData = settingsData;
        this.sections = settingsData.sections;
        for (int i = 0; i < sections; i++) {
            rowsForSection[i] = settingsData.settingsInSection[i].size();
        }
    }

    @Override
    public Object getItem(int position) {
        int sectionFromPostion;
        int rowFromPosition;
        // Calculate section and row here...
        return settingsData.getSetting(sectionFromPostion, rowFromPosition);
    }
}

And I just can't get the calculations for sectionFromPostion and rowFromPostion right...
Answer: Unfortunately Android does not have quite the same ability in regards to sections as you can achieve with the UITableView.  However Android does provide a solution, the ExpandableListView.  While similar to a ListView it works a bit differently and interacts with a different type of adapter.
Android provides the SimpleExpandableListAdapter that you can use with the ExpandableListView. I'll warn you now. It's clunky and pretty restricting.  Additionally, it requires you to organize your data into a List of Maps which in itself can be a pain to do.
Alternatively, you can create your own adapter for the ExpandableListView by implementing the BaseExpandableListAdapter.  It's very similar to implementing the BaseAdapter.  It just has a few extra bells and whistles to support a tier like structure.
Basically all these Expandable...[foo] classes introduce the idea of having a group (the section) and children (the data under a section). Instead of having an index to the data in your adapter, you'll have a groupPosition and a childPosition.  Meanwhile the ExpandableListView has this sorta murky middle notion of positions as it works with group/child positions, packed positions, and flattened positions.
As a side note. Depending on how your data is organized, I'd suggest checking out the Rolodex Adapters found in this 3rd party library. They are meant to make working with ExpandableListViews easier and has plenty of code examples and a demo app to help get you going.


How do you write a corresponding bassline for an already written melody?

Question: In my music theory class I have created a 16-measure melody, and have now been instructed by my teacher to create a corresponding bass-line for that melody. (I scored an 88% on my melody, so I assume it is relatively fine.) However, I am left very confused on how to do this. How do I determine which chords to use for the bass-line? How do I know if the newly created bass-line complements the melody properly?
I've searched online and have found nothing but extremely off-topic posts or YouTube videos. I'm not asking someone to do my homework for me, rather I'm asking how one makes a bass-line that complements a melody whilst following rules. My melody is pictured below:
Comment: This is obviously a question about theory, this is why I'm posting this as a comment rather than an answer: simply imagine a bass line and try to figure it out note by note. This is obviously hard for beginners, but you can use an instrument to check the notes before writing them down. If you have memorized the melody, chances are the bass line you'll improvise will almost perfectly fit the melody, and only minor corrections may be required.
Answer: First, you need to identify one or two candidate chords -- in a situation like this, you'll probably want to do this for each measure.  Try them out on the piano to help you choose between them.  For example, when there is a C in the melody, your candidate chords would be C major (I) and A minor (vi).  Mostly likely you'll choose C major.
Once you've written down the chord symbols below each measure, then you'll want to pick out one of the notes in the chord to assign to the bass line.  If you can make a nice scale-like movement in the bass line, that will sound nice!
Usually the teacher shows the students some examples of doing this.  I'm rather surprised this teacher hasn't done this.  Perhaps you could go to office hours.
There's one tiny thing about your otherwise very nice melody that I don't understand, and that is the last measure.  When I tried singing your tune, I felt better when I left out that last D.
Comment: Don't  leave out the F chord,(IV) which can fit to a C note as well. The D at the end works if it's a 1st time bar with a repeat, then a C for the 2nd time at the very end.
Answer: The steps would include.

Determining the Key
Providing points for Cadences
Determining the chords and then there inversions

And then finally you write a melody in response to the given notes.
Things to note.

The proper rules for good melody writing still apply to the bass line
you are writing.
Try and get the width of the melody an octave.
Try to avoid jumping big intervals.
No consecutive octaves or fifths
It would be good if you can show that you are comfortable with using
the Super Tonic and Dominant chord with its seventh (Remember proper
resolution.)
Your melody still needs a proper line
Answer: Simple answer:
1) Find your places of cadence (a "resting point" within the piece).  It looks like bar 8 beat 3 is a good candidate for a cadence.  Since your melody falls on E, and since (aside from the unorthodox ending on D at the end) your key is in C major, and since you seem relatively new to harmony, this should be a C major chord or A minor chord; write this down for later.  For simplicity sake, your next cadence will be at bar 16, which would require you to not finish on D if you want a perfect authentic (a.k.a "final sounding") finish.
2) Find your rhythm.  Your strong beats are 1 and 3, since throughout the piece you put emphasis on the 3 by using half notes on beat 3.  Without worrying about notes, clap or tap a rhythm that you think sounds like it fits your melody while remembering that you keep emphasizing that third beat.  Since the melody at those times has a half note on the third beat, this is an opportunity for your bassline to "take stage" and become pronounced.
3) Fill in your notes.  Write down the notes at your cadences first (you will revise this later), then start writing down your notes with the ultimate goal of "resting" at the cadences; ensure that rhythmic bassline melody fits the same standards that you have been taught that makes a "good" melody.
4) Go back and revise what you wrote, since now that you have a complete or almost complete bassline to accompany your melody, you can now go in and make small adjustments here and there with the bigger picture in mind (...really in front of you....)
Complicated answer:
Learn harmony; learn harmonic progression.  Then learn counterpoint and do a bunch of exercises.
Answer: I believe what the assignment calls for is an excerise in counterpoint, I think 1st species, as I recall. A good textbook re these 'rules'would be a good resource. The previous answers are examples of these.
As I recall, in my studies, we followed certain counterpoint rules as stated by Fuchs or Fuchs.what I meant by species, is at first one writes one line against another, then, progressing to one line against two lines, speaking verttically, as in the Bach Chorales. The species is then, I believe, a bass line, with more than just quarter notes against it, ie 2 notes against one, and so on. Please correct me if I am mistaken.
Comment: 1st species? Could you elaborate on that? Also, what does "re" in your second sentence mean? Which "rules" are you referring to? How does this answer the question?
Comment: "re" means regarding.  I think UriahB is a newcomer to SE and is finding his voice.  Let's give him a little time.  For now, for this particular question, judging from the amount of instructions the OP was given by his/her instructor, I think it's safe to say we don't need to ask the OP to understand counterpoint, 1st species, or rules.
Answer: As I see 16 measures here, my eyes went on eighth measure fastly. I was looking for cadance half-the-way.
You start with Do "C" and the last note is Re "D". This is something you don't want to do as you start writing melodies first. Because it makes a complicated harmonic structure in a hard way for you to have your way out of it through first and sixteenth.
Try dividing your measures to half, it will become easier to see your works as all. Like this = you have 16, so eighth measure is a buff zone for sixteen. fourth measure is a buff zone for eighth (first piece of it) and your twelve measure for the second piece.
What you did was questionbly open for some counterpoint writing. But remember, counterpoint writing is the most difficult to accomplish. If someone "recalling" counterpoint rules it means they don't know anything about it, believe me...
What to do to these buffer zones ? Try using your two beat notes at those points with your tones voice. As in Do Mi Sol "C E G" gives you the Do Major tone voice. (since you started with Do and no sharps or flats i assume its C Major)
Use Sol "G" in eighth measures end because it is your Dominant note.( fifth note is always Dominant in a tone right?)
Oh and when you are studying if you write the melody first it will be hard to put a bassline under it. Try writing the bass first, make sure you end and
-preferably- start with Tonic ( tone voice -First note- ) and put a dominant around eighth, good luck and have fun !


Chart.js não aparece no html

Question: Bom dia pessoal, recentemente resolvi implementar o chart.js em alguns projetos meus, porém ele não me exibe os dados.
Estou deixando abaixo o código fonte de testes que não é exibido.
    <!DOCTYPE html>

  <title></title>

<canvas class="line-chart"></canvas>

Answer: Tem dois erros no código:

deve usar new Chart e não new chart, veja a documentação: https://www.chartjs.org/docs/latest/getting-started/
os parâmetors estão mal formatados, falta uma vírgula aqui: type:'line',

var ctx = document.getElementsByClassName("line-chart")

var ChartGraph = new Chart(ctx, {
    type:'line',
    data:{
      labels: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun","Jul", "Ago", "Set", "Out", "Nov", "Dez"],
      datasets: [{
        label: "Taxa de Cliques - 2020",
        data: [5,10,5,14,20,15,6,14,8,12,15,5,10],
        borderWidth: 6,
        borderColor: 'rgba(77,166,253,0.85)',
        backgroundColor: 'transparent',
      }]

    }
  })

<canvas class="line-chart"></canvas>
Comment: Valeu irmão, resolveu meu problema!
Comment: boa, não esqueça de aceitar a resposta ;)

Chart.js não aparece no html


How do you play a scale "in sixths" or "in thirds"?

Question: I have developed a new interest in music after many years, so I am brushing up on old stuff that I have long forgotten.
I'm watching some instructional videos which discuss  "playing a scale in sixths" or "playing a scale in thirds". The videos also refer to "fourths" and "fifths" in other lessons.
What do these terms refer to? Does it mean the length of the note (in beats)?
Answer: Thirds and sixths are what are called intervals. They measure the distance between two pitches. When you count an interval, we count both the first pitch and the last pitch, so C up to E is a third (C is 1, D is 2, E is 3).
When the two pitches of an interval are played at the same time, we call it a harmonic interval. When the two pitches are played separately, it is a melodic interval.
So a C-major scale played in harmonic thirds would be C-E played together followed by D-F, E-G, F-A, etc.
We can also play a scale using melodic thirds, which would just be C E D F E G F A G B A C B D C.
(I would guess he means the latter definition, but the video was too long for me to find out.)
Comment: Playing the melodic scale is excellent practice for all instruments, in part because those patterns show up all over the place in music.  For strings, playing harmonic double-stops is equally great practice for similar reasons.   Harmonic thirds, sixths, fourths, and octaves are good patterns to learn.
Comment: Yes he definitely means melodic 3rds and 6ths. It's a common practice technique for improvisation. At worst you learn the scale better but due to the melodic sound of 3rd and 6ths such patterns can find their way into solos as well. Also just in case it wasn't clear from the C major example, you play those intervals diatonically or within whatever scale you are targeting. So you don't always play a major 3rd, you might play a minor 3rd depending on the scale at hand.
Comment: Funny. On violin, the assumption (at least in my experience) is harmonic intervals when in the context of a scale.
Comment: @GeneralNuisance yeah, I hadn't even heard of playing scales in melodic intervals when I took my grade 8 violin, and there were definitely harmonic ones because I remember hating them!


Quantified Modal Logic - How does an existence predicate help with a fixed-domain model?

Question: When constructing models for a first order modal logic, we have to decide whether we want to have a fixed domain (the possibilist semantics) or a world-relative domain (the actualist semantics).
In the fixed-domain model, the quantifiers range over all possible objects. Some will introduce an existence predicate, in order to restrict statements to the "actual" world.
The SEP page on modal logic summarizes the situation like this:

Furthermore, those quantifier expressions of natural language whose domain is world (or time) dependent can be expressed using the fixed-domain quantifier ∃x and a predicate letter E with the reading 'actually exists'. For example, instead of translating 'Some Man exists who Signed the Declaration of Independence' by
∃x(Mx & Sx),
the defender of fixed domains may write:
∃x(Ex & Mx & Sx),
thus ensuring the translation is counted false at the present time.

I'm having trouble grasping how  "∃x(Ex & Mx & Sx)" fixes an interpretation to the actual world any more than "∃x(Mx & Sx)" does.
As I understand it, these expressions are always evaluated at a world. So "Ex" will only be true in worlds where Ex is satisfied. (For instance, assume that G is an interpretation function, and assume that "Ex" is only satisfied in worlds where G(x) \in G(E).)
But wouldn't the same be true for "Mx"? Why should "Ex" be satisfied in one world any more than "Mx"?
What am I not grasping here?
Answer: My reading of the Modal Logic entry of SEP is that it does not claim that "$\exists x (Ex \wedge Mx \wedge Sx)$" fixes an interpretation to the actual world.
Introduction of the predicate letter $E$ merely gives an adopter of constant-domain quantification the ability to write a sentence asserting the existence of a man who signed the Declaration of Independence that may be false in one world and true in another, accessible world.
Interpreting $Ex$ as "$x$ actually exists in this world" makes the sentence false in this world and true in the world of 1777.  (Provided the obvious interpretations are given to $M$ and $S$ too.)
In 1775, however, no man had signed the Declaration of Independence.  The sentence "$\exists x (Ex \wedge Mx \wedge Sx)$" is false in that world too, though the interpretation is not fixed to the actual world.
Comment: Is "∃x(Mx & Sx)" true in the 1775 world? I would have thought that it isn't, because Mx and Sx won't turn out true in that world (assuming no object from the domain shows up in the interpretation of M and S in the 1775 world).
Comment: In constant-domain quantification, free variables take as values objects from the domain of the model, not necessarily from the domain of the "current world."  Hence $\exists x(Sx)$ is true in the 1775 world if there exist some element $x$ of the domain of the model (say, in the 1777 world) for which $Sx$ is true.
Comment: I must be confused. I'm having a hard time understanding how ∃x(Sx) could be true in the 1775 world, when Sx is not satisfied in the 1775 world.
Comment: Let $w1775$ and $w1777$ be two worlds. Let the sole domain $D$ contain two objects $\{ m, n \}$. Let $G$ be an interpretation of the predicate $S$ such that $G(S, w1775) = \{\}$ (which means nothing satisfies $S$ in $w1775$), and $G(S, w1777) = \{ m \}$ (which means $m$ satisfies $S$ in $w1777$). Under this interpretation, the truth conditions for predicates are relativized to worlds, aren't they? So $\exists x(Sx)$ should be true only in $w1777$, and not in $w1775$. Or am I mis understanding something?
Comment: Yes, when you define a model you choose the interpretation of each relation symbol in each world of the model.  In the constant-domain approach, the interpretation of a relation symbol is a relation of the proper arity on the domain of the model.  That's exactly what happens to the $E$ unary relation symbol.  Its introduction frees one from having to say that Benjamin Franklin is not a man or is not a signer of the US Declaration of Independence, given that Franklin is an element of the model's domain.  (To be continued.)
Comment: My example $\exists x(Sx)$, I realize, was confusing, because the sentence talks about a man "who *signed* the Declaration of Independence."  The use of the past tense forces one to choose the empty set as the interpretation of $S$ in 1775, if the sentence is to be translated faithfully.


Erro ao tentar unir 3 tabelas

Question: Estou tentando unir trés tabelas do meu banco de dados, sendo elas Propriedades | Licitacoes | Usuarios. Só que toda hora da o mesmo erro! ele é:
Fatal error: Call to a member function fetchAll() on a non-object in *** on line 61

O objetivo ao qual to tentando unir essa tabela é filtrar as informações na hora do echo, tanto que estou usando o WHERE no final do código. Quero que na hora que o usuário entrar na pagina em questão mostre apenas os resultados relacionado a ele, essa relação é dada pela licitacoes que o usuário possui e pelo Nivel que ele possui.
Já usei praticamente o mesmo código em outra ocasião e não deu nenhum erro parecido. Esse eu ja nao sei porque está dando! Podem me ajudar??
<?php
require_once "../conexao.php";
?>

<?php
$rs = $pdo->query(" SELECT a.ID as IDPROP, a.LICITI, a.NOME, a.NIVEL as NIPROP,
                           b.ID as IDLICI, b.ID_LICITI, b.ID_USER,
                           c.ID as IDCHAR, c.USUARIO, c.NIVEL as c.NICHAR

                    FROM propriedades a INNER JOIN licitacoes b on (a.LICITI = b.ID_LICITI)
                                        INNER JOIN usuario c on (b.ID_USER = c.ID)
                  ")->fetchAll();

if(!$rs){ print_r($pdo->errorInfo()); }foreach ($rs as $row){

?>

<?php echo $row['IDPROP'];?> = Informações da tabela propriedades
<?php echo $row['IDLICI'];?> = Informações da tabela licitacoes
<?php echo $row['IDCHAR'];?> = Informações da tabela usuario

<?php } ?>

Comment: @Lucas OBRIGADÃO. Esse ultimo erro que você falo solucionou o problema!
Comment: Tá faltando o `ON` no `INNER JOIN`, não? Tá aparecendo que erro?
Comment: Imprima a consulta e rode diretamente no banco veja se aparece algum erro.
Comment: @Lucas realmente tava faltando o ON, porem isso não resolveu! O erro eu listei na pergunta! "Fatal error: Call to a member function fetchAll() on a non-object in *** on line 61"
Comment: @rray rodar diretamente no banco? Como assim?
Comment: Esse acontence pq `query()` falhou normalmente é erro na consulta, logo não consegue encadear o `fetchAll()`. Quando a consulta falha é retornado o sql state que diz a mensagem de erro, 'categoria' e código.
Comment: Qual o erro do SQL eu quis dizer, desculpe
Comment: Seria jogar a consulta em uma variável e imprimi-la, depois testar no workbench ou phpmyadmin, `$sql = 'select ....'; echo $sql; $pdo->query($sql); ...`
Comment: To achando que é algum mal fechamento! Porque a pagina nunca termina de carrega, é como se estivesse em loop infinito
Comment: Ainda tá aparecendo o `Fatal error`, depois que tu colocou o `ON`?
Comment: @Lucas ta sim. O erro ta o mesmo!
Comment: Vi outro erro aí: `c.NIVEL as c.NICHAR `, remove esse último *alias*, fica só `c.NIVEL as NICHAR`
Comment: Show. Vou adicionar uma resposta.
Answer: Encontrei 2 erros no SQL: está faltando os ON nos INNTER JOIN e há um alias não necessário em c.NIVEL as c.NICHAR.
Segue o SQL correto:
SELECT a.ID as IDPROP, a.LICITI, a.NOME, a.NIVEL as NIPROP,
b.ID as IDLICI, b.ID_LICITI, b.ID_USER,
c.ID as IDCHAR, c.USUARIO, c.NIVEL as NICHAR
FROM propriedades a
INNER JOIN licitacoes b ON (a.LICITI = b.ID_LICITI)
INNER JOIN usuario c ON (b.ID_USER = c.ID)

Como o SQL estava incorreto, a função query() retornava false e tentava chamar direto fetchAll(), mas como false não é um objeto, o PHP lança esse Fatal error.
Para contornar esse tipo de situação, é interessante armazenar a consulta em uma variável e testá-la, por exemplo:
$res = $pdo->query('...');
if ($res === false) {
    // erro na consulta
} else {
    $lista = $res->fetchAll();
}

Erro ao tentar unir 3 tabelas


Python Code to count the font tags present in a webpage

Question: I need to count the number of font tags present.

Account #: 8428995632

Billing Date:
07-22-2013	Past Due Date:
08-12-2013

Service From:
06-11-2013	Service To:
07-11-2013	Days of Service:
30

Current Charges:    $30,488.60	Amount Due:    $30,488.60

 Meter readings for this bill:

Meter	Service
From	Service
To	# Days	Prior
Read	Current
Read	Consumption

S10406906	06-11-2013	07-11-2013	30	134	144	10

08400002	06-11-2013	07-11-2013	30	30748	32634	1886

S10406911	06-11-2013	07-11-2013	30	2717	3046	329

08405704	06-11-2013	07-11-2013	30	23755	25100	1345

S10406895	06-11-2013	07-11-2013	30	97	101	4

S10406893	06-11-2013	07-11-2013	30	7915	8406	491

<input type="hidden" name="BillId" value="842892230704" />

In this i need to count the number of font tags, if possible i need to count this pattern
8406491
Please not that after the font opening tag there is a number, that can be a dynamic one.
Thanks in advance
Comment: What have you tried so far? Post the python code you already have, elaborate on what is the actual problem you face.
Answer: Below is an example to count number of font tags in the html code:
soup = BeautifulSoup("file.html")
fontlist = soup.findAll('font')
print len(fontlist)


Equivalent in VB.NET to Add objects of T to a List(of T)

Question: This is my class
Public Class DBServer
    Public  ServerId  As Integer
    Public  ServerName As String
End Class

And Variable:
Dim serverList As New List(Of DBServer)

in C#. I can add like this:
serverList.Add(new DBServer{ ServerId=1,ServerName="Server1"});
How can I achieve this in VB.NET. I am using .NET 4.0.
Comment: Is `ServerName` supposed to be a String array?
Comment: What have you tried?  There are online C# to Visual Basic .NET converters you can use.  The syntax would nearly be identical I suggest looking at the MSDN VB.NET examples for List
Comment: actually it is not array. I tried and I got a conversion . but throws compilation error.
Answer: For a direct port, try
serverList.Add(new DBServer With { .ServerId=1,.ServerName="Server1"})

See Object Initializers: Named and Anonymous for more
Comment: @ken2k: Sorry I haven't compiled it, I translated it from memory. Is there a problem?
Comment: @ken2k: Just checked, builds correctly and works as expected :)
Answer: This is the correct direct translation from C# assuming that ServerName is actually a String array as posted (Note the extra curly brackets around the Servername initialiser):
serverlist.Add(New DBServer() With {.ServerId = 1, .ServerName = {"foo"}})

If Servername is not a string array and is in fact a string then @Binary Worrier has the correct solution:
serverlist.Add(New DBServer() With {.ServerId = 1, .ServerName = "foo"})

Answer: You can initialize a List with an Enumerable (http://msdn.microsoft.com/en-us/library/fkbw11z0)
    Dim serverList As New List(Of DBServer)({New DBServer With {.ServerId = 1, .ServerName = "Server One"},
                                             New DBServer With {.ServerId = 2, .ServerName = "Server Two"},
                                             New DBServer With {.ServerId = 3, .ServerName = "Server Three"}})

Comment: This cause Compile error. saying that we are giving one dimenstional array
Comment: Runs fine my side.  I suspect its actually because your property "ServerName" is an array of string rather than just a string.
Comment: actually it a string only not the array
Comment: Now that you've edited your question it is.  See Matt Wilko answer. With your update my example should be fine.


LESS 1.3.3, watch mode hogging a lot of CPU in espresso editor

Question: I was using an older version of less (1.2.1) by accident and when I updated the .js to the most recent version (1.3.3) it seems that Espresso, my html/css editor, now takes 40% cpu and up to 90% when in development/watch mode. I've tried other versions and it seems like it happens with 1.3.1+. I've tried different variations of the watch mode and even disabling it completely and it's still using 40-50% cpu. I basically can't work with it now.
edit: It seems like it's mostly being caused by watch mode, which I highly depend on :(
This is what my site head looks like. Any suggestions would be appreciated as I do not understand js at all.
<code><!doctype html>
<html>

<head>

<meta charset="utf-8"/>

<title>Article Sample</title>

<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!-- Adding "maximum-scale=1" fixes the Mobile Safari auto-zoom bug: http://filamentgroup.com/examples/iosScaleBug/ -->

<!-- Link directly to LESS stylesheet first -->
<link rel="stylesheet/less" href="style/default.less" type="text/css" media="screen" />
<link rel="stylesheet/less" href="style/tablet.less" type="text/css" media="screen" />
<link rel="stylesheet/less" href="style/mobile.less" type="text/css" media="screen" />
<link rel="stylesheet/less" href="style/wide-mobile.less" type="text/css" media="screen" />

<!-- Then link to LESS, and enable development watch mode -->
<script src="js/less-1.3.3.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
    less.env = "development";
    less.watch();
</script>
<!-- Voilà! Instant LESS previews in Espresso -->

<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->

</head>
</code>
Comment: after some monitoring of activity monitor it seems like most of the cpu usage spike comes from development/watch mode.
Answer: I think it is better to precompile first and then make the site read the already-compiled .css instead.
You can use Koala app for precompiling the less file or you can use grunt too, and get rid of the less.js.


How can I get information about coefficient std. error, t value and p value for Regularized Linear Model

Question: In R we can get a lot of information from summary model.
> summary(lm(mpg~wt+hp,data=mtcars))

Call:
lm(formula = mpg ~ wt + hp, data = mtcars)

Residuals:
   Min     1Q Median     3Q    Max
-3.941 -1.600 -0.182  1.050  5.854

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) 37.22727    1.59879  23.285  < 2e-16 ***
wt          -3.87783    0.63273  -6.129 1.12e-06 ***
hp          -0.03177    0.00903  -3.519  0.00145 **
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.593 on 29 degrees of freedom
Multiple R-squared:  0.8268,    Adjusted R-squared:  0.8148
F-statistic: 69.21 on 2 and 29 DF,  p-value: 9.109e-12

Are Std. Error, t value P value still meaningful in regularized case? and How can we get the information in addition to "coefficient estimate" in ridge or lasso regression?
Comment: I don't know if you get notified about my edits, but I've added a substantial bit more on ridge regression in GLMs.
Answer: ${\large \text{Section 1: Ridge regression with } \lambda \text{ known}}$
Linear Regression:
Under the assumption that $\lambda$ is known (which is a huge assumption) we can work out the distribution of the ridge regression estimator $\hat \beta_\lambda$ in an interpretable way.
We know that $\hat \beta_\lambda = (X^T X + \lambda I)^{-1} X^T Y$. Taking the SVD of $X$ we have $X = UDV^T$ so
$$
\hat \beta_\lambda = (V D^2 V^T + \lambda I)^{-1} V D U^T Y = V (D^2 + \lambda I)^{-1}D U^T Y
$$
$$
= V (D^2 + \lambda I)^{-1}D \left[DV^TVD^{-1} \right] U^T Y
$$
$$
= V (D^2 + \lambda I)^{-1}D^2V^T \left[VD^{-1}  U^T Y\right]
$$
$$
= V (D^2 + \lambda I)^{-1}D^2V^T \hat \beta.
$$
Letting $A_\lambda = V (D^2 + \lambda I)^{-1}D^2V^T$ we can see that we have
$$
\hat \beta_\lambda = A_\lambda \hat \beta \sim \mathcal N(A_\lambda \beta, \sigma^2 A_\lambda (X^T X)^{-1} A_\lambda).
$$
This means that $A_\lambda$ captures both the increase in bias that we've incurred and the corresponding reduction in variance, and we can see how it does so by shrinking $\beta$ along the smaller principal components.
Working out the variance we have
$$
A_\lambda (X^T X)^{-1} A_\lambda = V (D^2 + \lambda I)^{-2} D^2 V^T
$$
so
$$
\hat \beta_\lambda \sim \mathcal N\left(V (D^2 + \lambda I)^{-1}D^2V^T \beta, \sigma^2V (D^2 + \lambda I)^{-2} D^2 V^T\right).
$$
From this we can work out the usual tests since everything except $\beta$ and $\sigma^2$ is known in the above equation. It is important to note the role that the bias of $\hat \beta_\lambda$ plays in these tests, though, as described here for instance.
GLMs:
Here I'll discuss how to adapt the standard GLM procedure to handle an $L_2$ penalty on $\beta$. For a given $\lambda$ this will allow us to get $\hat \beta_\lambda$, and if we ignore uncertainty in $\lambda$ (i.e. assume it is known) we can then make inference about $\beta$. This is basically straight from McCullagh and Nelder's GLM book, so I'm going to be pretty light on details and just highlight how the addition of the penalty changes things.
We will maximize the penalized log-likelihood $l$ by Fisher scoring (which is equivalent to Newton-Raphson if the canonical link is used). This means that we iterate
$$
b^{(m+1)} = b^{(m)} - E\left( \frac{\partial l^2}{\partial \beta \partial \beta^T} \right)^{-1}_{(m)} \left(\frac{\partial l}{\partial \beta} \right)_{(m)}.
$$
Letting $A_{(m)} = - E\left( \frac{\partial l^2}{\partial \beta \partial \beta^T} \right)_{(m)}$ we have
$$
A_{(m)} b^{(m+1)} = A_{(m)} b^{(m)} + \left(\frac{\partial l}{\partial \beta} \right)_{(m)}.
$$
In the aforementioned McCullagh and Nelder, they show that for the unpenalized case $A_{(m)} = X^T W^{(m)} X$, with $W^{(m)}$ being the diagonal weight matrix, so for our case we have $A_{(m)} = X^T W^{(m)} X + \lambda I$.
Again in the unpenalized case, we can show that $\left(\frac{\partial l}{\partial \beta} \right)_{(m)} = X^T W^{(m)} G^{(m)} (Y - \mu^{(m)})$ for $G^{(m)}$ diagonal with $G^{(m)}_{ii} = g'(\mu^{(m)}_i)$. Now, with the penalty, we have $\left(\frac{\partial l}{\partial \beta} \right)_{(m)} = X^T W^{(m)} G^{(m)} (Y - \mu^{(m)}) - \lambda b^{(m)}$.
Putting this together, we have
$$
(X^T W^{(m)} X + \lambda I) b^{(m+1)} = (X^T W^{(m)} X + \lambda I) b^{(m)} + X^T W^{(m)} G^{(m)} (Y - \mu^{(m)}) - \lambda b^{(m)}
$$
$$
= X^T W^{(m)} (X b^{(m)} + G^{(m)}(Y - \mu^{(m)})) = X^T W^{(m)} (g(\mu^{(m)}) + G^{(m)}(Y - \mu^{(m)}))
$$
so we can see that this exactly corresponds to performing IRLS on the same working response as in the unpenalized case, except we simply use the weighted ridge regression estimator at each step rather than the unpenalized WLS estimator.
As for the variance and distribution of $\hat \beta_\lambda$, we can just get this from the final IRLS fit, so
$$
Var(\hat \beta_\lambda) = (X^T W X + \lambda I)^{-1} X^T W X (X^T W X + \lambda I)^{-1} = A I(\beta) A := \Sigma_\lambda
$$
where $I(\beta)$ is the observed information coming from the actual likelihood of $\beta$ (which is not penalized).
Since linear weighted ridge regression is just WLS on a modified data set, and WLS is an MLE, we have that $\hat \beta_\lambda$ is asymptotically normal with variance $\Sigma_\lambda$ and we can base hypothesis tests off of this. As before, the bias of $\hat \beta_\lambda$ needs to be remembered.
${\large \text{Section 2: } \lambda \text{ unknown}}$
More realistically, if we do not want to assume that $\lambda$ is known then the main techniques available to us (to the best of my knowledge) are the bootstrap and a Bayesian analysis. Since ridge regression corresponds to a normal prior on $\beta$, and the normal distribution is its own conjugate prior, we have that the MAP and posterior mean are the same, i.e. $\hat \beta_\lambda$ is both the MAP and the posterior mean. This should make Bayesian inference very tractable. For the bootstrap, we still have the bias issue so it should be used with care. More details to come.
${\large \text{Section 3: The lasso}}$
For the lasso things get tricky but I believe that this paper by Lockhart, Taylor, and the Tibshiranis addresses your question (although I must confess I have only skimmed it -- as I have time I'll flesh this section out more).
Comment: How do you account for uncertainty in the value of the parameter $\lambda$?
Comment: How about logistic regression?
Comment: Good points both. I'll follow up in a bit.
Comment: @hxd1011 If we assume that $\lambda$ is known I wonder if we could use the linear mode result on the last iteration of IRLS
Comment: @whuber you're very welcome; that was a very good point. Overall this has been a great excuse to really dig into all of this stuff.
Comment: This is an interesting topic and an active research area. [Here](http://feb.kuleuven.be/public/NDBAF45//postselection.htm) is a link to a recent workshop on the topic, there should be some interesting reads in the programme. My takeaway (a beginners perspective) was that confidence bounds for LASSO are wider than for vanilla regression. This is kind of funny knowing that LASSO would typically give a better balance w.r.t. the bias-variance trade-off. So if you want to predict, use LASSO; but if you want to do hypothesis testing, use vanilla regression (for higher power of the tests). Puzzling.
Comment: @RichardHardy interesting. Thanks for sharing the link. Hypothesis testing with the lasso seems like it might be more of a mathematical curiosity than a real statistically useful tool, but it's still a lot of fun to explore
Comment: @Chaconne, I have quite a different feeling about it. Once the effect of model selection on hypothesis testing is explicitly acknowledged, hypothesis testing for LASSO becomes not only a curiosity but a very relevant problem for many applied sciences.
Comment: @RichardHardy do you mean if we know the distribution of $\hat \beta(\hat \lambda)$, where $\hat \lambda$ is chosen in a potentially complex and data-dependent way, then the lasso might be useful as a standard inference tool?
Comment: @Chaconne, yes, I think so, as long as we can work out the distribution (which is challenging, but hopefully doable). I don't see why we should restrict the use of LASSO for forecasting and variable selection only. And since inference is typically done neglecting model selection, so one way or another we have to deal with it, and then why not using LASSO.
Comment: @RichardHardy fair point; seems like a good way to look at it. Relatedly, have you ever seen results for the distribution of $\hat \beta(\hat \lambda)$ in ridge regression with $\hat \lambda$ being chosen to optimize some out of sample measure of performance? I've done some searching but haven't found anything about inference in ridge regression with a data-dependent $\lambda$ (other than the bootstrap or a fully Bayesian analysis).
Comment: @Chaconne, no I am not aware of anything like that. It is an interesting topic, but unfortunately gravely under-researched.
Comment: @RichardHardy ok, well at least it's good to know that I haven't missed something famous. Thanks.
Comment: @Chaconne, Or we both missed that :)


Problemas ao mostrar duração em horas e minutos em PHP

Question: Estou tentando calcular uma duração entre valores de uma coluna no meu banco de dados. O valor até que está sendo calculado corretamente, mas acontece que o formato de hora:minuto não está saindo da maneira esperada.
Supondo que no meu banco de dados eu tenha a primeira duração que é de 1:30 e a segunda duração que é de 2:30, totalizará 04:00 horas, porém o que sai para mim em tela é 4:0 desse formato, como posso resolver?
Segue abaixo parte do meu código que faz a operação:
$query = mysql_query("SELECT ass.Duracao, pa.horas_dadas, pa.Horas_restantes, pa.Qtd_horas, ass.ID_Aluno, ass.ID_Pacote, ass.ID_Aula, pa.id_alunos FROM Assiste ass JOIN pacotes pa ON pa.ID=ass.ID_Pacote WHERE ID_Aluno = $pegaid AND ID_Pacote = $pegaid_pacote AND Status_presence = 'Ativa'");

while($row = mysql_fetch_array($query))
{
    $hora= $row['Duracao'];
    $show_qtd_horas = $row['Qtd_horas'];
    $hora1 = explode(":",$hora);
    $min_hora1 = ($hora1[0] * 3600) + ($hora1[1] * 60);
    $total=$total+$min_hora1;
}

$hora = floor($total / 3600);
$total = $total - ($hora * 3600);
$min = floor($total / 60)/10;
$min=str_replace(".","",$min);
$result_duracao=$hora.":".$min;

if(strlen($min)==1)
{
    $min=$min."0";
}

$update_pacotes = mysql_query("UPDATE pacotes SET horas_dadas='$result_duracao' WHERE id_alunos=$pegaid AND ID=$pegaid_pacote");

echo $result_duracao;

Comment: Como que está salvo a hora na coluna Duracao? já esta em algum formato? H:mm || segundos?
Answer:    while($row = mysql_fetch_array($query))
   {
     $hora= $row['Duracao'];
     $show_qtd_horas = $row['Qtd_horas'];
     $hora1 = explode(":",$hora);

     $min_hora1 = ($hora1[0] * 3600) + ($hora1[1] * 60);
     $total=$total+$min_hora1;
   }
     $hora = floor($total / 3600);
     $total = $total - ($hora * 3600);
     $min = floor($total / 60)/10;
     $min=str_replace(".","",$min);
     $result_duracao=$hora.":".$min;
     if(strlen($min)==1){
        $result_duracao=$result_duracao."0";
     }

      $testeHora = explode(":",$result_duracao);
      $lenHora= strlen($testeHora[0]);

      if($lenHora==1){
        $result_duracao="0".$result_duracao;
      }

1: No seu código altere  $min=$min."0"; para  $result_duracao=$result_duracao."0";
2: acrescente essas linhas no final do código antes do update.

 $testeHora = explode(":",$result_duracao);
 $lenHora= strlen($testeHora[0]);
    if($lenHora==1){
      $result_duracao="0".$result_duracao;
    }

que irá verificar se a parte da hora contém 1 ou 2 digitos. Caso tenha um digito irá concatenar com um 0 na frente.
Comment: Sua resposta foi a melhor, muito obrigado
Answer: Se o calculo esta correto você pode usar uma função 'date' nativa do php para exibir no padrão correto.
echo date('H:i', strtotime($nomedavariavel));

veja o exemplo utilizando o seu código no phpFiddle
Comment: Nao dá porque preciso mandar o dado para o banco de dados
Comment: não é para exibir em tela, preciso que este dado seja atualizado no banco
Comment: Salva uma variável com o resultado exemplo: $variavel_bd = date('H:m', strtotime($result_duracao));
Comment: Obrigado, tudo resolvido por aqui


Performance-enhancing drugs in cycling

Question: Why does everyone say elite cyclists are doping but none of them get caught even though they are regularly tested?
A perfect example is Lance Armstrong with the recent allegations.
Comment: I would recommend about reading this post - http://bicycling.about.com/od/professionalcycling/a/cheating.htm
Comment: @OutlawLemur, ah gotcha. I don't think doping in this context means those type of drugs, though those are banned as well. The doping referenced in the question are performance enhancing drugs - steroids, amphetamines, EPO, etc.
Comment: Also, it isn't like doping would make them better
Comment: @OutlawLemur, you don't think doping makes athletes perform better? If the drugs had no effect, why would they dope?
Comment: @JW8 Some drugs do... but I meant more like marijuana and drugs like that.
Comment: @JW8 Yes I understand
Answer: Basically, cheaters have an advantage over the testers - they pioneer new techniques or develop drugs that are designed to minimize the risk of detection. Further, the cheaters usually operate under a veil of secrecy - they don't want their efforts to be detected. For this reason, blood and urine samples are sometimes stored for years to allow more advanced tests to be run, once more advanced tests are developed.
The new drugs or techniques are usually detected in the end, frequently because a member of the inner circle confesses. Authorities may also successfully arrest members of these groups and confiscate material used to circumvent existing tests. However, these aids can provide their users an advantage over other competitors until a valid test is developed.
Comment: @Sancho, the quick answer is history. In one period, many top cyclists have either been busted or accused of doping - see Contador, Landis, and Ullrich as examples of past Tour de France winners that have been caught. Also see http://en.wikipedia.org/wiki/Doping_at_the_Tour_de_France for more info. This history leads many to believe that only dopers have a shot a winning - and that implies that any pro biker that wants to win HAS to dope, leading to this public perception.
Answer: Some forms of cheating are basically impossible to detect.  For example, blood doping (which is one of the things Lance Armstrong is accused of doing), where remove your own blood a few weeks to a month before a race, store it, and then transfuse into yourself during a race to help boost your red blood cell count.  Since it is your own blood, there are no chemical signatures to spot if you do it.  The only thing they can look at is your hematocrit (red blood cell count), but since they vary for different people and over time, they are forced to pick an arbitrary limit (50%).  But since the limit is arbitrary, cyclists just started blood doping right up to that limit, knowing they couldn't get caught.
Comment: Blood doping is detectable with a well-run biological passport system.

Performance-enhancing drugs in cycling


Using existential instantiation (logic)

Question: Am I using EI right on line 6? (Actually, I'm pretty sure the answer is 'no', and there's a few sketchy lines after that, too. So maybe you could also give a hint about how to do this).
Prove:

(∃x)(∀y)(Gxy → Hxy)     (Premise)
(∀x)(∃y)¬Hxy        (Premise)
<code>    ∴ ¬(∀x)(∀y)Gxy
</code>
(∀y)(Gay → Hay)     (1, Existential Instantiation)
Gab → Hab           (3, Universal Instantiation)
(∃y)¬Hay            (2, Universal Instantiation)
¬Hab                (5, Existential Instantiation)
¬Gab                (4, 6, Modus Tolens)
(∃y)¬Gay            (7, Existential Generalization)
¬(∀y)Gay            (8, Quantifier Negation)
(∃x)¬(∀y)Gxy        (9, Existential Generalization)
¬(∀x)(∀y)Gxy        (10, Quantifier Negation)
Comment: (6) is no good, because you introduced $b$ in (4). But you have essentially the right idea: just put (4) after (6)!
Comment: It would be very helpful if you tell explicitly in your question which system of logic you're working with, rather than leaving it to the reader to reconstruct it from _abbreviated_ names of rules.
Comment: @ZhenLin Please promote your comment to answer?
Answer: The below is verbatim from a comment by Zhen Lin, which was requested by the OP to be posted as an answer, but that wasn't done.
The primary intent of this answer is to remove this question from the Unanswered queue.

Zhen Lin wrote:

(6) is no good, because you introduced b in (4). But you have essentially the right idea: just put (4) after (6)!

Using existential instantiation (logic)


Wrong FQDN on Debian server

Question: I have defined the server's FQDN and its alias in /etc/hosts:
X.X.X.X server1.example.com server1

However, the command hostname --fqdn only returns the alias (server1) and not the FQDN. Why is that?
Comment: Is the `127.0.1.1` entry still defined in hosts file with the short name?  Is your server using the `127.0.1.1` option?  By default debian will setup the /etc/hosts with an entry like `127.0.1.1 fully.quallified.tld shortname`.
Answer: Have you changed /etc/hostname also? Did you restarted the network services after that change?
invoke-rc.d hostname.sh start
invoke-rc.d networking force-reload
invoke-rc.d network-manager force-reload

Without them, the server will still use the older one.
More info  can be found here.
Comment: I've restarted the whole server and the hostname still gets reset back to the alias.
Comment: Have you changed `/etc/hostname` too?
Comment: Yes, I have already done that.

Wrong FQDN on Debian server


Heaviside function & Integral Limits

Question: When considering integration, how does one use the Heaviside function in order to alter the limits of integration. For example
If i have
$$ \int_a^b f(x) dx $$
But want to change this integral to be over the range, for example $0$ to $\infty$, then how do i use the Heaviside to this?
From what i understand about graphing, H(x) is the line $y=1$ that begins at $0$ and goes to $+\infty$, or in this case $a$ to $b$.
Answer: $$\int_a^b{f(x)dx}=\int_a^{b}{f(x)[H(x-a)-H(x-b)]dx}=\int_0^{\infty}{f(x)[H(x-a)-H(x-b)]dx}$$
Comment: Could you elaborate on how you arrived at this conclusion?
Comment: If $H(x)=0$ for $x<0$ and $H(x)=1$ for $x>0$ then we have that $H(x-a)=0$   for $xa$ (similarly for $b$). Thus, $H(x-a)-H(x-b)=0$ for $x\in(-\infty,a)\cup(b,\infty)$ and  $H(x-a)-H(x-b)=1$ for $x\in(a,b)$.
Comment: Is $H(x−a)−H(x−b)=H(b-x)H(x−a)$, if so i understand.
Comment: @MathsPro Yes you can write it also like that.
Comment: As a final question, if one of the limits is already okay, i can just add the other? i.e if $b=\infty$ then i can just multiply the function by H(x-a)
Comment: @MathsPro Yes, correct.

Heaviside function & Integral Limits


wrong number of arguments (0 for 1) in a rails app with two models

Question: I keep getting 'a wrong number of arguments (0 for 1)' error and it seems like such a broad error that I can't seem to narrow down what the cause of it is.
I am making an appointment app that records a date range (start_date, end_date) in a table called Project.  When a new Project is created, a ProjectDate record is generated for every date in the range between start_date and end_date (ie. Feb.1 -Feb. 7 creates 7 ProjectDate records).
The line that the error appears on is: " if @project.update_attributes"
I'm fairly new to rails and so I don't really understand why it's not passing an argument.  My theory is that maybe I have the form_for url path wrong...but I don't know how.
Projects Controller (where the error appears)
def edit_date_range
 @project = Project.find(params[:p])
end

def update_date_range
 @project = Project.find(params[:p])
   if @project.update_attributes
    redirect_to  k1s3_path(:p => @project.id)
  else
   redirect_to  edit_date_range_path(:p => @project.id)
 end
end

Models
  class Project < ActiveRecord::Base
   has_many :project_dates, dependent: :destroy, inverse_of: :project
   accepts_nested_attributes_for :project_dates, allow_destroy: true

 after_update :add_and_remove_dates

def dates_in_date_range
  (self.prep_start.to_date .. self.prep_end.to_date.to_a)
end

def add_and_remove_dates
  dates.where('schedule_date < ? OR schedule_date > ?', start_date, end_date).destroy_all
  dates_in_date_range.each do |date|
  dates.find_or_create_by(schedule_date: date, available: true)
  end
end

  class ProjectDates < ActiveRecord::Base
    belongs_to :project, inverse_of: :project_dates

Table Structures
Project table structure
  :id
  :title (string)
  :start_date (date)
  :end_date(date)
  :status (boolean)

ProjectDates table structure
  :id
  :project_id (integer)
  :schedule_date (date)
  :available (boolean)

form
  <%= form_for @project, url: update_date_range_path(:p => @project.id) do |f| %>

  <%= f.hidden_field :org_start, :value => @project.start_date %>
  <%= f.hidden_field :org_end, :value => @project.end_date %>
  <%=  f.text_field  :end_date %>
  <%=  f.text_field  :start_date%>

  <%= f.submit 'SAVE CHANGES' %>

  <% end %>

Answer: You are not passing any parameters to the update_attributes method, which expects 1 param (usually a hash containing everything that needs to be updated). Hence the wrong number of arguments (0 for 1) error message.
Change:
if @project.update_attributes

to
if @project.update_attributes(project_params)

project_params would be the private method that sets the needed parameters as required
private
def project_params
   params.require(:project).permit(<attr1>, <attr2>, <attr3>...)
end

Comment: `ActiveModel::ForbiddenAttributesError` is because of not marking the parameters as required. See http://stackoverflow.com/questions/17335329/activemodelforbiddenattributeserror-when-creating-new-user
Comment: That gives me this:" ActiveModel::ForbiddenAttributesError "
Comment: I checked and I am passing params into the method...this is where I'm confused.
Comment: I'm using   params.require(:project).permit! , so they should all be good.
Comment: I am already using def project_params
   params.require(:project).permit!
end
Comment: Thank you. That fixed that error.  I have another...but it's not related.


Implicit differentiation

Question: I need to find the derivatives of
$(1+xy)^3 =yx^{-1} $
I tried this and stuck
$3(1+xy)^2 (0+ x(\frac{dy}{dx}) + y ) = -yx^{-2} + (x^{-1} \frac{dy}{dx} ) $
$\frac{dy}{dx} (x+y-x^{-1}) = -yx^{-2} - 3(1+xy)^2 $
$\frac{dy}{dx} = \frac{-yx^2-3(1+xy)^2}{x+y-x^{-1}} $
I'm not quite sure how to simplify it to achieve the final answer -
$\frac{-y(3x^2(1+xy)^2+1}{x(3x^2(1+xy)^2-1} $
Comment: take logarithm at both sides D: of your equation
Comment: You have a mistake in the third equation ... Ping me, if you want some help.
Comment: @JoseGarcia is there anyway to avoid using logarithm for this ? Because I haven't learnt it and I need to use the basic rules to solve this
Answer: Applying the $d$ operator to both sides as I think you have done we have
$$
3(1+xy)^2(y+xy')=y'\frac{1}{x}-\frac{y}{x^2}\implies 3y(1+xy)^2+3x(1+xy)^2y'=y'\frac{1}{x}-\frac{y}{x^2}
$$
which we can solve for $y'$ as follows
$$
y'(\frac{1}{x}-3x(1+xy)^2)=3y(1+xy)^2+\frac{y}{x^2}\\
\implies y'=\frac{3y(1+xy)^2+\frac{y}{x^2}}{\frac{1}{x}-3x(1+xy)^2}=
\frac{3x^2y(1+xy)^2+y}{x-3x^3(1+xy)^2}
$$
Comment: I don't quite understand the second line in the first part . How did the 3y and 3x appear and how (y+xy') become (1+xy)^2
Comment: He is applying the chain rule to take $$\frac{d}{dx}(1+xy)^3.$$ If we write $$f(x,y)=1+xy$$ then we have $$\frac{d}{dx}(f(x,y))^3=3(f(x,y))^2\left(\frac{d}{dx}f(x,y)\cdot\frac{d}{dx}x+\frac{d}{dy}f(x,y)\cdot\frac{d}{dx}y\right).$$ Note that $$\frac{d}{dx}f(x,y)=y$$ and $$\frac{d}{dy}f(x,y)=x$$ (check this for yourself), so we get $$\frac{d}{dx}(f(x,y))^3=3(1+xy)^2(y+xy').$$ From here, he distributes over the addition in the second parentheses to get $$3(1+xy)^2y+3(1+xy)^2xy'.$$ He just rearranged this to look like above: $$3y(1+xy)^2+3x(1+xy)^2y'.$$

Implicit differentiation


Ultra limit of sequence is bounded implies sequence is bounded, analogous to convergence

Question: Fix a non principal ultra filter $\omega$ on $\mathbb{N}$.
Assume $(a_n)_n\subseteq \mathbb{R}$ such that $\lim_{n\rightarrow \omega}a_n <\infty$. Does it follow that $(a_n)_n$ is bounded by a finite value?
Comments: Put $a=\lim_{n\rightarrow \omega} a_n$. For $\epsilon=1$, consider $S_1= \{n: |a_n-a|<1\}$.
Then, $\omega(S_1)=1$ and $S_1$ is infinite. Hence for all $n\in S_1$, $|a_n|\leq |a|+1$
Thus it remains to show that $\mathbb{N}\backslash S_1$ is finite.
Comment:
Clearly, $\omega(N\backslash S_1)=0$, but this does not imply that $\mathbb{N}\backslash S_1$ is finite.
Answer: This does not follow.
Take a non-principal ultrafilter $\omega$  on $\mathbb{N}$ such that $\omega(2 \mathbb{N}) = 1$ and consider the sequence $x_n$ defined by
$x_{2n} = 0$ and $x_{2n+1} = 2n+1$. Clearly $x_n$ is unbounded and yet its $\omega$-limit is $0$.
In fact, since every non-principal ultrafilter on $\mathbb{N}$ contains either the set of odd numbers or the set of even numbers, this idea shows that an example of this type exists for every choice of $\omega$.


Converter uma string em inteiro no SQLite

Question: Prezados estou tentando criar uma sql para um aplicativo móvel, a sql está tudo bem mas à aplicação dá o seguinte erro na hora de executar: "campo esperando uma string e atual é inteiro", a pergunta é como faço para converter o campo "icone" da sql para inteiro, segue sql:
select
    l.*,
    c.descricao as categoria,
    case when l.tipo_lancamento = 'c' then 1 else 0 end as icone
from
    tab_lancamento l
join
    tab_categoria c on (c.id_categoria = l.id_categoria)

O campo tipo_lancamento é um varchar mas, mas já mudei para um integer mas continua dando de de incompatibilidade
Desde já Agradeço!!!
Comment: Qual é o tipo do campo `tipo_lancamento` na tabela  `tab_lancamento` ? você poderia postar a estrutura das tabelas ?
Comment: O campo tipo_lancamento é um varchar mas, mas já mudei para um integer mas continua dando de de incompatibilidade
Comment: 1) Se o campo `tipo_lancamento` é um inteiro, qual o motivo de compara-lo com um `c` ? 2) Você parece estar usando uma espécie de acento agudo para delimitar o `c`, tente usar aspas simples.
Answer: Assumindo que sua Estrutura seja similar ao seguinte:
CREATE TABLE tab_lancamento
(
    id_lancamento integer,
    id_categoria integer,
    tipo_lancamento character varying(1)
);

CREATE TABLE tab_categoria
(
    id_categoria integer,
    descricao text
);

Dados:
INSERT INTO tab_categoria ( id_categoria, descricao ) VALUES ( 1, 'Primeira Categoria' );
INSERT INTO tab_categoria ( id_categoria, descricao ) VALUES ( 2, 'Segunda Categoria' );
INSERT INTO tab_categoria ( id_categoria, descricao ) VALUES ( 3, 'Terceira Categoria' );

INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 1, 1, 'a' );
INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 2, 2, 'c' );
INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 3, 3, 'c' );
INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 4, 1, 'a' );
INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 5, 2, 'b' );
INSERT INTO tab_lancamento ( id_lancamento, id_categoria, tipo_lancamento ) VALUES ( 6, 3, 'c' );

A seguinte consulta deverá funcionar:
SELECT
    l.*,
    c.descricao AS categoria,
    (CASE WHEN l.tipo_lancamento = 'c' THEN 1 ELSE 0 END) AS icone
FROM
    tab_lancamento l
JOIN
    tab_categoria c ON ( c.id_categoria = l.id_categoria );

Saída:
id_lancamento  id_categoria  tipo_lancamento  categoria           icone
-------------  ------------  ---------------  ------------------  ----------
1              1             a                Primeira Categoria  0
2              2             c                Segunda Categoria   1
3              3             c                Terceira Categoria  1
4              1             a                Primeira Categoria  0
5              2             b                Segunda Categoria   0
6              3             c                Terceira Categoria  1


Limit of an integral with an x border

Question: How to evaluate this limit?
$$\lim_{x\to0}\frac{\int_{0}^{x}\sin(u^3)\;\text{du}}{x^4}$$
where the whole integral is under $x^4$
Comment: can you use $$\LaTeX$$ please?
Comment: is it $$\lim_{x->0}(\int_{0}^{x}sinu^3du)/x^4$$?
Comment: the searched Limit should be $$\frac{1}{4}$$
Comment: Ok, i thought i used it. thanks for your help!
Answer: By the Fundamental Theorem of Calculus, write
$$\int_0^x \sin u^3\,du=F(x)-F(0)\;,\;\;\text{with}\;\;F'(t)=\sin t^3\implies$$
$$\lim_{x\to0}\frac{F(x)-F(0)}{x^4}\stackrel{\text{l'Hospital}}=\lim_{x\to0}\frac{\sin x^3}{4x^3}=\frac14$$
Answer: Note that both the numerator and the denominator approach zero as $x\to 0$. Thus, we can use L'Hôpital's Rule and take the derivative of both individually. The Fundamental Theorem of Calculus allows us to simplify the integral in the numerator.
$$\lim_{x\to 0}\frac{\int_0^x\sin u^3du}{x^4}=\lim_{x\to 0}\frac{\frac d{dx}\left(\int_0^x\sin u^3du\right)}{\frac d{dx}(x^4)}=\lim_{x\to 0}\frac{\sin x^3du}{4x^3}$$
Again, both numertor and denominator approach $0$. We can thus apply L'Hôpital's rule one more time.
$$\lim_{x\to 0}\frac{\sin x^3du}{4x^3}=\lim_{x\to 0}\frac{\frac d{dx}\left(\sin u^3du\right)}{\frac d{dx}(4x^3)}=\lim_{x\to 0}\frac{3x^2\cos x^3du}{12x^2}=\lim_{x\to 0}\frac 14\cos x^3=\frac 14$$
Comment: very well explained. Thank you!

Limit of an integral with an x border