How should play be restarted after a player swings their boot near an opponent's head?

Question: Referees have stopped play for a high boot when nearby opponents are challenging with their head, whether or not it there is contact. And in the past, bicycle goals have been disallowed due to the risk of injuring another player.
How should play be restarted after these stoppages of play? Would it count as a foul, and is it cautionable?
Comment: I've edited the title of this question. Previously it read as "how do referees restart play after an indirect free kick offence?" which sort of answers itself. I believe the real question you asked is how play is restarted after "high boot" offences.
Answer: If no contact has been made with the opponent, play is restarted with an indirect free kick from where the foul occurred (Law 12.2):

An indirect free kick is awarded if a player:

plays in a dangerous manner

Otherwise, a direct free kick or penalty kick must be awarded to the opposing team (Law 12.1):

If an offence involves contact it is penalised by a direct free kick or penalty kick.

A yellow card is usually not required for dangerous play; but the referee may still caution the offender if the action is made with obvious risk of injury. However a player must be sent-off if they deny an obvious goal-scoring opportunity to the opposing team by playing in a dangerous manner.
Answer: There is no such offence as "high boot". However, if a player swings their boot near an opponent's head without contact occurring, there are two offences that may have been committed.
If contact has occurred, it's just a regular carelessly / recklessly / excessively forcefully kicks an opponent offence, which results in a direct free-kick or penalty kick like most other fouls.
The tl;dr is -

If the opponent is forced to not play the ball to avoid potential injury, an indirect free kick is awarded for playing in a dangerous manner.
If the swinging foot is a near-miss, even if the opponent has not pulled out of the challenge, a direct free kick may be awarded. Depending on the severity of the challenge, a caution or send-off may be issued.
If either of the above offences occurs and:

a promising attack is broken up, the player committing the offence is cautioned for unsporting behaviour; or
an obvious goalscoring opportunity is denied, the player committing the offence is sent off.

The first offence is playing in a dangerous manner. Law 12.2 states:

An indirect free kick is awarded if a player:

plays in a dangerous manner

...
Playing in a dangerous manner is any action that, while trying to play the ball, threatens injury to someone (including the player themself) and includes preventing a nearby opponent from playing the ball for fear of injury.
A scissors or bicycle kick is permissible provided that it is not dangerous to an opponent.

As seen there are two elements to this offence, the first is:

a player does something that places either themselves, a teammate, or an opponent at risk injury
a nearby opponent avoids playing the ball in order to avoid injuring whoever it is that has been put at risk of injury.

Here are some examples of what would constitute playing in a dangerous manner:

A red player attempts to kick a ball at head height, close to the face of a blue player. The blue player avoids playing the ball to avoid being kicked in the face.
A red player falls on the ground, landing on top of the ball. The red player continues to lay on the ball, making no real effort to get up. A blue player avoids kicking at the ball so that they do not kick the red player.
A red player dives head first at a shin height ball to play it. A blue player, who otherwise would have been able to clear the ball, avoids kicking the ball so that they do not kick the red defender in the face.

In all of the above examples, the red player has committed the offence of playing in a dangerous manner.
As counterexamples, here are two incidents that are not playing in a dangerous manner, but are often incorrectly called as such:

A red player kicks at a ball at head height near a blue player's face. There is no contact, and the blue player manages to get a head to it first. The blue player then loses control of the ball and begins appealing for a "high boot". There is no offence, as the blue player was not prevented from playing the ball.
A red player falls on the ground, and begins flailing at a nearby ball whilst lying on their back. A blue player rushes in and attempts to play at the ball, before the red player manages to kick it away. There is no offence, as the blue player was not prevented from playing the ball.

If the referee believes a player has committed the offence of playing in a dangerous manner, the restart is an indirect free kick to the opponents.
Note: if contact occurs, the foul must not be sanctioned as playing in a dangerous manner, and a direct free kick offence should be considered instead.

The second offence is carelessly, recklessly, or excessive forcefully tackling or challenging an opponent. Law 12.1:

A direct free kick is awarded if a player commits any of the following offences against an opponent in a manner considered by the referee to be careless, reckless or using excessive force:
...

tackles or challenges

...

In 2016/17, the word "challenges" was added to this offence, to indicate that referees should not just be looking at "tackles", but all contests for the ball. Given the definitions of careless, reckless and excessive force, it seems plausible that swinging a foot within centimetres of an opponent's head as they're trying to play the ball, resulting in a near-miss, could be considered careless at the very least.
The other advantage of taking this approach, is that the referee does not need to wait and see if the opponent is prevented from playing the ball by the challenge. As soon as the challenge occurs, as long as it is careless, reckless, or excessively forceful the direct free kick may be awarded.
As described in this answer, if the challenge is careless, just the direct free kick is awarded; if reckless, the player concerned is also cautioned for unsporting behaviour. Finally, if there is excessive force, the player concerned is sent-off for serious foul play (assuming it was a challenge for the ball).

No matter which solution the referee uses to deal with players swinging boots near an opponent's head, the tactical nature of the offence (as with any offence) should be considered.
If the offence breaks up a promising attack, the player is cautioned for unsporting behaviour.
If the offence results in an obvious goalscoring opportunity being denied, the player is sent-off.
Law 12.3:

There are different circumstances when a player must be cautioned for unsporting behaviour including if a player:
...

commits a foul or handles the ball to interfere with or stop a promising attack

...
A player, substitute or substituted player who commits any of the following offences is sent off:
...

denying an obvious goal-scoring opportunity to an opponent moving towards the opponents' goal by an offence punishable by a free kick (unless as outlined below)

...


foreach loop error message

Question: Anyone know why the following code:
foreach (Word.XMLSchemaReference reference in Globals.ThisDocument.Application.ActiveDocument)
{

}

Gives me:

Error 1   foreach statement cannot operate on variables of type
  'Microsoft.Office.Interop.Word.Document' because
  'Microsoft.Office.Interop.Word.Document' does not contain a public
  definition for 'GetEnumerator'    C:\Program Files\Microsoft
  Office\Templates\Projects\Project1\Project1\ActionsPaneControl1.cs    1054    13  Project1

I have that code in an actionpane control in a Word document level project which has been created with VS2013 using C# .Net 4.0 for Word 2010.
I am trying to run the following code within that loop:
if (reference.NamespaceURI.Contains("ActionsPane"))
{
reference.Delete();
}

Basically, the documents created with my addin give the user a message when they reopen the created document:

One or more XML expansion packs are available for this file. Choose
  one from the list below. No XML expansion pack Microsoft Actions Pane
  3

So it seems I need to find the reference and delete it before the user saves the document?
Comment: This message says that `Globals.ThisDocument.Application.ActiveDocument` isn't an enumerable collection, so you can't enumerate through it with `foreach`
Comment: How would I get around this issue?  I want to `    if (reference.NamespaceURI.Contains("ActionsPane"))
      {
        reference.Delete();
      }`.
Comment: Then updated part of code doesn't matter. The error is in `foreach` statement. The `ActiveDocument` is NOT a collection, so you can't iterate through it - just like you CAN iterate through `List`, but CAN'T iterate through `double`. You need to find a property in `ActiveDocument` class, which contains a collection you need.
Comment: In my answer below - use the ActiveDocument.XMLSchemaReferences collection
Answer: The message is very clear: Globals.ThisDocument.Application.ActiveDocument does not implement IEnumerable. I think you are looking for something in the active document that implements a IEnumerable of XMLSchemaReference. Check the properties from the Globals.ThisDocument.Application.ActiveDocument.
Comment: Updated question with purpose of loop.
Answer: You're trying to enumerate over ActiveDocument. Are you trying to enumerate over the XML schemas?
foreach (var schema In ActiveDocument.XMLSchemaReferences){
    schema.dosomething
}

Comment: why have I just been downvoted for providing an answer?
Comment: Updated my question with further much needed details.
Comment: I still think you are trying to enumerate over the wrong thing. Try the above code
Comment: The foreach part now works, but it doesn't have a .delete command to delete any found schemas.
Comment: I'm using Word 2003 and I have a Delete() method on the reference - uppercase D.
Comment: Maybe I'm using the wrong thing, I type `schema.Delete();` and get `Error 1 'object' does not contain a definition for 'Delete' and no extension method 'Delete' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference)`
Comment: It looks like your schema reference is a generic object type. Try casting it to XMLSchemaReference - ((XMLSchemaReference)schema).Delete() - or change the "var schema" to "XMLSchemaReference schema".
Comment: OK, the code now works, but it still displays `One or more XML expansion packs are available for this file. Choose one from the list below. No XML expansion pack Microsoft Actions Pane 3` when opening the documents created with my action pane.
Comment: Policing peoples comments seems to be an obsession with some people, rather than spending time answering the question.

foreach loop error message


The locus of points with given sum of squares of distances to two fixed points

Question:
$A(a,b)$ and $B(b,-a)$ are two fixed points. If $P(x,y)$ is a moving point such that $$|AP|^2 + |PB|^2 = |AB|^2 \tag1$$  prove that $x^2 + y^2 =(b-a)(x+y)$.

So far I tried to use distance formula in the equation (1). But at the end I could not get the desired outcome. And I think I am not wrong, as it seems to me that it is the only way to solve the problem. Also, could anybody explain to me analytically, when the question says $P(x,y)$ is a moving point.
Answer: for P satisfies the condition:
$$(x-a)^2+(y-b)^2+(x-b)^2+(y+a)^2=(a-b)^2+(a+b)^2$$
Solve:
$$(x^2+a^2-2ax)+(y^2+b^2-2bx)+(x^2+b^2-2bx)+(y^2+a^2+2ay)=2a^2+2b^2$$
$$- a x - 2 b x +  x^2 +  a y +  y^2 = 0$$
$$\left(x-\frac{a+2b}2\right)^2+(y+a/2)^2=\left(\frac{\sqrt{2a^2+4b^2+4ab}}{2}\right)^2$$
The last equation is the locus of point P which apparently is a circle.
Comment: Where is $b$ now ? I enjoy when I notice that I am able to find small typo's. Cheers :-)


Simulate behavior of  element

Question: I have something like:

text	...

I need to enable user to click on entire table row to navigate on that link.
Now I use the following code:
$(function () {
    $('tr').each(function () {
        var tr = $(this);
        if (tr.hasClass('no-row-link')) return;
        var links = $('a', tr);
        if (links.length != 1) return;
        tr.addClass('row-link').click(rowLinkClick);
    });

    function rowLinkClick() {
        var tr = $(this);
        var links = $('a', tr);
        if (links.length != 1) return;
        window.location = links.attr('href');
    }
});

but the problem is, this behaviour is not working very nice. User can command-click on normal link to open page in new tab, but he can't here. User can right-click on normal link to view link context menu, but he can't here.
The only way I can do what I want is to iterate throw table cells (th/td) and wrap their contents on links. And then make those links behave with display:block. This isn't very elegant solution. Is there any other solutions for that?
Answer: How about using a data-attribute on your rows?

Then in jQuery:
$('.table-selector').on('click', 'tr', function(){
    var href = $(this).data('href');

    if (href){
        window.location = href;
    }
});

It certainly looks more elegant, don't you think? ^^
UPDATE:
Ah, the right click behavior ... kk
tr { position: relative; }
tr a { position: absolute; display: block; width: 100%; height: 30px/*or something*/ }

CSS solution, not sure about the flexibility of your table but if possible ... here's a DEMO of how I would try it.
Comment: Looks like elegance is subjective ... care to comment on the downvotes?
Comment: Indeed this is a more elegant way to simulate the linking, but does not answer the actual question of how to simulate the right-click behaviour of showing a context menu that allows users to open the link in a new tab.
Comment: Btw: You can create a custom context menu for your simulated a tags using the 'contextmenu' event and some custom markup (see [here](http://stackoverflow.com/questions/4495626/making-custom-right-click-context-menus-for-my-web-app)) in which you can add a `` link. However, as this needs a lot of work and the new tab functionality is only one of the many options of the default context menu I would say the cleanest method is still to wrap the cells in `` tags and use CSS to style them properly.
Comment: wrapping cells in a tags doesn't sound "great" imho
Comment: As you do not want to have an a tag in the cell but want the whole cell to be a link I think its semantically ok. In the end I would't mind though, but from experience feel that the styling to get the whole cell clickable is much simpler when it is wrapped.
Comment: Imho opinion that's the whole bottleneck. It's not semantically ok at all. Then better go for a simulated `div` structure which acts as a table by setting the proper `display` in css.
Comment: I decided to run a little JavaScript snippet which surrounds every `` content with `` tag and styles this `` tag do it grows to entire `` area.
Answer: You can check the e.ctrlKey property and either use window.navigate or window.open accordingly:
$(function () {
    function rowLinkClick(e) {
        var href = $(this).find('a').attr('href');
        if (href) {
            (e.ctrlKey ? window.open : window.navigate)(href);
        }
    }

    $('tr')
        .not('.no-row-link')
        .has('a')
        .addClass('row-link')
        .click(rowLinkClick);
});

And you can use CSS to show a link-like mouse cursor:
.row-link {
    cursor: pointer;
}

http://jsfiddle.net/zmr6whjh/2/
I think having a right-click on the row show the context menu for the link might be a bit much. I'm not sure there's a sensible way to do that.

Simulate behavior of  element


Webserver Multiple Gateways

Question: I have Ubuntu Server 12.04
I have 3 gateways on my lan
10.0.0.1
10.0.0.2
10.0.0.3

Ubuntu has 3 NICs
eth0 10.0.0.60 gw 10.0.0.1
eth1 10.0.0.61 gw 10.0.0.2
eth2 10.0.0.62 gw 10.0.0.3

If a request comes in from gw 10.0.0.1 it work fine.
the other gateways don't
I have tried to fix this with routes but I can't seem to get it right.
My ISP can only give 10Mbps up per modem the server streams a live video feed. I need all 3 modems for load balancing
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.0.0.3        0.0.0.0         UG    100    0        0 eth0
10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 eth1
10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 eth2
10.0.0.0        0.0.0.0         255.255.255.0   U     0      0        0 eth0

If this could be done with one NIC I am fine with that I just need to be able to balance this traffic.
I tried this (but all networking stopped after):
#echo "60 out60" >> /etc/iproute2/rt_tables
#echo "61 out61" >> /etc/iproute2/rt_tables
#echo "62 out62" >> /etc/iproute2/rt_tables

#ip route add default via 10.0.0.1 table out60
#ip route add default via 10.0.0.2 table out61
#ip route add default via 10.0.0.3 table out62

#ip rule add from 10.0.0.60 table out60
#ip rule add from 10.0.0.61 table out61
#ip rule add from 10.0.0.62 table out62

This Diagram doesn't have the server in question its just so you can see the network layout.
Network Diagram
http://22.214.171.124/netdiag.png

Comment: Why do you have three gateways for a web server?
Comment: Wut... where is all the traffic going? Why three gateways?
Comment: My ISP can only give 10Mbps up per modem the server streams a live video feed. I need all 3 modems for load balancing.
Comment: What does you routing table look like? You might have to configure each one to be on a separate subnet.
Comment: This network is in a production environment. I can't change the design of the network, only the server its self.
Comment: You need to setup PBR
Comment: Could you change gw ip addresses (10.0.0.1/10.0.0.2/10.0.0.3) on the modems?
Comment: Try disabling rp_filter
Comment: No, you don't need 3 modems. You need to host this in a datacenter and get a proper connection.
Comment: A datacenter is in the future just maxing out the resources I have first.
Answer: I will strongly recommend to change subnet. It's very bad idea to use the same subnet for all interfaces and their gateways, imho
I would suggest to use something like the following
eth0 10.0.1.61 gw 10.0.1.1
eth1 10.0.2.62 gw 10.0.2.1
eth2 10.0.3.63 gw 10.0.3.1

You could try to setup PBR, but I don't know, if it would work in your environment
#!/bin/sh

IP1='10.0.0.60'
IF1='eth0'
GW1='10.0.0.1'
P1_NET='10.0.0.0/24'

IP2='10.0.0.61'
IF2='eth1'
GW2='10.0.0.2'
P2_NET='10.0.0.0/24'

IP3='10.0.0.62'
IF3='eth2'
GW3='10.0.0.3'
P3_NET='10.0.0.0/24'

/sbin/ip route add $P1_NET dev $IF1 src $IP1 table ISP1
/sbin/ip route add default via $GW1 table ISP1

/sbin/ip route add $P2_NET dev $IF2 src $IP2 table ISP2
/sbin/ip route add default via $GW2 table ISP2

/sbin/ip route add $P3_NET dev $IF3 src $IP3 table ISP3
/sbin/ip route add default via $GW3 table ISP3

/sbin/ip rule add from $IP1 table ISP1
/sbin/ip rule add from $IP2 table ISP2
/sbin/ip rule add from $IP3 table ISP3

/sbin/ip route add default via $P1
/sbin/ip route flush cache

Don't forget to enable ip forwarding and disable Reverse Path Filtering
# echo 1 > /proc/sys/net/ipv4/ip_forward
# echo 0 > /proc/sys/net/ipv4/conf/default/rp_filter

Comment: I can not modify the network. I have many other production systems running on this network.
Comment: I will try this again, but last I tried it broke networking.
Comment: $ sudo ip route add 10.0.0.0/24 dev eth0 src 10.0.0.60 table ISP1
RTNETLINK answers: Invalid argument
Comment: I removed the scr field from this command, it ran successfully but didn't work in the end
`# ip route add 10.0.0.0/24 dev eth2 table ISP3`
Comment: Did you add ISP1/ISP2/ISP3 to the /etc/iproute2/rt_tables ?
Comment: yes i added
`1 ISP1
2 ISP2
3 ISP3`
Comment: According to the Network Diagram that you have provided, I don't understand, where is web server himself? And 3 servers at the bottom of the diagram are they 3 different physical servers?
Comment: The server is actually a virtual server on one of those physical servers.
Answer: The confusion expressed in the comments stems from this Private Class A LAN networking scheme being not very conventional or common in practice. Usually each net block is (a /28,/16 etc.) is broken up and the gateway set to the first usable IP. In this case it looks like each modem is a /31.
Paste output of route -n or netstat -nra (should work on most *nix variants)  if you're interested as to what gateway each interface believes it has, for further diagnosis.

Webserver Multiple Gateways


Octave changes on 2nd time

Question: Suppose a piece of music contain two subsequent parts than differ only by octaves (say, second part is entirely 8va). Is there any way to show this in sheet music, except by writing each part separately? In other words, how to show that the 2nd repetition of a part should be 8va (8vb, 15va, 15vb)?
Additional question: How to show that only one stave of the system (usually treble) should be 8va (8vb, 15va, 15vb)?
This is popular in music. For example, most piano pieces of Yann Tiersen for the movie Amélie.
Answer: There are a couple of ways to achieve this. If a whole section of music in a particular part is to be played an octave higher when repeated, simply use text. Something like "8va 2nd time" at the beginning of the passage you want an octave higher, is perfectly clear. You could use a dotted line to show the exact group of notes to be played an octave higher if necessary. If you only want a few notes in a part to be played an octave higher on a repeat, you could add these notes above the notes to be played the first time, and make the note size smaller or bracket the noteheads. You could also then use text to be absolutely clear, for instance by adding something like "2nd time" above the first bracketed note. However, this use of small or bracketed notes, for a change on a repeat, is fairly common, so the text may not be necessary. Having said that, it is often useful to use a short amount of text to make your meaning clear.
If it is not clear when the player should return to playing at pitch, for instance if it is not simply after the repeated section, you use the term loco to show that the music is to played at the written pitch.
Also, to answer your additional question, the markings above would be understood to only apply to one instrument, and so one stave, in a score, if the instrument only uses a single stave. This is the case for most instruments in a score. Piano, harp and other keyboard instruments, on the other hand, are examples of instruments using two staves; in this case you need to use a dotted line to make it clear which stave has the octave adjusted. If only a text marking of "8va 2nd time" we're put above a section of piano music, it wouldn't be clear if this applies to both staves or just one.
Comment: Thank you. I thought about any special symbols/words for this cases when asked the question. But if I can freely use human language then I can just write "entirely 8va 2nd time", "treble stave 8va 2nd time".
Answer: Put something like
<code>(2. 8va)
</code>
over the start of the repeat.  This kind of notation is pretty common.  If the 1st repeat has a change from the material before, this is usually written as
<code>8va (2. loco)
</code>
Where "loco" does not mean to play a crazy repeat but merely one without 8va.

Octave changes on 2nd time


static method to calculate multiple values

Question: I have this code:
    class Square {
        constructor(side) {
            this.side = side;
        }
    }

    class Rectangle {
        constructor(width, height) {
            this.width = width;
            this.height = height;
        }
    }

    class calcMe {

    }

    const square = new Square(4);
    const rectangle = new Rectangle(4, 2);
    const circle = new Circle(5);

    console.log(calcMe.calculate(square));
    console.log(calcMe.calculate(rectangle));

And I want to make a static method that can calculate the area of these shapes. How can I tell this to the static method? My attempt is:
class AreaCalculator {
    static calculate(val) {
        for (let key in val) {
            if (key === 'side') {
                return console.log(`L'area del quadrato è ${val.side * val.side}`)
            } else {
                if (key === 'width') {
                    return console.log(`L'area del rettangolo è ${val.width * val.height}`)
                } else {
                    if (key === 'radius') {
                        return console.log(`L'area del cerchio è ${val.radius * val.radius * Math.PI}`)
                    }
                }
            }
        }
    }
}

But is obviously wrong, even if I can console log the correct results. Can anyone can point me into the right direction? How can I have access to all the shapes values to return the correct calculation?
Comment: It would be better to encapsulate the area calculation logic within the shape object itself as it is the shape itself that should know how to calculate its own area. You would then have something like circle.area(), square.area() etc
Comment: Question: why a seperate class for squares? Surely that could just be a variant of rectangle where the constructor has one parameter?
Comment: Style comment: Don't use nested `else { if ... }` use `else if`.
Answer: It would be better to encapsulate the area calculation logic within the shape object itself as it is the shape itself that should know how to calculate its own area. You would then have something like circle.area(), square.area() etc
e.g.
class Square {
    constructor(side) {
        this.side = side;
    }

    area() {
        return this.side * this.side;
    }
}

const square = new Square(4);
const squareArea = square.area();

Answer: It is definitely easier to use instance methods to do the calculation for each type of object.
Not sure about what you want or the second part. One thing about the methods defined in the class body is that they will be assigned to the class prototype. So here is some possible solution.

    class Square {
        constructor(side) {
            this.side = side;
        }
        area(){
          return this.side * this.side;
        }
    }

    class Rectangle {
        constructor(width, height) {
            this.width = width;
            this.height = height;
        }
        area(){
           return this.width * this.height;
        }
    }

    class Circle {
        constructor(radius) {
             this.radius = radius;
        }
        area(){
            return Math.PI * this.radius * this.radius;
        }
    }

    class calcMe {
       calculate(obj) {
           return obj.area()
       }
    }

    const square = new Square(4);
    const rectangle = new Rectangle(4, 2);
    const circle = new Circle(5);

    console.log(calcMe.prototype.calculate(square));
    console.log(calcMe.prototype.calculate(rectangle));
    console.log(calcMe.prototype.calculate(circle));


Baseline adjustment when both pre- and post values are subject to left-censoring

Question: Assume $X$ is a binary treatment variable, $Y$ is a continuous variable measured pre- and post-treatment $(Y_{pre}$, $Y_{post})$, and $Z$ represents the remaining covariates. Both $Y_{pre}$ and $Y_{post}$ are subject to left-censoring.
Does anyone know an approach to analyze the effect of $X$ on $Y_{post}$ adjusted for $Y_{pre}$ and $Z$? Tobit regression (e.g.) can handle the situation where only $Y_{post}$ is censored, and various methods are suggested in the case where only $Y_{pre}$ (and/or $Z$) is censored. But what if both $Y_{pre}$ and $Y_{post}$ are subject to left-censoring?
Comment: I usually think of time-to-event variables with left-censoring. Can you explain what kind of variable or setting has $Y_{pre}$ and $Y_{post}$ subject to left censoring?
Comment: Thanks for your reply. I acknowledge that the terminology in the literature is ambiguous. What I mean is that for some observations of Y it is only known that the value is below a certain number. Should I change the original post?
Comment: Since we usually condition on $Y_{pre}$ we don't need as much to think of its distribution (unlike what we do for $Y_{post}$).  It's just that when we condition on $Y_{pre} = y$ and $y$ is at the lower detectable limit we are really conditioning on $Y_{pre} \leq y$ and this incomplete conditioning will result in a larger residual variance for $Y_{post}$.  So you might posit a flexible nonlinear model in $Y_{pre}$ with even a spike at the lower limit, but having two variance terms for $Y_{post}$.  I'm not sure how this would play with categorical $Y_{post}$.
Comment: I think if you let $\Delta = Y_{post} - Y_{pre}$ be your outcome measure you can derive that this is interval censored and derive the interval bounds based on which of the two are below the limit of detection.
Answer: If $Y_{pre}$ and $Y_{post}$ are, for instance, lab analytes where the assay can only detect down to a lower limit of detection, you can use an EM algorithm to impute the values according to some distributional assumption.
To illustrate with a univariate case: consider first the M step. To calculate the likelihood, an order statistic result is to just input the CDF functional. For instance:
set.seed(123)
n <- 100
ypre <- rlnorm(n = n, meanlog = -3, sdlog = 3)
ypre[ypre < 1] <- 1

negloglik <- function(param, x, cens) {
  -sum(pnorm(x[cens], mean = param[1], sd=param[2], log.p = T)) -
    sum(dnorm(x[!cens], mean=param[1], sd=param[2], log = T))
}

nlm(f = negloglik, p=c(0,1), x=log(ypre), cens = ypre==1)

Gives (with lots of warnings because the nlm algo is a bit rough)
$estimate
[1] -2.509127  2.642844

Which we can then apply expectation (E-step) based on the conditional expectation
paramest <- nlm(f = negloglik, p=c(0,1), x=log(ypre), cens = ypre==1)$estimate
pcens <- mean(ypre == 1)
expval <- integrate(function(x) x*dnorm(x, mean=paramest[1], sd = paramest[2]),
  lower=-Inf, upper=qnorm(pcens))
ypre_e <- ifelse(ypre==1, exp(expval), ypre)

Now this is considerably more complicated with multivariate analyses. If we are able to assume normality for the $Y$s (or some transformation), we can use linear regression as a maximum likelihood process. We can factor the joint likelihood of Ypre, X, and Ypost into the likelihood of Ypre and of Ypost|X, Ypre. I think we can thus develop the algorithm:

Initialize parameter estimates for Ypre, the regression parameters for the mean Ypost response adjusting for Ypre and treatment, and the residual standard error of Ypost
Calculate the expected value of Ypre
Estimate the regression using a maximum likelihood procedure with the conditional mean of Ypost given by the current regression estimates and current residual variance
Update the regression estimates and residual variance according to the MLE.
Repeat steps 3 and 4 until convergence.


Remote Desktop over SSH SOCKS proxy to bypass firewall

Question: I'm trying to connect to a Windows server from my Mac using RDC2.1 for Mac.
The problem is the server I need to connect to is guarded by the evil dragon - IP-based access control on a completely separate network.
I have an IP I can get in on, but it's at my office (i.e. a completely separate network).
Because that network isn't set up for VPN, I've set up a SOCKS proxy through an SSH tunnel (which is all working fine).
               (SSH proxy)
Me (on my Mac) ----------> Office Linux box ----> Windows server
(home network)             (office network)       (other network)

From my Linux server in my office (the SSH server) I can telnet to port 3389 on the Windows server, no problem. But from my Mac I can't get so much as a squeak out of it. Any ideas?
Comment: "I have an IP I can get in on" - there would be no point having the security if I couldn't bypass it!

That's like having a security guard at your front door and telling him to never let anyone in or out and him taking you very literally...
Comment: So you're asking Sys Admins to help you bypass security put in place by Sys Admins?
Answer: You don't need a SOCKS proxy for this; simple SSH port forwarding will work.  For example, there's a server at my office I frequently need to access, which we'll call server.example.com.  I can't connect to it directly, but I can ssh to myofficemachine.example.com.  So I do this:
ssh -L 3389:server.example.com:3389 myofficemachine.example.com

And then I point my local Remote Desktop client to localhost. This works great, and my setup is almost identical to yours -- a Mac at home, a Linux box at my office, and a Windows server on another work network.
Comment: This did the trick nice and quickly!
Comment: This still works with the latest RDP client (by Microsoft) on Mac (OSX 10.10). ... _just to keep the answer up to date_
Comment: @0xC0000022L done :)
Comment: This works with the latest Mac Remote Desktop client too?  With a Domain on the Windows side?
Comment: It shouldn't matter what's on the other side.  I don't know if I've used the *latest* Mac client, but it should work.  If you're having problems, you might want to post a new question.
Comment: @Simon: it would help _this_ answer to appear at the top if you accepted this one instead of the other one (yes, one can change that).
Comment: Well, this question is, for some reason, "off topic," but this answer is *exactly* what I needed for a quick how-to-use-`ssh`-for-this. Still works with RDP on MacOS to a Windows 7 computer in a firewalled network via a computer that I've got remote ssh access into.
Answer: You could try using CoRD, a replacement remote desktop app which supports SOCKS proxies.
Comment: After downloading and using CoRD I already prefer it to Microsoft's own RDC... good find Marc


how to define $x^\sqrt 2$?

Question: Can anyone please tell me how to define $x^\sqrt 2$ ?
If it was $x^2$ or $x ^ \frac{1}{2}$, we could have said that  $x^2$ means $x \times x$ and $x ^ \frac{1}{2}$ means a number y such that $y^2 = x$.
But  how to define $x^\sqrt 2$ ?
Can anyone please help me ?
Comment: $e^{\sqrt2\ln x}$?
Comment: Or this: https://math.stackexchange.com/q/1272546/42969
Comment: I think it is poor practice to think of $x^a$ as $x\times x$ $a$ times (or the inverse of this). What does $e^x$ mean in that case? What about $x^i$? Think of the exponential function as a special function that satisfies the property $a^x a^y=a^{x+y}$. Then for integer exponents it follows that the exponential function is repeated multiplication. But you should think of this as a special case of the exponential function and not the other way round.
Answer: Take a sequence of rationals $q_n$ converging to $\sqrt 2$. Then $x^{\sqrt 2}$ is defined as the limit of the sequence $x^{q_n}$. From continuity of the exponent, this limit exists, is unique, and independent of the choice of sequence. (And as you said, you already have a definition for each term in the sequence, since the powers are rational)

how to define $x^\sqrt 2$?


setting bits at shifts using bitwise operators

Question: Im trying to replicate the function
int test(int x, int y)
 {
   int result = 0;
   int i;
   for (i = y; i <= x; i++)
   result |= 1 << i;
   return result;
  }

which takes two ints and sets a bit for each position between the two numbers. Assuming  0 <= x <= 31, and 0 <= y <= 31. For example (7, 5) will set 1 to 1110 0000 where a bit is set after shifting 5, 6, and 7 times.
Im trying to do the same thing but have been restricted to using only certain bitwise operators (~ & + <<). however am having difficulty finding a way that does not use a loop. The function should return 0 if y > x.
I believe I can replicate the or operator x|y using ~(~x & ~y).
and x^y using ~(~(~x & y) & ~(x & ~y));
http://www.tutorialspoint.com/cprogramming/c_operators.htm
Comment: Easier to replicate if code used `unsigned test(unsigned  x, unsigned  y)` rather than `int`.  Negative values and `int` overflow are a pain.
Comment: `((1u << (y+1)) + ~0u) & ~((1u << x) + ~0u)`
Comment: `1` shifted by `(y+1)` sets the bit for 2**(y+1), then adding `~0` (all 1's) effectively subtracts one to get all lower bits set instead.  Then do the same for `x` instead of `y+1`, invert it so only the low bits are clear, then AND the two.  Works for me as long as `y` is less than 31, or for everything if I use `~0u` instead of `((1u << (y+1)) + ~0u)` just for when `y==31`
Comment: Oh wait, I have the low number in `x` and you have it in `y`... try swapping `x` and `y`
Comment: Calling `+` a 'bitwise operator' is a little unusual.  So, the problem is that the revised function must handle a range of values for `x` and `y` (what is the maximum allowed value — 6, 7, 14, 15, 30, 31, 62, 63?) and must _not_ use a loop to do so?  Can it use conditionals?
Comment: @JonathanLeffler my apologies, the range is 0 <= x <= 31, and 0 <= y <= 31. Correct im trying to do so without looping and cannot use conditionals.
Comment: @Dmitri did not work for me, nor do I quite follow.
Comment: @Dmitri this is my implementation of your method which returns 0, have I made a mistake? https://gist.github.com/anonymous/3fb37154200fa6666671ce289e35a838
Comment: Looks right except for the special case when `y` is 31 or whatever the highest bit number is (if it is, just `return ~((1u << x) + ~0u);` instead).
Comment: @Dmitri ah yes that was it, my mistake, thanks.
Answer: If you can use - you could do it like this:
int test(int x, int y)
{
    int mask1 = (1 << y) - 1;
    int mask2 = (1 << (x+1)) - 1;
    int result = mask1 ^ mask2;
    return result;
}

Checking for y > x is left as an exercise for the reader.
Comment: I considered that, however both - and ^ are restricted.


Java JMeter DSL. How to execute custom logic in threadGroup() method?

Question: The problem: I need to execute UI autotests in the performance tests. Need to look at how many users can open the Web page and do some requests exactly from this page (performance test on the API is not enough).
So I use Java JMeter DSL for the performance testing.
I have the next code:
TestPlanStats stats = testPlan(
            threadGroup(
                    testParams.getThreads(), Duration.ofMinutes(testParams.getLoadTime()),
                    myCustomLogic
            ).rampTo(testParams.getThreads(), Duration.ofMinutes(testParams.getRumpUpTime())),
            influxDbListener(envSetting.getInfluxDbUrl())
                    .measurement("ui-performance")
    ).run();

The question is: how to implement myCustomLogic in the threadGroup for execution of UI tests for each thread in the performance test?
For example, I already tried to put jsr223Sampler() with the script on Groovy.
I have an implementation of UI autotest with the needed logic (open web page and other actions)
public class ApiSteps {

public void doSomeLogic() {
    //do some actions
}

}
and put this script like this:
        String script = "Object apiStepsInstance = new ApiSteps();" +
            "vars.putObject(\"apiSteps\", apiStepsInstance)" +
            "def apiSteps = vars.getObject(\"apiSteps\")\n" +
            "apiSteps.doSomeLogic()";
    DslJsr223Sampler dslJsr223Sampler = new DslJsr223Sampler("UI performance test", script);
    dslJsr223Sampler.language("Groovy");
    TestPlanStats stats = testPlan(
            threadGroup(
                    testParams.getThreads(), Duration.ofMinutes(testParams.getLoadTime()),
                    dslJsr223Sampler
            ).rampTo(testParams.getThreads(), Duration.ofMinutes(testParams.getRumpUpTime())),
            influxDbListener(envSetting.getInfluxDbUrl())
                    .measurement("ui-performance")
    ).run();

In the script, I tried to call the apiSteps.doSomeLogic() java method.
Tell me please if this is a successful way to put Groovy script with calling java method please correct my script.
If the way of putting this Groovy script is wrong, please provide the way how can I do UI autotests during performance testing.
Thanks a lot for the answers.
Answer: This looks like valid and correct way of running Groovy code using JMeter Java DSL
At least if you do something like:
testPlan(
        threadGroup(1,
                1,
                new DslJsr223Sampler("UI performance test", "println('Hello from JSR223')")))
        .run();

You should see Hello from JSR223 message in stdout:

Most probably if you need to run your custom class you need to add it to JMeter Classpath (along with any dependencies) like here
You can check out Groovy code debug ticket for some hints.
More information: JMeter DSL: Bringing Performance Testing Closer to Developers
Answer: As Dimitri mentioned, the general approach looks ok.
I only want to point out that if you want to use a ramp up and then hold for duration, you should use something like this:
threadGroup()
  .rampToAndHold(testParams.getThreads(), Duration.ofMinutes(testParams.getRumpUpTime()), Duration.ofMinutes(testParams.getLoadTime())),
  .children(dslJsr223Sampler)


Why does my VMWare / Linux host slow down every 6 hours?

Question: I have a VPS with standard LAMP stack and a busy website. Operating system is CentOS 5.5. Virtualization is done with VMWare. My server gets real slow about every 6 hours. Logging into it I see that 1.6GB of RAM is consumed. However, summing up the memory usage of active processes adds up only to about 700MB. Can anyone make any sense of this?
"free" shows this:
             total       used       free     shared    buffers     cached
Mem:       2059456    2049280      10176          0      14780     380968
-/+ buffers/cache:    1653532     405924
Swap:      2096472         96    2096376

While this is output of "ps":
[root@vmi29 /]# ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.0  10348   688 ?        Rs   Jun05   0:01 init [3]
root         2  0.0  0.0      0     0 ?        S<   Jun05   0:00 [migration/0]
root         3  0.0  0.0      0     0 ?        SN   Jun05   0:00 [ksoftirqd/0]
root         4  0.0  0.0      0     0 ?        S<   Jun05   0:00 [migration/1]
root         5  0.0  0.0      0     0 ?        SN   Jun05   0:00 [ksoftirqd/1]
root         6  0.0  0.0      0     0 ?        S<   Jun05   0:00 [migration/2]
root         7  0.0  0.0      0     0 ?        SN   Jun05   0:00 [ksoftirqd/2]
root         8  0.0  0.0      0     0 ?        S<   Jun05   0:00 [migration/3]
root         9  0.0  0.0      0     0 ?        SN   Jun05   0:00 [ksoftirqd/3]
root        10  0.0  0.0      0     0 ?        S<   Jun05   0:06 [events/0]
root        11  0.0  0.0      0     0 ?        S<   Jun05   0:00 [events/1]
root        12  0.0  0.0      0     0 ?        S<   Jun05   0:00 [events/2]
root        13  0.0  0.0      0     0 ?        S<   Jun05   0:00 [events/3]
root        14  0.0  0.0      0     0 ?        S<   Jun05   0:00 [khelper]
root        31  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kthread]
root        38  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kblockd/0]
root        39  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kblockd/1]
root        40  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kblockd/2]
root        41  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kblockd/3]
root        42  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kacpid]
root       204  0.0  0.0      0     0 ?        S<   Jun05   0:00 [cqueue/0]
root       205  0.0  0.0      0     0 ?        S<   Jun05   0:00 [cqueue/1]
root       206  0.0  0.0      0     0 ?        S<   Jun05   0:00 [cqueue/2]
root       207  0.0  0.0      0     0 ?        S<   Jun05   0:00 [cqueue/3]
root       210  0.0  0.0      0     0 ?        S<   Jun05   0:00 [khubd]
root       212  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kseriod]
root       302  0.0  0.0      0     0 ?        S    Jun05   0:00 [khungtaskd]
root       303  0.0  0.0      0     0 ?        S    Jun05   0:00 [pdflush]
root       304  0.0  0.0      0     0 ?        S    Jun05   0:01 [pdflush]
root       305  0.0  0.0      0     0 ?        S<   Jun05   0:05 [kswapd0]
root       306  0.0  0.0      0     0 ?        S<   Jun05   0:00 [aio/0]
root       307  0.0  0.0      0     0 ?        S<   Jun05   0:00 [aio/1]
root       308  0.0  0.0      0     0 ?        S<   Jun05   0:00 [aio/2]
root       309  0.0  0.0      0     0 ?        S<   Jun05   0:00 [aio/3]
root       515  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kpsmoused]
root       582  0.0  0.0      0     0 ?        S<   Jun05   0:00 [mpt_poll_0]
root       583  0.0  0.0      0     0 ?        S<   Jun05   0:00 [mpt/0]
root       584  0.0  0.0      0     0 ?        S<   Jun05   0:00 [scsi_eh_0]
root       590  0.0  0.0      0     0 ?        S<   Jun05   0:00 [ata/0]
root       591  0.0  0.0      0     0 ?        S<   Jun05   0:00 [ata/1]
root       592  0.0  0.0      0     0 ?        S<   Jun05   0:00 [ata/2]
root       593  0.0  0.0      0     0 ?        S<   Jun05   0:00 [ata/3]
root       594  0.0  0.0      0     0 ?        S<   Jun05   0:00 [ata_aux]
root       610  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kstriped]
root       631  0.0  0.0      0     0 ?        S<   Jun05   0:05 [kjournald]
root       656  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kauditd]
root       689  0.0  0.0  13364   928 ?        S<s  Jun05   0:00 /sbin/udevd -d
root      2123  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kmpathd/0]
root      2124  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kmpathd/1]
root      2126  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kmpathd/2]
root      2127  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kmpathd/3]
root      2128  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kmpath_handlerd]
root      2203  0.0  0.0      0     0 ?        S<   Jun05   0:00 [kjournald]
root      2613  0.0  0.0   5908   648 ?        Ss   Jun05   0:00 syslogd -m 0
root      2617  0.0  0.0   3804   424 ?        Ss   Jun05   0:00 klogd -x
root      2707  0.0  0.0  10760   372 ?        Ss   Jun05   0:02 irqbalance
apache    2910  0.5  0.6 213964 12912 ?        S    00:22   0:07 /usr/sbin/httpd
dbus      3011  0.0  0.0  21256   904 ?        Ss   Jun05   0:00 dbus-daemon --system
root      3025  0.0  0.0   3800   576 ?        Ss   Jun05   0:00 /usr/sbin/acpid
68        3038  0.0  0.2  31152  4336 ?        Ss   Jun05   0:01 hald
root      3039  0.0  0.0  21692  1176 ?        S    Jun05   0:00 hald-runner
68        3046  0.0  0.0  12324   856 ?        S    Jun05   0:00 hald-addon-acpi: listening on acpid socket /var/run/acpid.s
68        3052  0.0  0.0  12324   856 ?        S    Jun05   0:00 hald-addon-keyboard: listening on /dev/input/event0
root      3105  0.0  0.0  62624  1212 ?        Ss   Jun05   0:00 /usr/sbin/sshd
root      3264  0.0  0.0  74820  1156 ?        Ss   Jun05   0:00 crond
root      3292  0.0  0.0  18416   472 ?        S    Jun05   0:00 /usr/sbin/smartd -q never
root      3300  0.0  0.0   3792   480 tty2     Ss+  Jun05   0:00 /sbin/mingetty tty2
root      3301  0.0  0.0   3792   480 tty3     Ss+  Jun05   0:00 /sbin/mingetty tty3
root      3302  0.0  0.0   3792   484 tty4     Ss+  Jun05   0:00 /sbin/mingetty tty4
root      3304  0.0  0.0   3792   480 tty5     Ss+  Jun05   0:00 /sbin/mingetty tty5
root      3306  0.0  0.0   3792   480 tty6     Ss+  Jun05   0:00 /sbin/mingetty tty6
apache    5158  0.4  0.5 211896 11848 ?        S    00:28   0:04 /usr/sbin/httpd
apache    5519  0.4  0.5 211896 11992 ?        S    00:29   0:03 /usr/sbin/httpd
root      5649  0.0  0.0  63848  1184 pts/0    S    Jun05   0:00 /bin/sh /usr/bin/mysqld_safe --datadir=/var/lib/mysql --soc
mysql     5696  2.1  1.9 411060 40392 pts/0    Rl   Jun05   2:01 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql
apache    5943  0.4  0.5 211896 12000 ?        S    00:30   0:03 /usr/sbin/httpd
apache    5976  0.6  0.5 211896 11792 ?        S    00:30   0:04 /usr/sbin/httpd
apache    6073  0.4  0.5 211896 11208 ?        S    00:31   0:03 /usr/sbin/httpd
apache    6122  0.4  0.5 211896 11848 ?        S    00:31   0:03 /usr/sbin/httpd
apache    6128  0.3  0.5 211896 11940 ?        S    00:31   0:02 /usr/sbin/httpd
apache    6159  0.5  0.5 211896 11872 ?        S    00:31   0:04 /usr/sbin/httpd
apache    6636  0.4  0.6 213960 13444 ?        S    00:32   0:02 /usr/sbin/httpd
apache    6787  0.3  0.5 211884 11308 ?        S    00:33   0:02 /usr/sbin/httpd
apache    6796  0.4  0.5 211884 12024 ?        S    00:33   0:02 /usr/sbin/httpd
apache    6801  0.3  0.5 211896 11920 ?        S    00:33   0:01 /usr/sbin/httpd
apache    6804  0.4  0.5 211884 11848 ?        S    00:33   0:02 /usr/sbin/httpd
apache    6825  0.4  0.5 211896 11972 ?        S    00:33   0:02 /usr/sbin/httpd
apache    6866  0.3  0.5 210860 11044 ?        S    00:33   0:01 /usr/sbin/httpd
apache    6870  0.2  0.5 211896 11108 ?        S    00:33   0:01 /usr/sbin/httpd
apache    6872  0.3  0.5 211896 11900 ?        S    00:33   0:01 /usr/sbin/httpd
apache    6993  0.3  0.5 211896 11836 ?        S    00:33   0:02 /usr/sbin/httpd
apache    6994  0.3  0.5 211896 11792 ?        S    00:33   0:01 /usr/sbin/httpd
apache    7136  0.2  0.5 211896 11432 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7143  0.2  0.5 210860 11052 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7145  0.2  0.5 211896 11136 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7266  0.2  0.6 213952 12748 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7299  0.2  0.5 211884 11276 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7311  0.2  0.5 211884 11300 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7313  0.3  0.5 211884 11876 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7345  0.2  0.5 210872 11100 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7349  0.2  0.5 210860 11008 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7350  0.2  0.5 211896 11832 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7351  0.1  0.5 211884 11072 ?        S    00:34   0:00 /usr/sbin/httpd
apache    7352  0.2  0.5 210872 11096 ?        S    00:34   0:01 /usr/sbin/httpd
apache    7449  0.1  0.5 210860 11020 ?        S    00:35   0:00 /usr/sbin/httpd
root      7490  0.3  0.0      0     0 ?        S    Jun05   3:11 [vmmemctl]
root      7597  0.0  0.0  72656  1260 ?        Ss   Jun05   0:06 /usr/lib/vmware-tools/sbin64/vmware-guestd --background /va
apache    7720  0.1  0.5 210860 10748 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7726  0.1  0.4 209836  9304 ?        R    00:36   0:00 /usr/sbin/httpd
apache    7727  0.1  0.5 210860 10916 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7731  0.1  0.5 210860 10780 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7732  0.3  0.5 210860 10916 ?        S    00:36   0:01 /usr/sbin/httpd
apache    7733  0.1  0.5 210872 11000 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7735  0.1  0.5 211884 11048 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7761  0.1  0.5 210860 10552 ?        S    00:36   0:00 /usr/sbin/httpd
apache    7776  0.1  0.4 209836  8648 ?        R    00:37   0:00 /usr/sbin/httpd
apache    7790  0.2  0.3 208812  7724 ?        R    00:40   0:00 /usr/sbin/httpd
apache    7800  0.2  0.3 208812  8088 ?        R    00:40   0:00 /usr/sbin/httpd
root      7801  0.0  0.0   3792   484 tty1     Ss+  00:41   0:00 /sbin/mingetty tty1
apache    7820  0.2  0.3 208812  7552 ?        R    00:41   0:00 /usr/sbin/httpd
apache    7834  0.2  0.3 207788  6756 ?        R    00:42   0:00 /usr/sbin/httpd
apache    7864  0.2  0.2 207788  6148 ?        R    00:42   0:00 /usr/sbin/httpd
apache    7872  0.3  0.2 207788  5856 ?        R    00:43   0:00 /usr/sbin/httpd
apache    7874  2.5  0.3 207788  6336 ?        R    00:43   0:00 /usr/sbin/httpd
root      7875  0.3  0.0  63844  1056 ?        S    00:43   0:00 sh -c lsb_release -sd 2>/dev/null
root      7879  1.6  0.0  65604   964 pts/0    R+   00:43   0:00 ps aux
root     16316  0.0  0.1  90128  3272 ?        Ss   Jun05   0:00 sshd: milanb [priv]
milanb   16358  0.0  0.0  90128  1752 ?        S    Jun05   0:00 sshd: milanb@pts/0
milanb   16360  0.0  0.0  66076  1480 pts/0    Ss   Jun05   0:00 -bash
root     16875  0.0  0.0 101068  1324 pts/0    S    Jun05   0:00 su -
root     16877  0.0  0.0  66184  1692 pts/0    S    Jun05   0:00 -bash
root     24373  0.0  0.3 206764  7348 ?        Rs   Jun05   0:01 /usr/sbin/httpd

UPDATE:
Here, it happens again (about a hour later this time).
[root@vmi29 ~]# cat /proc/meminfo
MemTotal:      2059456 kB
MemFree:         17340 kB
Buffers:         17788 kB
Cached:         407804 kB
SwapCached:          0 kB
Active:         517704 kB
Inactive:       122188 kB
HighTotal:           0 kB
HighFree:            0 kB
LowTotal:      2059456 kB
LowFree:         17340 kB
SwapTotal:     2096472 kB
SwapFree:      2096376 kB
Dirty:             160 kB
Writeback:           0 kB
AnonPages:      214436 kB
Mapped:          13296 kB
Slab:            27392 kB
PageTables:      18780 kB
NFS_Unstable:        0 kB
Bounce:              0 kB
CommitLimit:   3126200 kB
Committed_AS:   514788 kB
VmallocTotal: 34359738367 kB
VmallocUsed:    264012 kB
VmallocChunk: 34359473911 kB
HugePages_Total:     0
HugePages_Free:      0
HugePages_Rsvd:      0
Hugepagesize:     2048 kB

iostat output:
[root@vmi29 ~]# iostat
Linux 2.6.18-194.3.1.el5 (vmi29)        06/06/2010

avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           6.33    0.00    1.07    1.83    0.00   90.78

Device:            tps   Blk_read/s   Blk_wrtn/s   Blk_read   Blk_wrtn
sda              12.02        44.47       123.40    2526367    7011298
sda1              0.00         0.04         0.10       2036       5466
sda2              0.00         0.03         0.00       1681        200
sda3             12.01        44.39       123.30    2522226    7005632

Free:
[root@vmi29 ~]# free -m
             total       used       free     shared    buffers     cached
Mem:          2011       2002          8          0         15        386
-/+ buffers/cache:       1600        410
Swap:         2047          0       2047

Command that Nathan Powell suggested:
[root@vmi29 ~]# ps aux | awk '{SUM += $3} END { print SUM }'
20.2

Update2:
[root@vmi29 ~]# ps aux | awk '{SUM += $4} END { print SUM }'
12.5

Free:
[root@vmi29 ~]# free
             total       used       free     shared    buffers     cached
Mem:       2059456    2038316      21140          0       7360     492800
-/+ buffers/cache:    1538156     521300
Swap:      2096472        100    2096372

Comment: The content of meminfo is strange... usually "lost" RAM (not used by the cache) ends up being used by the SLAB, but it's not your case. MemFree (really unsued ram) + Cached + AnonPages + Mapped + Slab should match more or less (there are other allocations, but they're small) the total amount of memory.
Are you running a PV kernel? The hypervisor has the ability to forcibly "steal" the memory from guests when need (and of course when it's configured to do it).
Comment: I am sorry.  My bad.  I meant $4 in that command not $3.
Comment: /proc/meminfo should shed some light on what's going on: please post its content.
Comment: http://www.linuxatemyram.com/ should explain linux memory usage well enough
Comment: @cpbills: the link you sent in section titled "How do I see how much free ram I really have?" is really the issue I'm talking about here, so I don't see how that helps? "free" shows that I "really have" 400MB free, while "ps" shows that only 700MB is used. 400+700=1100. However, the computer has 2GB of RAM. So, where is 900MB gone? I'm suspecting VMWare issue, but I'd like to be sure before accusing my hosting provider.
Comment: it is being used for disk caching. it is FREE, but in use.
Comment: cpbills: memory used for disk caching is shown in "cached" column of "free" output. It only shows 380MB. So, this is not the case here. If it were so easy, I wouldn't have bothered asking here.
Comment: the second row of free is buffers + cache + free, 10176+14780+380968 = 405924
Comment: @cpbills: so, it's still only 400MB. Where's the rest?
Comment: @Luca: I just updated the question.
Comment: @Nathan: at least we got CPU load SUM ;)  I'll try $4 next time it happens, thanks.
Comment: bleh.  Yeah, sorry.
Comment: Now it happened again, and it's even worse. I only have about 15 httpd processes (there aren't many visitors on website at this time - people are asleep, it's 5am in country where 98% of visitors come from). However, 1.5GB of RAM is consumed. This has got to be VMWare issue.
Answer: Run slabtop or parse /proc/slabinfo and look at your kernel slabs; it's very common for the kernel to cache a lot of directory entries and inodes (dentry_cache, ext3_inode_cache) on a system, especially one with lots of file access like an Apache server that's sending lots of static content (images, etc.). This is where your "missing" memory is usually.
If this tweaks you out you can adjust vm.cache_pressure in /etc/sysctl.conf to reduce that usage but I highly recommend understanding why first.
Answer: Check vmmemctl memory usage. I had a similar problem, see RedHat Linux: server paging, sum of RES/RSS + buffers + cached < TOTAL. Who is using my memory?
In my case, we had an 8GB RAM server and we couldn't find which process was using. This is our vmmemctl:
cat /proc/vmmemctl

target:              1000894 pages
current:             1000894 pages
rateNoSleepAlloc:      16384 pages/sec
rateSleepAlloc:         2048 pages/sec
rateFree:              16384 pages/sec

timer:                325664
start:                     3 (   0 failed)
guestType:                 3 (   0 failed)
lock:                3623088 (  29 failed)
unlock:               623698 (   0 failed)
target:               325664 (   2 failed)
primNoSleepAlloc:    3620199 (  11 failed)
primCanSleepAlloc:      2900 (   0 failed)
primFree:            2622165
errAlloc:                 28
errFree:                  28

getconf PAGESIZE
4096

So vmmemctl is using 4GBs
It's a pity the vmmemctl doesn't use a standard method to report how much memory it's using, but I think it's because how it's implemented.
The main reference from vmware offers a lot of detail about ballooning.
I quote since it's relevant to our original problem ( 'why is this server paging if it has non used memory'? ):

"Typically, the hypervisor inflates the virtual machine balloon when
  it is under memory pressure. By inflating the  balloon, a virtual
  machine consumes less physical memory on the host, but more physical
  memory inside the  guest. As a result, the hypervisor offloads some of
  its memory overload to the guest operating system while  slightly
  loading the virtual machine. That is, the hypervisor transfers the
  memory pressure from the host to the  virtual machine. Ballooning
  induces guest memory pressure. In response, the balloon driver
  allocates and pins  guest physical memory. The guest operating system
  determines if it needs to page out guest physical memory to  satisfy
  the balloon driver's allocation requests. If the virtual machine has
  plenty of free guest physical memory,  inflating the balloon will
  induce no paging and will not impact guest performance. In this case,
  as illustrated in  Figure 6, the balloon driver allocates the free
  guest physical memory from the guest free list. Hence, guest-level
  paging is not necessary.
However, if the guest is already under memory pressure, the guest
  operating system  decides which guest physical pages to be paged out
  to the virtual swap device in order to satisfy the balloon  driver's
  allocation requests. The genius of ballooning is that it allows the
  guest operating system to intelligently  make the hard decision about
  which pages to be paged out without the hypervisor's involvement."
"genius of ballooning" :)
Comment: I wish I could accept 2 answers. troyengel's suggestion helped me for some dedicated servers as well, but in this particular case it was really ballooning effect. The hosting provider oversold the capacity.
Answer: VSZ = Virtual Memory Size.
Have a look at all your httpd (apache) processes. 200MB each times lots.
Comment: After machine is rebooted, I still see 20-30 Apache processes with 200MB VSZ each, but overall RAM usage is only -/+ buffers/cache: 289296. Those 200MB are not multiplied for each Apache process, they are shared.
Answer: First 'free -m' which shows the usage in Megs, makes more sense visually...since it's not 1996 anymore :)
Second, you have a lot of ram cached, so you aren't out of ram.
3rd, you are only swapping 96K.  That is trivial.
To see what is swapping, open 'top', Then use 'O' (cap o) then 'p' then enter.
Ram is not the only thing that will make things "slow".  Look at disk i/o and Proc usage as well.
Comment: If VMware's vmmemctl is active then it is intentionally taking physical RAM away from your VM to give to other VM's. If this is the case then Hypervisor level paging may also be affecting your system. Is it possible that you are seeing a transient side effect of that? What level of vmmemctl ballooning does the Hypervisor report?
Comment: @Milan: Use iostat to check I/O
Comment: Thanks, but it still does not explain why "free" reports 1.6 GB usage while sum of processes is much lower. CPU usage is very high (20+ load) because VMWare's vmmemctl kicks in to deal with the RAM increase. How do I check disk I/O?
Comment: Sure it does.  Cached is not used.  Google "how do I check disk io in Linux"  And a load of 20 will certainly be the issue.
Comment: My question is not why the system is slow. My question is why would "free" report one number, while summing up processes in "ps" output gives a much lower number. Any clues?
Comment: Yes, and I have answered it twice now.  Cached is not used.  It is simply cached.
Comment: @Nathan: please look at free output once again. Only 380MB is cached. System has 2GB RAM. Cached is not used: 2GB - 380MB = 1.6GB. However, summing up the memory usage of each process in "ps" output only gives about 700MB. 1.6GB - 700MB = 900MB. What is happening with these 900 MB of RAM?
Comment: Ok, let's figure this out.  Do this:

ps aux | awk '{SUM += $3} END { print SUM }'

That should give us the % of memory used.

Then look at 'free -m', add the free and cached columns.  And then divide that number by total memory, and multiply by 100.  That should give you the percentage of ram free is showing as utilized.

The numbers should be close.  If they aren't then I might have an error in my logic, but that seems right to me.
Comment: It just happened again. I updated my question with result of your command.
Comment: @Helvick, thanks for commenting. I can only access the guest system, as I'm renting this VPS server. Is there a way to see the level of vmmemctl balloning on the guest side?


Como usar Angular input mask

Question: Eu uso AngularJs e Ionic e estou tentando usar este Input Mask, mas não sei bem como fazer. Eu sigo os passos e mesmo assim aparece este erro: Erro Angular.
Referências no index.html:

app.js:
angular.module('starter', ['ionic', 'ui.utils.masks','starter.controllers', 'starter.services'])

Comment: Qual o erro que mostra pra você? No teu console.
Comment: Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.13/$injector/modulerr?p0=starter&p1=Error%3…code.ionicframework.com%2F1.0.0-rc.5%2Fjs%2Fionic.bundle.min.js%3A48%3A381)
Comment: Acho que faltou adicionar o js do ionic
Comment: Ja tem, está logo acima. Não coloquei aqui para não ficar muito grande.
Answer: O problema é que a referência ao arquivo angular-input-masks-standalone.min.js estava fora da pasta www, tornando o arquivo inacessivel.
Desta forma funcionou.
Forma certa

Forma errada

Pelo menos aqui deu certo.
Comment: https://github.com/assisrafael/angular-input-masks não existe a pasta /angular-input-masks/
Comment: No meu pacote tinha, da uma olhada no seu para algo equivalente.

Como usar Angular input mask


Erro de versão do Gradle

Question: Alguém tem alguma ideia de como resolver esse erro no Android Studio?
Plugin is too old, please update to a more recent version, or set ANDROID_DAILY_OVERRIDE variable to...

erro-gradle.PNG1055x71 6.59 KB
Meu classpath esta assim:
classpath 'com.android.tools.build:gradle:2.2.0-alpha3'
Nesse link diz que a ultima versão do gradle é a alpha4 mas não funciona como alpha4.
Link: http://tools.android.com/tech-docs/new-build-system
Já cliquei no link do erro mas não funciona também.
Como solucionar esse problema?
Obrigado a todos.
Answer: Você pode alterar o classpath e colocar um "+" antes da versão que define a alteração, assim, ele não perderá a compatibilidade (tão cedo).
classpath 'com.android.tools.build:gradle:2.2.+'

Fazendo isso você garante que será suportado até enquanto houver versões 2.2.qualquer versão
Quanto mais especifico for, maior a chance de perder a compatibilidade, quanto maior for a granularidade, maior a chance de manter a compatibilidade e ter que refazer algo que a API mudou.
Por exemplo:
Você pode fazer isso:
classpath 'com.android.tools.build:gradle:2.+'

Mas é arriscado, porque o desenvolvedor pode deprecar algum método a partir da 2.3 e você ser pego de surpresa e ter que refazer algumas coisas a "toque de caixa".
Comment: Carlos vlw pela resposta.
Editei aqui mas não funcionou.

Obrigado cara.
Comment: Patz, tentou dar um Fix Plugin?
Comment: Sim mano mas mesmo assim não deu certo.

Erro de versão do Gradle


Functions and their properties

Question: I was looking through my calculus notes on my book regarding the properties of functions. I came upon two questions which appear to be unclear, so if anybody could explain to me what they mean and how to get to the answer it would be really nice.
1) A differentiable function which is not 1:1 has either a maximum or a minimum .
Does this mean that whichever function which is NOT 1:1 (whatever that means) may have a min or a max?
2) A strictly increasing function has to be 1:1. Here again , i am not able to grasp the function of a 1:1 question.
Any explanation would be really usefull :)
Comment: An [injective function](https://en.wikipedia.org/wiki/Injective_function) (also called a one-to-one function) is a function $f~:~X\to Y$ such that for every $x_1,x_2$ if $x_1\neq x_2$ then $f(x_1)\neq f(x_2)$.  In other words, if you take two *different* inputs, they *must* map to two *different* outputs.  A function which is not injective must have at least one example of a pair of inputs $x_1,x_2$ such that despite $x_1\neq x_2$ you still have $f(x_1)=f(x_2)$.
Comment: The first statement seems to be incorrect unless you change the phrase to be about **local** maximums or minimums.  $f(x)=x^3-x=x(x+1)(x-1)$ is a differentiable function which is not one-to-one (*e.g. $-1,0$ and $1$ all map to the same output of zero*) but it is unbounded in both directions and as such has no max or min.  The second statement is true since being strictly increasing means if $x_1<x_2$ then $f(x_1)<f(x_2)$ (*for whatever `<` makes sense in the contexts of the domain and codomain*) which directly implies that if $x_1\neq x_2$ then $f(x_1)\neq f(x_2)$
Comment: I grasped the concept of 1:1 with you answer well, but im still unsure about the first question ... i saw the question as stated above. However, wouldn't the question imply that a function which is not 1:1 , so many functions that actually exist, have either a maximum or minimum'?
Comment: The question seems kind of unclear. Might i read it as if a function which is not 1:1 NEEDS to have a max or a min ? because in that case, i think the statement would indeed be false
Answer: A 1-1 function means if $f(a) = f(b)$ then $a = b$.  That for any value $c$ there are not two different $a,b$ so that $f(a) = c; f(b)=c$.
This makes 2) trivial.  If $f$ is not 1-1 then there are some $a,b,$  $a\ne b$ and $f(a) = f(b)$ then either $a < b$ and $f(a) \not < f(b)$ so not increasing, or $b < a$ and $f(b) \not < f(a)$ so not increasing.  So if $f$ is increasing it is impossible for $f$ to be not 1-1.
1) is refering to a local maximum/minimum.  $f(x) = x^3 - x$ is not 1-1 because $f(0) = f(1) = f(-1) =  0$.  But it has no global maximum/minimum.  But is has a local maximum at $x=-\frac 1{\sqrt 3}$ and a local minimum $x = \frac 1{\sqrt 3}$ (It's a local minimum because all the $x$ near $\frac 1{\sqrt 3}$ yeild a larger $f(x)$.  BUt not all the $x$ in the real numbers do. [Obviously $x = -10000$ is a much smaller result.]).
If $f$ is not 1-1 it might have local max/min but doesn't have to.    But if it doesn't it can't be differentiable.
$f(x) = \begin{cases} x& x\in \mathbb Q\text{ and the denominator is odd}\\-x& x\in \mathbb Q\text{ and the denominator is even} \\ 0& x\not \in \mathbb Q\end{cases}$
Is not 1-1 as $f(x) = f(y) = 0$ if $x, y \not \in \mathbb Q$.  But it has no max or min as every neighborhood of $x$ will have rationals with even and odd denominators so every neighborhood of $x$ will have $f$ values greater or less than $f(x)$.
Comment: Love the expalantion , thank you . just to make sure i grasped the concept, that would imply that the first statement is false and the second one true?
Comment: Is it correct to say that a differentiable function which is not 1-1 might as well NOT have a local min /max? or would that be wrong? asuming what you just wrote, that if a 1-1 function doens't have a local min/max it can't be differentiable
Comment: Finally implying that a DIFFERENTIABLE function (not 1-1) NEEDS to have a local min /max, because otherwise it wouldn't be differentiable?
Comment: No, a differentiable function that is not 1-1 will have an $a < b$ so that $f(a) = f(b)$ and there must be a local max/min between a and b.  That's the extreme value theorem.  It's not so much that not having a max min means it wouldn't be differentiable so much as a differentable non 1-1 must have an extreme value.
Comment: Okay , but is it always the case? meaning that a differentiable non 1-1 function must ALWAYS have a min /max according to the extreme value theorem?
Comment: according to what you said : a differentiable function that is not 1-1 will have an a<b so that f(a)=f(b) and there must be a local max/min between a and b. That's the extreme value theorem.
Answer: 1) Any function, be it 1:1 or not , MAY have a minimum or a maximum.
2) 1:1 means that inputting different values yields different values as output. So if a function $f$ is  (strictly) increasing,and $x, x'$ are in the domain of $f$, $x\ne x'$, say $x<x'$, then $f(x)  <f(x')$, so they can't be equal.
Comment: Does that imply that the second question is indeed true?
Comment: That every striclty increasing function is indeed one to one?
Comment: Yes, absolutely. The same is true if, more generally, the function is strictly decreasing.
Comment: Is it right to say , taking into consideration the first question , that a differentiable function NEEDS to have a local min /max, because otherwise it would not be differntiable?
Comment: Why should it be so? Tthe function $f(x)=2x$ has neither a maximum nor a minimum on $\mathbf R$.
Comment: But is 2x a differentiable function ? I am kind of confused... i was also taking into consideration what the other used was saying
Comment: A linear function is the most differentiable of functions, since it is its own linear approximation!

Functions and their properties


Is there a difference between using upstream and fastcgi_pass?

Question: Is there any difference between doing this:
upstream hhvm {
    server unix:/var/run/hhvm/hhvm.sock;
}
...
location ~ \.(hh|php)$ {
    fastcgi_pass hhvm;
}

and this:
location ~ \.(hh|php)$ {
    fastcgi_pass unix:/var/run/hhvm/hhvm.sock;
}

Which is preferable?
Answer: Using upstream allows you to do some simple load balancing between multiple backends. If you have only one backend (as seems to be the case) then it doesn't really buy you anything.
Comment: Also if you use this upstream in several places you could modify it in one place


Trying to create a gird using a 2D Array and nested loop but get undefined as a result within the array

Question:

function makeGrid(numColumns, numRows) {
  var grid = [];
  var rows = [];

  var columns = [];
  for(let i = 0; i < numRows; i++) {
     grid[i] = [];
     for(let j = 0; j < numColumns; j++) {
       grid[i][j] = columns[j];
     }
  }
  return grid;
}

console.log(makeGrid(3,4));
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
Answer: You were on the right track! Just like you had to create an array for each row, you have to also create an array for each column:

function makeGrid(numColumns, numRows){
  const grid = [];
  for(let i = 0; i < numRows; i++){
     grid[i] = [];
     for(let j = 0; j < numColumns; j++){
       grid[i][j] = []; // Previously: columns[j]
     }
  }
  return grid;
}

console.log(makeGrid(3,4));

On closer inspection after this fix, your variables rows and columns were unused. I removed them.
Also, you should prefer let and const over var, where applicable. In short: let and const are more similar to how variable declarations and scoping work in other languages, and unlike var they don't come with the (potentially confusing) features of being hoisted and redeclarable.
Comment: thanks for your help you helped me achieve the answer i was looking for, and I have taken on borad using let and const from now on
Answer: function makeGrid(numColumns, numRows){
    var grid = []

    for(let i = 0; i < numRows; i++){
        grid.push([])
        for(let j = 0; j < numColumns; j++){
            `turns out I was meant to make the grid equal to "j+1"`
            grid[i][j] = j+1;
        }
    }
    return grid
}

console.log(
    makeGrid(3,4)
)


How can I set android font family to make the width the same?

Question: The text of tvA include two spaces, and tvB include one space.
but in UI, the width of the two control are not same.
I hope the width both tvA and tvB the same, how do do? Thanks!
<code> <TextView
   android:id="@+id/tvA"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="1  2" />

 <TextView
   android:id="@+id/tvB"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="3 45" />
</code>
Answer: Default droidsans font is not Monospaced Font, so you can not make "wrap_content" textviews to be the same width. To do this, you have to use some customized font.
You should use some fonts like "courier new". Pack the ttf file with your APK(in assets folder) and do this in your code:
<code>Typeface tf = Typeface.createFromAsset(getAssets(),
        "fonts/CourierNew.ttf");
TextView tva = (TextView) findViewById(R.id.tvA);
TextView tvb = (TextView) findViewById(R.id.tvB);
tva.setTypeface(tf);
tvb.setTypeface(tf);
</code>
Comment: Why downvote? Default droidsans font is not Monospaced Font, so you can not make  "wrap_content" textviews to be the same width. To do this, you have to use some customized font. Am I misunderstanding the question or providing a wrong answer?
Comment: I thought you had answered for how to set font. I misunderstood.
Comment: It is OK. It was also my fault for not elaborating my answer. I have modified it and hope it could help.
Comment: Thanks! Can I copy windows 7 font cour.ttf to assets\fonts folder and use windows font?
Comment: Yes I think you can. And you can also google to get a lot of download resources. Tell us if it works.


Partial fraction on $\frac{2\cos^2(x)-1}{a^2-2a\cos(x)+1}$

Question: $$\frac{2\cos^2(x)-1}{a^2-2a\cos(x)+1}$$ I've seen this thing on an integral on this site and this is doable with partial decomposition (also checked with Wolfram), but my question is: how? I tried factoring since what I've learned is that you have to have factors in the denominator to do the: $$\frac{A}{\text{denominator 1}}+\frac{B}{\text{denominator 2}}$$, etc. But I don't know if having a $(\sqrt{1+a^2}+\sqrt{2a\cos(x)})(\sqrt{1+a^2}-\sqrt{2a\cos(x)})$ would help to do partial decomposition? Also tried long division since the degree is higher than in the denominator but didn't work either. Any hints?
Comment: What is the variable on which you want to integrate? $x$ or $a$? If you want to perform partial decomposition it should be $a$ as partial decomposition deals with rational fractions.
Comment: @Acyex: Are you looking for $$ \dfrac{2\cos^2(x)-1}{a^2-2a\cos(x)+1} = \dfrac{-a^4-1}{2 a^2 \left(-a^2+2 a \cos (x)-1\right)}-\dfrac{a^2+1}{2 a^2}-\dfrac{\cos (x)}{a}$$
Comment: yes i am @Moo, that's the one
Comment: @mathcounterexamples.net oh really? never thought of that, then I treat cos(x) as a constant or what? But the integral was with respect to x, but that's out of my point regardless, I'm only interested in the partial fraction decomposition and I'm still looking for one answer :(
Answer: I suppose that you are integrating for $x$.
The first thing I would do is to use the tangent half-angle substitution $x=2 \tan ^{-1}(t)$$
$$\int\frac{2\cos^2(x)-1}{a^2-2a\cos(x)+1}\,dx=\int\frac{2 \left(t^4-6 t^2+1\right)}{\left(t^2+1\right)^2 \left((a+1)^2
   t^2+(a-1)^2\right)}\,dt$$ Now
$$\frac{2 \left(t^4-6 t^2+1\right)}{\left(t^2+1\right)^2 \left((a+1)^2
   t^2+(a-1)^2\right)}=$$ $$-\frac{(a-1)^2}{a^2 \left(t^2+1\right)}-\frac{4}{a \left(t^2+1\right)^2}+\frac{a^4+1}{a^2 \left((a+1)^2 t^2+(a-1)^2\right)}$$
Comment: The numerator is a poly of degree 2 in $\cos x$, while the denominator is linear in $\cos x$ - as in the comments above, probably easier to do the division first before other substitutions...
Comment: You can also split the numerators and possibly the factored denominator of $\frac{a^4+1}{a^2(…)}$.
Comment: @TymaGaidash. There are so many things we could do ! Cheers ;-). By the way, congratulations for your questions !
Comment: @peterag. There are so many things we could do ! Cheers ;-).
Comment: @ClaudeLeibovici What do you mean by "congratulations"? I see, it may be possible to do partial fractions on the factored denominators. You can also leave the answer as is for simplicity.
Comment: I'm still looking for an answer that doesn't involve unintuitive substitutions, since what I asked was the partial fraction decomposition, not the integral, in spite of so, i appreciate your post!


Colocar uma url no campo text e mostrar ela em um DIV ao lado

Question: Como posso fazer isso? Tenho um formulário que tem alguns input text, gostaria que quando o usuário colasse uma url de uma imagem na web aparece ao lado um div com essa imagem. Creio que seria com Ajax mas não tenho nenhuma ideia de como começar.
Answer: Basta criar o elemento com a URL da imagem:

// SEM jQuery
// Executa a ação ao sair do campo, também pode usar `onkeyup`
// para ser executado tada vez que uma tecla é solta (mas não vejo necessidade)
document.getElementById('imagem').onblur = function(){
   // Pega o elemento onde será "impressa" a imagem
   var res = document.getElementById('result');

   // Cria o elemento img
   var img = document.createElement('img');

   // Atribui a URL como src
   img.setAttribute('src', this.value);

   // Limpa o lugar de "impressão"
   res.innerHTML = '';

   // "Imprime" a imagem
   res.appendChild(img);
}

// COM jQuery
// Executa evento ao sair do campo 'blur'
// Também pode usar 'keyup' para executar quando soltar a tecla
$(document).on('blur', '#imagem2', function(event){
  event.preventDefault();

  // Pega o elemento de "impressão"
  $('#result').html(
    // Define o HTML dele como um novo element
    // img com src do valor do input
    $('').attr('src', this.value)
  );

});

SEM jQuery: <input type="url" id="imagem" />

COM jQuery: <input type="url" id="imagem2" />

Comment: Kadu, muito obrigado!
Comment: Kadu,
Nesse seu script teria como eu não apresentar a imagem tamanho real? Gostaria de apresentar uma imagem de 50 x 50 px
Comment: Tem sim, com jQuery você coloca assim `$('').attr('src', this.value).css({'width': '50px', 'height': '50px')` sem faz assim: https://jsfiddle.net/tfx2op7p/1/
Comment: Kadu, deu certinho! Agora só preciso de mais 2 campos: Como posso pegar o que digitei no input text e exibir na div, o outro campo teria como pegar a data e hora atual e jogar em um input tbm?
Comment: @William a lógica é a mesma, só que você não vai precisar criar a tag `img` basta setar o valor da propriedade text assim `$(elemento).text( 'valor do texto' )`
Answer: Então, para esse resultado não é necessário AJAX, uma vez que seu usuário vai colar uma URL de imagem da web. Se você colocar a url no atributo SRC do elemento html IMG assim que o usuário colar, você vai obter o resultado esperado.
Creio que seu maior problema vai ser validar se a url gerou uma imagem válida. Segue uma sugestão de código:

window.changemeurlexample = function(e, el){
  var resultimg = document.querySelector('#urlexampleresult');
  resultimg.setAttribute('src',el.value);
  document.querySelector('.str').innerHTML = el.value;
};
var resultimg = document.querySelector('#urlexampleresult');
resultimg.onerror = function(){
  alert('Imagem inválida.');
}
.fleft{ float:left; }
.fright{ float: right; }
.fclear{ clear: both; }
.snippet #inputurl{padding: 5px; border: 1px solid #777;border-radius:2px;}
.result-image img{margin-left:20px;max-width: 200px;height:auto;display:block;min-width: 200px;height:200px;background-color:#eee;}

    <input onkeyup="window.changemeurlexample(event, this);" name="inputurl" id="inputurl" />

Answer: Olá,
De uma maneira bem simples, e sem validacoes ficaria mais ou menos assim:

$(function(){
  $('#btn_carrega_imagem').click(function(){
      $('#container_img').html('');
      $('#container_img').show();
  });
});

<form action="" method="post" >
    <input type="text" name="url_imagem" id="url_imagem" value="http://www.palmeiras.com.br/public/upload/imagem/times//imagem_20_original.png" />
    <button id="btn_carrega_imagem">Carregar Imagem</button>
</form>

Espero ter ajudado
Abraços
Answer: Aproveitando o gancho da pergunta, exibiu tudo certo, porém eu gostaria de não apresentar a imagem no tamanho real, teria como usar alguma função ou propriedade para carregar no tamanho exemplo 50px x 50px ?


How do I fix the xcrun unable to find simctl error?

Question: I have Xcode 6.2 Beta. Attempting
xcrun simctl

in terminal yields

xcrun: error: unable to find utility "simctl", not a developer tool or in PATH
Comment: My app was running without issue then suddenly I came across this. I had no license to agree to and command line tools was set. A simple reboot of my machine worked.
Comment: please select correct answer
Comment: After adding a second user to my Mac, I ran into this issue. This command resolved it!
Answer: I solved this problem by entering
Xcode > Preferences > Locations

And assigning the Command Line Tools
This is in Xcode Version 7.2 beta (7C46t)
Comment: "assigning the Common Line Tools" ... nice, but why aren't they set on install? haha
Comment: Great! After updating to Catlina 10.15.3 it simply disappeared.
Comment: Worked for Xcode 14 as well. They need to set it on install.
Comment: Note this also works when "pod lib lint My.podspec" throws the same error.
Comment: I also got this error after installing brew. This answer works like a charm, thanks!
Comment: If my Xcode have the above path setup. Shall i need the download the command line tools additionally in the machine
Comment: In case somebody like me stuck in the obvious image.

After enter the `Locations` Tabs, you should select the `Command Line Tools` to an options and the comment below will change to your Xcode path.

And then back to a new terminal, `simctl` is ready to go.
Comment: 'Preferences' has been changed to 'Settings...'
Answer: In Xcode, open the Xcode menu at the top, then select Preferences…, and then select the Locations tab.
Comment: This makes it a lot more clear how to make the change, thanks for pic!
Comment: Just clicking the dropdown causes the machine to ask for a password and fixed the issue.
Answer: In Terminal, try this.
sudo xcode-select -s /Applications/Xcode.app

/Applications/Xcode.app is your Xcode.app path.
If you still get an error in the terminal.
try  sudo xcodebuild -license to agree to the license.
Comment: This is what worked for me. I always had Xcode installed and always worked in the IDE, but this is the first time that I am using Xamarin in VS for Mac. Once I issued the second command in the terminal and started the debugger, the "Deploying to Device" window showed that I accepted the license and then started installing additional components.
Comment: This answer should have way more visibility. According to how you installed xcodebuild you could not have licenses accepted, things don't work and you don't know why
Answer: Got similar issue on executing command
./Scripts/bootstrap.sh -d.

This helped me Xcode > Preferences > Locations, Set Command line Tools
Comment: How classic issue..
Comment: Weird, but works! Thanks for all the help man, I don't know what I'd do building iOS stuff without this kind of help!
Comment: Yeap, That's it...
Answer: I had the same problem. My application was working well but suddenly in next run, it started throwing the "simctl" error. It seems I had started Xcode update installation in the background.
Fix: I just started the Xcode application and it prompted to install some pending tools update. After Xcode updates, my app started working normally.
Answer: Had this issue after the latest version of XCode (Version 14.0 (14A309)) installed itself.
For me the Command Lint Tools were all installed etc and it made no sense; none of the above worked. However when running xcrun -v simctl it showed me that my SDKPATH was set to version 15.5 of the SDK; the new version is 16.0.
To resolve I added the below line to the top of my .zshrc file and restarted my terminal.
export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk

Note: The 'file' iPhoneSimulator.sdk is a simlink to the latest SDK version so I hope I don't need to change this again!
Comment: So my issue here is that I apparently defined SDKROOT in my .zshrc.  Simply removing the `export SDKROOT` was enough to allow the properly-selected Command Line Tools selection to work.
Comment: it works also for minor version 14.3 (14E222b)
Answer: While running Xcode, open the Xcode menu, go to Preferences…, then select Locations
In Locations, "Command Line Tools", choose your version of Xcode.
It should be fine. This worked for me.
Answer: Choose Xcode Preferences then choose Locations tab and inside go to command line tools Drop down box and choose one.
Problem sovled !
FYI:
I tried this with Xcode 12.3
Comment: Worked for 13.3.1. Thanks!
Comment: Also worked for Xcode 14.2
Answer: If you are interested in command line "approach", please try: installer -pkg /Applications/Xcode.app/Contents/Resources/Packages/XcodeSystemResources.pkg -target /. In addition, please make sure that xcode-select -s selected right Xcode installation path.
Answer: adding xcode in preference-> locations works fine
Comment: Adding command line tools as xcode version in preference-> locations works fine
Answer: You are facing this issue because the path of command line tools are not configured correctly in your XCode. Please navigate to Xcode > Settings > Locations tab . Unselect and select the XCode version name option and that should resolve this issue.
enter image description here
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: Here are a few steps you can try to fix this error,
1.) Clean and Rebuild Solution: Clean the solution in Visual Studio by going to the "Build" menu and selecting "Clean All" or using the keyboard shortcut Shift + Command + K. After that, rebuild the solution by selecting "Build All" from the "Build" menu or using the keyboard shortcut Command + B.
2.) Verify Build Configuration: Make sure you have the correct build configuration selected. Go to the toolbar at the top of Visual Studio and check the selected build configuration (e.g., Debug, Release). Ensure that you're trying to launch the application with the appropriate build configuration.
3.) Check Provisioning Profiles: Ensure that the provisioning profiles used for the app are correctly configured. Make sure you have valid provisioning profiles for the device or simulator you're trying to run the app on. You can check and manage your provisioning profiles in Xcode's "Preferences" under "Accounts" and ensure they are up to date.
4.) Restart Visual Studio and Simulator: Quit Visual Studio for Mac and close the iOS Simulator. Then, relaunch Visual Studio and the Simulator to see if the issue persists.
5.) Update Xcode and iOS Simulator: Make sure you have the latest version of Xcode and the iOS Simulator installed. Open the App Store on your Mac, go to the Updates tab, and install any available updates for Xcode or the iOS Simulator.
Answer: following are the steps to solve this issue -

open terminal on your mac
type cd.. 2 times
Now go to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs
Now type ls, you will find sdk's here. Fir iPhone, you should see iPhoneOS.sdk.
copy this path as /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk
now reopen the terminal and type export SDKROOT=/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk
now this error should be removed and your devices should be now recognised by system


java-With multicastSocket, recipients can not receive broadcasts

Question: Learning java MulticastSocket, the same LAN only the machine can receive the broadcast, the other equipment can not. why? Is the router setting problem or the broadcast address setting problem?
send.java
public class sentServer {
    public static void main(String[] args) {
        String host = "188.8.131.52";
        int port = 9998;String message = "test-multicastSocket";
        try {
            InetAddress group = InetAddress.getByName(host);
            MulticastSocket s = new MulticastSocket();
            s.joinGroup(group);
            DatagramPacket dp = new DatagramPacket(message.getBytes(),message.length(),group,port);
            s.send(dp);
            s.close();
        } catch (UnknownHostException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {e.printStackTrace();
        }
    }
}

The listening address set here is 22.214.171.124
recevier.java
public class reClinet {
    public static void main(String[] args) {
        String host="22.214.171.124";
        int port=9998;
        int length=1024;
        byte[] buf=new byte[length];
        MulticastSocket ms=null;
        DatagramPacket dp=null;
        StringBuffer sbuf=new StringBuffer();
        try {
            ms=new MulticastSocket(port);
            dp=new DatagramPacket(buf,length);
            InetAddress group=InetAddress.getByName(host);
            ms.joinGroup(group);
            System.out.println("port is open");
            ms.receive(dp);
            ms.close();
            int i;
            for(i=0;i<1024;i++){
                if(buf[i]==0){
                    break;
                }
                sbuf.append((char)buf[i]);
            }
            System.out.println("message"+sbuf.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

`
Thanks
Comment: Thanks for accept!
Answer: In case you are asking: why can only systems attached to the same network segment see broadcasts?
That is the nature of broadcasts in Java: a client connects to a specific server; and joins the broadcast group; then that client will be notified.
If a client doesn't get those notifications; you have to look into your network settings, firewalls, ...


All continuous functions are analytic

Question: This might be very silly to ask, but somehow this sequence of results are leading me to this wrong result. I am dealing with complex analysis and the mistake I am making might be because I am using some results from real analysis.
If a function, $f(z)$, is continuous in simply connected domain, then it will be Riemann integrable and hence its antiderivitive, $F(z)$, will exist and moreover the antiderivative will be differentiable in the domain.
This implies that $F(Z)$ is analytic since it is differentiable in the neighborhood of all points.
Which also means that it is infinitely times differentiable.
And hence even $f(z)$ is infinitely times differentiable and hence, $f(z)$ is also analytic.
Comment: Have you tried setting $f(z)=\overline{z}$, for example, to see at which step you argument breaks down?
Comment: How do you define the anti derivative?
Comment: a function F such that F'(z) = f(z)
Comment: What is the question?
Answer: Your second point is where it breaks. The antiderivative exists iif the integral from one point to another is independent from the path that is taken which is not guaranteed by continuity.
Comment: Yes on a compact for instance. But to define the antiderivative you have to choose a point, lets say (0,0) , an then define F(x,y) as the integral from you get from going from (0,0) to (x,y) and to do that you have to choose a path to integrate on. The problem is that you have no guarantee that the "F(x,y)" you just calculated doesn't depend on the path you arbitrary chose. For example the result may be different if you go (0,0)-->(0,y)-->(x,y) or if you go (0,0)-->(x,0)-->(x,y) in straight lines.
Comment: Part of the problem for the OP is the misleading name of "integral" that is often given to the antiderivative.
Comment: Are not all continuous functions Riemann integrable?
Answer: You are mixing up complex differentiability and real differentiability.
Comment: I was ..got it now..thank you.
Answer: Take $f$ defined on the real line by $f(x) = e^{-1/x}$ for $x>0$ and $f(x)=0$ if $x\leq 0$. The function $f$ is continuous, and is even infinitely differentiable, on the real line, but is not analytic. Indeed, you prove that $f^{(n)}(0)=0$ for all $n$, which shows that $f$ that cannot be analytic on any interval containt $0$ in its interior, as it would then be (by analytic continuation) equal to the zero function.
Comment: That doesn't really answer the question. OP is aware that the result does not hold, (s)he asks to point a flaw in the argument.

All continuous functions are analytic


How save work document in .pdf format in C#

Question: I replace the fields in word template with some values using C#, then I need to save the word document as .pdf file. I am able to save it as a .doc file but not .pdf.
Answer: You need to tell it the new format instead of just a new name. Changing the string name will still try to save it as a word doc, but then the .pdf extension will have Word trying to open your (still Word) document as a pdf.
wordDoc.SaveAs(@"C:\Documents\myFile.pdf", WdSaveFormat.wdFormatPDF);

Answer: I would say need some 3rd part libs to save as a pdf file.


Send email to only certain Users, Rails 5

Question: I'm having trouble sending an email blast to only certain users who have a boolean set to true and to not send the email to those users who have it set to false.
In my app I have Fans following Artists through Artists Relationships. Inside my ArtistRelationship model I have a boolean that fans can set to true or false based on if they want email blasts from Artists or not when the Artist makes a post.
So far, I have this:
artist.rb
class Artist < ApplicationRecord

  def self.fan_post_email
    Artist.inlcudes(:fans).find_each do |fan|
      fan.includes(:artist_relationships).where(:post_email => true).find_each do |fan|
        FanMailer.post_email(fan).deliver_now
      end
    end
  end

end

posts_controller.rb
class Artists::PostsController < ApplicationController

  def create
    @artist = current_artist
    @post = @artist.artist_posts.build(post_params)
    if @post.save
      redirect_to artist_path(@artist)
      @artist.fan_post_email
    else
      render 'new'
      flash.now[:alert] = "You've failed!"
    end
  end

end

I'm having trouble getting the fan_post_email method to work. I'm not entirely sure how to find the Fans that have the boolean set to true in the ArtistRelationship model.
Answer: You want to send mails to fans of a particular artist. Therefore you call
@artist.fan_post_email

That is you call a method on an instance of the Artist class. Instance methods are not defined with a self.[METHOD_NAME]. Doing so defines class methods (if you where to call e.g. Artist.foo).
First part then is to remove the self. part, second is adapting the scope. The complete method should look like this:
def fan_post_email
  artists_relationships
    .includes(:fan)
    .where(post_email: true)
    .find_each do |relationship|
      FanMailer.post_email(relationship.fan).deliver_now
    end
  end
end

Let's walk through this method.
We need to get all fans in order to send mails to them. This can be done by using the artist_relationships association. But as we only want to have those fans having checked the e-mail flag, we limit those by the where statement.
The resulting SQL condition will give us all such relationships. But we do it in batches (find_each) in order to not have to load all of the records into memory upfront.
The block provided to find_each is yielded with an artists_relationships instance. But we need the fan instances and not the artists_relationships instances to send the mail in our block and thus call post_email with the fan instance associated with the relationship.  In order to avoid N+1 queries (a query for the fan record of every artists_relationships record one by one) there, we eager load the fan association on the artists_relationships.

Unrelated to the question
The usage of that method within the normal request/response cycle of a user's request will probably slow down the application quite a lot. If an artists has many fans, the application will send an e-mail to every one of them before rendering the response for the user. If it is a popular artist, I can easily imagine this taking minutes.
There is a counterpart to deliver_now which is deliver_later (documentation. Jobs, like sending an e-mail, can be queued and resolved independent from the request/response cycle. It will require setting up a worker like Sidekiq or delayed_job but the increase in performance is definitely worth it.
If the queueing mechanism is set up, it probably makes sense to move the call to fan_post_email there as well as the method itself might also take some time.
Additionally, it might make sense to send e-mail as BCC which would allow you to send one e-mail to multiple fans at the same time.