send push notification form my server PHP

Question: I'am trying to send push notification from my localhost to my iDevices all work properly but in the PHP error log I got the warning below Why ?
NOTE: I receive the Push on all Devices
THE WARNING:
PHP Warning:  socket_close(): supplied resource is not a valid Socket resource in /Applications/MAMP/htdocs/Push/SendPush.php on line xxx

Some of My Code:
//....
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert);

$apns = stream_socket_client('ssl://' . $apnsHost . ':' . $apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext);
//...

socket_close($apns);
fclose($apns);

Answer: Most likely Apple is terminating the connection after it receives your payload.
To silence the warning make the following change:
@socket_close($apns);

Answer: stream_socket_client() returns false if there was an error. You should explicitly test for it:
$apns = stream_socket_client(...);
if ($apns === FALSE) then
    die("Error while getting stream socket ($error): $errorString");
}

where $error/$errorString are the ones you've specified in the stream_socket_client() call.
Comment: hello i added ur code if(...){} else{echo "..."}; I got the else echoing witch mean $apns == True, and I still got the warning


Strong parameters and Nested Routes - Rails 4.0

Question: I have no idea how this works in rails but I set up routes like this:
  resources :users do
    resources :api_keys
  end

(User has_many: api_keys, api_key belongs_to: user)
So I then (since I only care about API Keys), created the following controller:
class ApiKeysController < ApplicationController
    before_action :authenticate_user!

    def index
        @user = User.find(params[:user_id])
        @api_key = User.apikeys
    end

    def create
        @user = User.find(params[:user_id])
        @api_key = ApiKey.new(create_new_api_key)
        create_api_key(@api_key, @user)
    end

    def destroy
        destroy_api_key
    end

    private

    def create_new_api_key
        params.require(:api_key).permit(user_attributes: [:id],  :api_key)
    end

end

Which states, authenticate user before every action, index fetches all api keys based on a user id. create is suppose to create an api key based on a user id, (note: create_api_key(@api_key, @user) just an abstracted method that states - if we saved, redirect to user_path with a message, if we failed, back to user path with a error message)
And destroy, well that just finds an api key, destroys it and redirects (again with the abstraction).
Whats the issue?
the create_new_api_key method. Its freaking out and saying:

syntax error, unexpected ')', expecting => (SyntaxError)

I thought this is how I pass in the user id ??
Answer: You need to change the order of the arguments passed in to permit to fix the syntax error:
def create_new_api_key
    params.require(:api_key).permit(:api_key, user_attributes: [:id])
end


Is this derivative correct ?- solved

Question: I want to compute
$$\frac{d}{dt}\left[ \int_t^{\tau}e^{-r(s-t)}(-pc) \,ds\right]$$ First, I know that I can just solve the integral and take the derivative:
$$\frac{d}{dt}\left[ \int_t^{\tau}e^{-r(s-t)}(-pc) \,ds\right]=\frac{d}{dt}\left[ \frac{-pc}{r}\left(1-e^{-r(\tau-t)}\right)\right]$$
$$=pc\cdot e^{-r(\tau-t)}$$
however, I want to solve it "straight away" using the Fundamental Theorem of Calculus. However, I must be doing something wrong because I obtain the following:
$$\frac{d}{dt}\left[ \int_t^{\tau}e^{-r(s-t)}(-pc) \,ds\right]=-e^{-r(t-t)}(-pc)-pc\int_t^{\tau} \frac{d}{dt}e^{-r(s-t)}ds$$
$$=pc-pc\cdot r\int_t^{\tau} e^{-r(s-t)}ds$$
$$=pc+pc [e^{-r(\tau-t)}-1]$$
$$=pc\cdot e^{-r(\tau-t)}$$
Comment: Initially, I did an algebra mistake and wasn't getting the same result for the second equation. Now it seems to be right. The magic of typing in latex code :). Already wrote the question though. So tell me if the way I compute this second derivative is correct according to you.
Comment: You are using the wrong formula $$\frac{d}{dt}\int_{a(t)}^{b(t)}u(t,s)ds=\int_{a(t)}^{b(t)}\frac{\partial u}{\partial t}(t,s)ds$$ instead of $$\frac{d}{dt}\int_{a(t)}^{b(t)}u(t,s)ds=\int_{a(t)}^{b(t)}\frac{\partial u}{\partial t}(t,s)ds+b'(t)u(t,b(t))-a'(t)u(t,a(t))$$ In your case, $$\frac{d}{dt}\int_t^\tau u(t,s)ds=\int_t^\tau\frac{\partial u}{\partial t}(t,s)ds-u(t,t)$$
Answer: $\frac{d}{dt} \int_t^\tau e^{-r(s-t)}(-pc)ds$
$= \frac{d}{dt}\left[- \int_\tau^t e^{-r(s-t)}(-pc)ds\right]$
$= \frac{d}{dt} \int_\tau^t pc \cdot e^{rt} \cdot e^{-rs}ds $
$= pc \cdot \frac{d}{dt} \left [ e^{rt}\cdot \int_\tau^t f(s)ds\right], $
where $f(s) = e^{-rs}$. Try using the fundamental theorem now.
This doesn't really make it much easier, because you'll still have to evaluate the integral when using the product rule.
Comment: I don't think this is right. Note that $f(s)$ actually depends on $t$!
Comment: I realized that so I updated my answer. You need to use the product rule too

Is this derivative correct ?- solved


How can I collect shipping information?

Question: I can't figure out how to get the shipping address information to be collected on checkout in Commerce on Drupal 10.
My setup

Created a Manual payment gateway that collects billing information.
Installed the Commerce Shipping module (version 2.6).
On /admin/commerce/config/order-types/default/edit, set Workflow to Fulfillment,  checked the box Enable shipping for this order type, and set the Checkout flow to Shipping as instructed in the module README.
Added four different flat rate shipping methods at /admin/commerce/shipping-methods.  None of the shipping methods have any conditions to limit visibility; they should all be shown.

However, when I add a product to the cart and then go to checkout, shipping information is never displayed.  I do see the payment information (to input a billing address) and contact information (input an email).  This happens both for anonymous and logged-in users (even user 1, so it's not a permissions issue).
The Shipping checkout flow has "Shipping information" under Order information, which is the default configuration.
Comment: Have you enabled the "Shippable" trait on the product variation type?
Answer: Have you enabled the "Shippable" trait on the product variation type?

How can I collect shipping information?


Is there room for an electric guitar in Superstition (Stevie Wonder)?

Question: Long story short, we are going to be playing an instrumental accompaniment to this song at school. I can play either a guitar or bass. I know that the lead riff is a clavinet and there is a bass line:
Is there a separate electric guitar or is it just bass and clav? Or is there a good way to work in an electric guitar part?
The current ensemble is:

Piano
Reeds
Drums
Bass
Possibly electric guitar

Edit: Thanks for everyone's help! I ended up playing the lead guitar riff and we have another bass player.
Comment: By chance, I happened to see a few days ago a clip of Stevie Wonder performing this song, circa 1972. There was a guitarist who seemed to be doubling the riff.
Comment: If you mean the song by Stevie Wonder I will say that my band does that song with two guitars, a bass and drums.  We don't have a clav or any other type keys or any horns.  We do a quite authentic and recognizable rendition with just the guitars.
Answer: I don't know why nobody else has mentioned this, but Stevie Wonder originally wrote "Superstition" to be a guitar song, not a keyboard song. Stevie Wonder wrote "Superstition" for guitarist Jeff Beck and his band Beck, Bogert and Appice in 1973.
Jeff Beck recorded the original version (with slightly different lyrics) which had no keyboards at all. Because of the record labels' schedules, the Stevie Wonder version was released first and became a bigger hit, but that is not how Stevie Wonder and Jeff Beck intended it to happen.
Listen to Jeff Beck's guitar-centric version.

Furthermore, guitarist Stevie Ray Vaughan and his band did an excellent cover of "Superstition" in 1986. Behind the lead guitar are keyboardist Reese Wynans playing both Clavinet and Hammond organ. Stevie Wonder made a cameo appearance in the video, lending his approval to this version as well.

Update: I just realized that in 2010, when Stevie Wonder performed at the Rock and Roll Hall of Fame concert, he performed "Superstition" together with Jeff Beck on lead guitar.

So yes, guitars and "Superstition" are a natural.
Answer: The original recording is actually two clavs, bass, drums, 2 brass tracks, vox.
If you have a keyboard player for the main hook riff, the guitarist could comp the 2nd clav line, which is much more chordal.
Though if it's a choice between guitar or bass, then the bassline is far more important, imo.
I uploaded a few bars to Soundcloud showing just drums, bass, 2nd clav line.
[perms for extracts for educational use only]
Answer: In funk there is always room for electric guitar! (Or two, as in this live in the studio video of the song.) Try 1-2 string "chords", heavily muted, playing rhythm.
Answer: As tetsujin says, take the second clav part, or double up the first, or even make up a second riff that works against the first. Then, after the riffy bit, play chords to help fill out the horns part. I've done that in several bands which played this great song.


Interpretation of the Error Correction Term as time to correct

Question: I have the following question that I haven't managed to find a satisfying answer. In an Error Correction Model (assuming that all its assumptions hold):
$$\Delta y_{t} = a + b(y_{t-1}-\hat c-\hat kx_{t-1}) + c\Delta y_{t-1} + d\Delta x_{t-1}+ e_{t}$$
what is the accurate interpretation of $b$ as the time that is required to correct the deviation from disequilibrium? Of course it has to be $-1 < b < 0$.
Until now what I have found is:
1) That $ln(2)/b$ measures the half life ie the number of periods that are required to correct half the deviation from equilibrium. Can we infer something about the time that is required to correct fully the deviation?
2) That $1/b$ measures the number of periods that are required to correct fully the deviation ignoring any other short-term disruptions.
Complete answers and especially references that discusses exactly this are much appreciated. Thank you in advance!
Comment: Here is a video tutorial that can help you! https://youtu.be/lvyTjcI9po4 Regards,
Answer: I'm afraid your exploration so far of the intuition behind $b$ is incorrect. By definition, the correction mechanism is asymptotic. This means that it always takes infinite time to adjust. As such, $b$ cannot be associated with a time measure.
To back up my claims, and without loss of generality, consider a simplified model:
$$ \Delta y_{t} = -b(y_{t-1} - \bar{y}) + e_{t} $$
Note I have defined $b$ as positive. This is just for simplicity.
Assume that there was a shock in $t=0$ so that $y_{0} \neq \bar{y}$, and there was no shock thereafter (you can adapt this to put the shock in period $t$ and then look into the future). This is, $e_{t} = 0 \quad \forall t >0$.
Then, we can re-write the model as:
$$ y_{t} - y_{t-1}  = -b(y_{t-1} - \bar{y}) $$
Rearranging:
$$ y_{t} = (1-b)y_{t-1} + b\bar{y} $$
This is, current level is a weighted average of previous level and long-run level. This should immediate deny any relation between time and $b$. But let's continue.
Now, iterate from the above equation using backward substitution. You will get:
$$ y_{t} = (1-b)^t y_{0} + b\bar{y}\big(1 + (1-b) + (1-b)^2 + \cdots + (1-b)^{t-1}\big) $$
The sum inside the parenthesis is a geometric series. Thus, the equation can be written as:
$$ y_{t} = (1-b)^t y_{0} + b\bar{y}\big(\frac{1-(1-b)^{t}}{1-(1-b)}\big) $$
Simplifying the $b$:
$$ y_{t} = (1-b)^t y_{0} + \bar{y}\big(1-(1-b)^{t}\big) $$
Rearranging:
$$ y_{t} = \bar{y} + (1-b)^t(y_{0} - \bar{y}) $$
From here you can see that convergence into the long-run level, or steady state, only happens asymptotically, for $0<b<1$. This is:
$$ \lim\limits_{t \rightarrow \infty} y_{t} = \bar{y} $$
To conclude, $b$ has no time interpretation, as convergence always takes infinite time. The correct interpretation of $b$ is as the speed of adjustment. Although apparently counterintuitive, they are unrelated.
Comment: I am not convinced that this is correct. What you wrote, I think, is correct for the particular case when the long run equilibrium level is constant; if so, note that this is at tremendous loss of generality. The y bar in your initial equation should be replaced with the cointegration coefficient * cointegration variable, whose value would change every period.


XMPP Server on EC2 Amazon Web Service (AWS)

Question: My company uses OpenFire for server-side and smack for client-side in its XMPP Android application.
AWS seems like a good and scalable service for what we need.
We use it for testing our app, but I'm afraid that the server will crash with 20k-50k users.
I have 2 questions:

Is AWS good enough for an XMPP (OpenFire) server? What are the pros and cons?
How do I build such an application that can handle 20k online users at least, and lets say 2k opened chat rooms?
Is there any specific tutorial for this kind of stuff?

Money is not a problem in terms of server costs. Time is what matter for us right now.
Comment: Does OpenFire support running your XMPP service across multiple servers? Because if it does I would think that AWS would be great for that. You could bring up new servers and spread the load as you add more users.
Answer: AWS will work for what you intend without any problem, things to be aware though of an EC2 implementation

You'll lose CPU cycles when the underlying node is under high load, be ready for your machines to sometimes not deliver enough CPU juice
Disk I/O will be a bit slower than a regular machine

Apart from that Openfire does have a clustering solution, which is commercial, and as far as I know the company behind it died (and they haven't open sourced it, gah), I've been trying to contact them to get the clustering solution myself, to no avail.
So if you choose Openfire you'll be stuck with one server having to carry all the workload, which sounds a bit stressing with the numbers you're talking about, if you want to start with Openfire it looks like a good easy way to get rolling but when you need to be aware of your options when you start to grow ;)
For tutorials have a look at the Openfire howto at http://ubuntuforums.org/showthread.php?t=525670, it's not a bad one :)
Comment: I need the ability to grow. Do you recommend another XMPP server-side application? Also, what about this connection module? http://www.igniterealtime.org/projects/openfire/connection_manager.jsp
Comment: Any XMPP server should do the task, although clustering is a bit of a daunting task. That connection module will connect your XMPP server to other networks, maybe you can end up using this to connect multiple XMPP servers between them, but they'll see the users as being on remote servers, try it out though.
Comment: ejabberd scales a bit more linearly.
Comment: I just found this thread: http://community.igniterealtime.org/thread/32723 . They say that we should use: http://docs.safehaus.org/display/PENROSE/Home . After reading about this it sounds exactly like what AWS does. am I wrong?
Comment: Yeah, that's the main issue, if you have separate Openfire servers users will see one each other form different domains, as Tom O'Connor says ejabberd will be a bit more linear to grow but also the learning curve is steeper than Openfire. Try starting your project with Openfire so you can test your code but keep in mind that you'll need to look at other XMPP servers as soon as you start growing.
Comment: hi @lynxman what happened with you please help


range-expression of range based for loop in C++

Question: I am trying to pass a pointer of vector to range based for loop for its range-expression.
Here is the syntax of range based for loop:
attr(optional) for ( init-statement(optional) range-declaration : range-expression )
loop-statement

Referenced from cppreference.com:
range-expression is evaluated to determine the sequence or range to iterate. Each element of the sequence, in turn, is dereferenced and is used to initialize the variable with the type and name given in range-declaration.

begin-expr and end-expr are defined as follows:

    If range-expression is an expression of array type, then begin-expr is __range and end-expr is (__range + __bound), where __bound is the number of elements in the array (if the array has unknown size or is of an incomplete type, the program is ill-formed)
    If range-expression is an expression of a class type C that has both a member named begin and a member named end (regardless of the type or accessibility of such member), then begin-expr is __range.begin() and end-expr is __range.end();
    Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed).

I defined begin and end and expect them to be used for begin-expr, to dereference the pointer, but failed. Here is my codes:
#include <iostream>                // std::cout
#include <vector>
using namespace std;

vector<int>::iterator
begin(vector<int> *a)
{
   return a->begin();
}

vector<int>::iterator
end(vector<int> *a)
{
   return a->end();
}

int main()
{
    vector<int> v = {1,2,3,4};
    vector<int> *p = &v;
    for (auto i : p) {
        cout << i << endl;
    }
    return 0;
}

I am still getting the below compile error:
Invalid range expression of type 'vector<int> *'; did you mean to dereference it with '*'?

Is there anything I missed here?
Comment: Change the loop to `for (auto i : *p)` and you don't need to bother with your `begin()` and `end()` functions [which won't work, as the lookup of `begin()` and `end()` for a range-based loop uses ADL which doesn't work as you want/need for pointers].
Comment: Simpler, just get rid of the pointer altogether: `vector v = {1,2,3,4}; for (auto i : v) { ... }`
Answer:
Otherwise, begin-expr is begin(__range) and end-expr is end(__range), which are found via argument-dependent lookup (non-ADL lookup is not performed).

begin() and end() are looked up only via ADL. For pointers, it works like this:

For arguments of type pointer to T or pointer to an array of T, the type T is examined and its associated set of classes and namespaces is added to the set.

The only namespace associated with std::vector<int> is namespace std, so that's where begin() and end() will be looked up.
Putting begin() and end() into namespace std makes the code work, but adding new declarations into std causes undefined behavior (with a few exceptions), and shouldn't be done.


catching optional part in regular expression

Question: I have an input text which can be either:
"URL: http://www.cnn.com Cookie: xxx; yyy"

or just:
"URL: http://www.cnn.com"

How do I capture both URL and cookie into two separate variables in Python? The part I don't know how specify is the optional cookie.
Thanks.
Answer: import re

inputstring = "URL: http://www.cnn.com Cookie: xxx; yyy"

if 'Cookie' in inputstring:
    m = re.match('URL: (.*?) Cookie: (.*)', inputstring)
    if m:
        url = m.group(1)
        cookie = m.group(2)
        print url
        print cookie
else:
    m = re.match('URL: (.*)', inputstring)
    if m:
        url = m.group(0)
        print url

Answer: Just use separate capture groups, and ? for the optional part of your regex. If a capture group doesn't capture anything the group's value will be None.
>>> regex = re.compile(r'URL: (\S+)(?:\s+Cookie: (\S+))?')
>>> regex.match("URL: http://www.cnn.com Cookie: xxx;yyy").groups()
('http://www.cnn.com', 'xxx;yyy')
>>> regex.match("URL: http://www.cnn.com").groups()
('http://www.cnn.com', None)

I've just used \S+ for the URL and cookie patterns in the above for example purposes. Replace them with your real URL and cookie patterns.
Instead of groups() you can use group(1) and group(2) -- the behavior is the same, but groups() is nice with unpacking. eg:
url, cookie = match.groups()

Answer: str = 'URL: http://www.cnn.com Cookie: xxx; yyy'

match = re.search(r'URL: (\S+)( Cookie: (.*))?', str)
print match.group(1)
print match.group(3)

>>> http://www.cnn.com
>>> xxx; yyy

Comment: Thanks, I didn't know groups can be nested.
Answer: Enclose the optional part in (Cookie: xxx; yyy")?


User permissions database design using PostgreSQL's inheritance

Question: I have a task of creating a database using PostgreSQL. I have to implement user permissions through inheritance. I don't have a clear vision on how to do that. Let's say i have 3 user roles: administrator, moderator and registered user. What i was thinking is to have a users table which would hold standard data about the user himself (first name, last name, email, password...). Table users wold have a FK to a table with the group that a user belongs to (moderator, administrator or registered user) so i know which table to query to get the permissions.
Since administrator and moderator have the permissions that a registered user has i thought that administrator and moderator tables would inherit permissions of the registered user and add their own permissions specific to them. The tables would be there just for the permissions they would not have a relationship with any other tables.
Then later on i would query the user_group table to see which group user belongs to and then query the right table to get the permissions (which would be of type boolean).
But with this approach i don't see a way to restrict a certain permission for a specific user (for example posting comments). I would have to restrict the permission for the whole group.
Any suggestions on the best way to do this would be highly appreciated.
Answer: A typical ACL based security schema sounds very much like you described. A User can have one or more Roles, a Role can have permissions (a role seems the same as your group).
The answer to your question pretty much depends on the level of granularity that you need (in a project i have worked on we had the need an extra level to the classical example described above). As i see your example, you have two options:

Assign the permissions directly to users. Doesn't seem the case since you also need the roles (admin, moderator) etc. And if a role has access to posting comments usually you do not want to restrict it to a few users (if you want to do this to more users than maybe its the case for another role)
If you need this though, maybe an exception mechanism can work. A user has a role, BUT there can be a separate table to store the exceptions, the permissions not allowed for him even though it has a certain role
Comment: Tnqu :) option number 2 seems like the right choice... After posting the question i had an idea that i could make each of the tables inherit the users table and store the users there, but soon realised that i would have to migrate the data about the user in case i want to change the role he belongs to


Is there an easy way to find the (number of) subgroups of a given group?

Question: Is there an easy way to find all subgroups of a given group? For example, say you had the dihedral group $D_{4}$ - is there a way to work out how many subgroups this has, or what they are, or can it only be done by trial and error or inspection?
Comment: Finding subgroups is at least as hard as factorizing integers because $\mathbb{Z}_n$ has a subgroup corresponding to every divisor of $n$, and the expected difficulty of factorization is the basis of the belief in the security of RSA encryption.
Comment: One set of tools that can provide a very slick solution to these kinds of questions is called "The Sylow Theorems."
Comment: I don't know what you have in mind when you say "trial and error or inspection." The worst thing you could do is literally to test every subset to see if it's a subgroup or not. Of course you can do much better than this. First, you can try to identify the cyclic subgroups generated by every element. Next, you can try to identify the subgroups generated by every pair of elements (piggybacking on your previous calculations). And so forth. Depending on what the group is you can try various more sophisticated things, like finding Sylow subgroups, applying Goursat's lemma...
Comment: In general, finite groups can have a lot of subgroups. For example, a vector space over $\mathbb{F}_p$ of dimension $n$ has subgroups corresponding to subspaces of dimension $0 \le k \le n$. The number of subspaces of dimension $k$ is the Gaussian binomial coefficient ${n \choose k}_p$, so the total number of subgroups is the sum of these.
Answer: I think the answer to the question "Is there an easy way to find all subgroups of a given finite group?" is no.
There are of course methods for doing this that are used by GAP and Magma, which are very effective for small and moderately large groups, but I would not describe them as easy. Also, as far as I am aware, none of the current implementations are complete algorithms, in the sense that they will not, even theoretically, work on arbitrarily large groups. The older methods required databases of perfect groups, which of course could only be complete up to some order.
The newer methods require knowledge of the maximal subgroups of all finite almost simple groups. This is still not completely known theoretically, although is is still a very active area of research. For a complete description, you would need to know (or understand) all irreducible modular representations of all almost simple groups. The maximal subgroups of the Monster sporadfic group are still not completely determined, but there are only a small number of uncertainties remaining.
Answer: Consider only abelian $p$-groups of a fixed order, say $p^n$.
Let $C=$cyclic group of order $p^n$ and $E=$ elementary abelian $p$-group of order $p^n$.
Let $G$ be any abelian $p$-group of order $p^n$. Then
$$ 1=|\mbox{subgr. of order} p^k  \mbox{ in C}| \leq |\mbox{subgr. of order} p^k  \mbox{ in G}| \leq |\mbox{subgr. of order} p^k  \mbox{ in E}| $$
The number of subgroups in cyclic or elementary abelian $p$-group are very well known.
In arbitrary abelian $p$-group, it is possible to describe by combinatorial argument the number of subgroups of a given order. But its complexity increases because of
(1) structure of $G$ and
(2) all the possible structures of subgroups of order $p^k$ in $G$.
So far, this is vague reason only for abelian $p$-groups. For non-abelian $p$-groups, it is further more difficult. (The study of non-abelian $p$-groups is especially concentrated on a specific class of groups of order $p^n$, rather than all the groups of order $p^n$.)
At last, I would say, there is no easy way to do the problem you posed.


node.js scalability with event timers (setTimeout)

Question: I'm building a turn-based text game with node.js and socket.io. Each turn has a timeout and after that the player loses the turn and it passes to the next player. I'm using the setTimeout function as I said in another question.
The problem is that I don't know how to scale that over multiple instances and maybe multiple servers. AIUI, if I set a timeout, I could only clear it in the same instance. So if a player loses his turn, for example, the timeout will be renewed with the other player turn, but this new player won't have access to the timer object to clear it, because it's running on the first player's instance.
I looked at Redis pub/sub feature (which I'll have to use anyway), but I didn't find anything about timed events or delayed publishing.
TL;DR, how can I keep an instance/server independent timer?
Answer: The solution I've found to this is to use some message system (Redis pub/sub in my case) to keep each player instance aware of the current status.
Each player has a worker instance which handles his own turn (this includes the timer). When it finishes, either via a move by the player or via the timeout, it advances the turn counter and informs all instances via the pub/sub with the new turn number. All of the instances receive the message and compares the turn number with its own player number. If it matches, then the instance handles the turn and the cycle repeats.
I'll try to provide an example (more of a pseudocode):
// pub & sub are Redis publisher & subscriber clients, respectively

function Game (totalPlayers, playerNumber) {
  this.turn = 0
  this.totalPlayers = totalPlayers
  this.playerNumber = playerNumber

  // Subscribe to Redis events
  sub.on('message', function (channel, message) {
    message = JSON.parse(message)

    switch(message.type) {
      case 'turn':
        this.onTurn(message.turn)
    }
  })

  sub.subscribe(this.channel, function() {
    this.checkStart()
  })
}

Game.prototype.checkStart = function () {
    // This checks if this instance  is for
    // the last player and, if so, starts the
    // main loop:
    if(this.playerNumber == this.totalPlayers - 1) {
      pub.publish(this.channel, JSON.stringify({type: 'turn', turn: 0})
    }
}

Game.prototype.onTurn = function(turn) {
  this.turn = turn
  if(this.turn == this.playerNumber) {
    this.timer = setTimeout(this.endTurn.bind(this), this.turnTime)
  }
}

Game.prototype.endTurn = function() {
  this.turn = (this.turn + 1) % this.totalPlayers
  pub.publish(this.channel, JSON.stringify({type: 'turn', turn: this.turn})
}

I had some problems with this approach and the main problem was the initial status, which wasn't quite right if the players connected almost at the same time. It's also a good idea to send information and make sure all instances are in sync.
I hope that I made this clear if someone is running into the same problem.
Answer: A reliable independent timer could be done with Redis and its TTL option (plus its Pub/Sub mechanic).
//enable keyspace events:
redisClient.send_command('config', ['set', 'notify-keyspace-events', 'Ex']);

// add a key:
const key = '<some meaningful key string>';
redisClient.set(key, '<some note for the key, not usable though>');

// set the key to expire:
redisClient.expire(key, 100); // duration in seconds

// somewhere else in the code, subscribe to the 'expired' event:
const expiredSubKey = `__keyevent@${config.redis.db}__:expired`; // you need redis DB number here
redisClient.subscribe(expiredSubKey, () => {
    redisClient.on('message', async (channel, key) => {
        // channel is actually expiredSubKey, ignore it
        // 'key' is the key you've set up previously
    });
});

(more info: How to receive Redis expire events with node?)
Apart from being service-indepedent this technique has one more upside:

there is no polling involved, you don't need to check for the expired key regularly

it also has some downsides:

its a bit 'hacky', meaning it wasn't designed exactly for the purpose
I couldn't find a way to get the value on expiration event, so only a key can be used which is limiting
if you have multiple instances of a service (i. e. scaling) you'll have that many subscribers, thus the event will fire for every one of them. Sometimes this is not a problem, sometimes it is. This can actually be resolved through advanced Redis pub/sub.

Also you could use some third-party service for this. I was able to find a couple of them with free plans and reasonable API (though I'm using my own, described above ).


Error on create new generic docker machine

Question: I trying to create new docker-machine with driver "generic" on VPS and I get this error:
MacBook-Pro-Pavel:demo pavel$ docker-machine create --driver generic --generic-ssh-key ~/.ssh/id_rsa --generic-ip-address=22.214.171.124 regru
Running pre-create checks...
Creating machine...
(regru) Importing SSH key...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with debian...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Error creating machine: Error running provisioning: ssh command error:
command : sudo systemctl -f start docker
err     : exit status 1
output  : Job for docker.service failed. See 'systemctl status docker.service' and 'journalctl -xn' for details.

Machine with driver "virtualbox" create normally:
MacBook-Pro-Pavel:~ pavel$ docker-machine ls
NAME           ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER        ERRORS
regru          -        generic      Running   tcp://126.96.36.199:2376             Unknown       Unable to query docker version: Cannot connect to the docker engine endpoint
swarm-node-0   -        virtualbox   Running   tcp://192.168.99.100:2376           v17.06.0-ce
swarm-node-1   -        virtualbox   Running   tcp://192.168.99.101:2376           v17.06.0-ce

systemctl status docker.service и journalctl -xn here.
What am I doing wrong?
UPDATE
$ docker version
Client:
 Version:      17.06.0-ce
 API version:  1.30
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:31:53 2017
 OS/Arch:      darwin/amd64

Server:
 Version:      17.06.0-ce
 API version:  1.30 (minimum version 1.12)
 Go version:   go1.8.3
 Git commit:   02c1d87
 Built:        Fri Jun 23 21:51:55 2017
 OS/Arch:      linux/amd64
 Experimental: true

Answer: Chances are, you are doing everything right.
It seems there is an issue with docker.
I don't have much understanding, however here is a link for details:
https://forums.docker.com/t/docker-machine-create-fails-on-digitalocean/34750
Work around is to manually provide older docker engine:
docker-machine create
--driver amazonec2
--engine-install-url=https://web.archive.org/web/20170623081500/https://get.docker.com

Add --engine-install-url to your setup and see if that works.
Comment: Thanks, saved my sleep, 5 years later! Seems to be an update to the get.docker.com that broke docker-machine installs, at least with the aws driver


How to get key and value from a dictionary after merging it from two list in Python?

Question: I have two list:
<code>list_a = [<User: x>, <User: y>]
list_b = [False, True]
</code>
I want to create a dictionary by merging it. I did by the following code:
<code> details = dict(zip(list_a,list_b))
</code>
But i am not able solve the issue how to get the value in a template.
In my template code:
<code>{% for x in details %}
   {{  }}
   {{  }}
{ % endfor %}
</code>
I have these two vacant tag in template. I want to put it as follow:
for the first iteration,
<code>{{ x }}
{{ False}}
</code>
for second iteration,
<code> {{ y }}
 {{ True}}
</code>
..and so on
Comment: can you please post better example for list_a .... post sample data please instead of pseudocode
Answer: <code>{% for key, value in details.iteritems %}
    {{ key }}
    {{ value }}
{ % endfor %}
</code>


CRC32 as .NET HashAlgorithm and endianness

Question: CRC32 is calculated as uint32, while HashAlgorithm in .NET by convention returns byte[]. I can, of course, easily convert it with bytes = BitConverter.GetBytes(hash) but this is affected by "endianness" of a system (almost no chance for big-endian, of course).
Anyway, I've been thinking is there any convention to follow? I have a feeling that it should be big-endian to make hash.ToString("X") and bytes.ToHex() (assuming .ToHex() exists) look the same.
I've checked https://github.com/vurdalakov/crc32/wiki/CRC32 and it does not do that. Any thoughts?
Comment: "Any thoughts?" is really too broad. Try to ask a specific question. Stackoverflow is not really geared toward ruminations.
Answer: I can only cite examples, where the zip and gzip file formats store the CRC in little-endian order. I'm sure someone can find examples where a 32-bit CRC is stored in big-endian order, sometimes called "network order" as big-endian is intended to be a convention for network communications.
If you are defining your own protocol, then you can pick whichever you like. For the code to be portable, you would need to use shift operators to pick apart the bytes so that the endianess of the machine does not affect the result.
Comment: Thanks. Still the question is, does it specifically do little-endian or it just stores native representation which happens to be little-endian?
Comment: What is "it" in "does it specifically" and "it just stores"?


Show that $\int_1^\infty \frac{\log(x-1)}{x^3}\, dx = -\frac 1 2$ by considering $f(z)=\frac{[\log(1-z)]^2}{z^3}$

Question:
Show that $\int_1^\infty \frac{\log(x-1)}{x^3}\, dx = -\frac 1 2$ by considering $f(z)=\frac{[\log(1-z)]^2}{z^3}$.

Attempt at a solution:
Perform the line integral of a small circle centered at $x=1$, lines along the $x$ axis from 1 to $\infty$ and $\infty$ to 1, as well as a circle of infinite radius joining the two lines along the $x$ axis together. The integrals along both circles are $0$.
There is a simple pole at $z=1$ with residue $1$, so by CRT the above integral is $2\pi$.
So I have $$2\pi = \int_1^\infty \frac 1 {x^3} [\log(1-x)]^2 \, dx + \int_\infty^1 \frac 1 {(xe^{2\pi i})^3} [\log(1-xe^{2\pi i})]^2 \, dx \, e^{2\pi i}$$
And I'm stuck here I can't see how to get to $\int_1^\infty  \frac{\log(x-1)}{x^3} \, dx = -\frac 1 2$.
I can get to $\log(1-x)$ by bringing a factor of $i \pi$ outside of the $\log$ but can't see how to get rid of the square of the exponential.
Comment: I don't know why you have factors of $e^{2\pi i}$ everyhwere, doesn't make sense to me as $e^{2\pi i} = 1$. Is there any reason why you shouldn't consider $(1/z^3) \log(1-z)$ to begin with?
Comment: Also, it seems that you forgot to account for the fact that the "phase" of the integral along $\infty$ to $1$ is an amount of $\pi$ larger than the phase of the integral along $1$ to $\infty$.
Comment: Additionally, I presume it should be $\log(x-1)$ and not $\log(1-x)$
Comment: $$\int_{1}^{+\infty}\frac{\log(z-1)}{z^3}\,dz \stackrel{z\mapsto\frac{1}{z}}{=} \int_{0}^{1}z\log\left(\frac{1}{z}-1\right)\,dz=\int_{0}^{1}z\log(1-z)-z\log z\,dz$$
equals
$$ \int_{0}^{1}(1-z)\log z-z\log z\,dz = \int_{0}^{1}(1-2z)\log z\,dz \stackrel{\text{IBP}}{=}-\frac{1}{2}$$
since $\int_{0}^{1}z^\alpha\log(z)\,dz=-\frac{1}{(\alpha+1)^2}$ for any $\alpha>-1$.
Comment: @QM_42 I think you should be going along half-circles, not full circles, because you can't define a logarithm that is holomorphic everywhere, you need to "cut out" a line.
Comment: @user159517 so should all the $e^{2\pi i}$ be $e^{\pi i}$ instead?
Comment: @user159517 It's not actually a full circle... and indeed, the full circle should be the right idea.
Answer: I recommend shifting your integral over a bit:
$$I=\int_0^{+\infty}\frac{\ln(z)}{(z+1)^3}~\mathrm dz$$
Now consider $f(z)=\frac{\ln^2(z)}{(z+1)^3}$.  Taking the same approach as you have,
$$\begin{align}\oint f(z)~\mathrm dz&=\int_0^{+\infty}f(z)~\mathrm dz+\int_{+\infty}^0f(ze^{2\pi i})~\mathrm dz\\&=\int_0^{+\infty}\frac{\ln^2(z)}{(z+1)^3}-\frac{\left[\ln(z)+2\pi i\right]^2}{(z+1)^3}~\mathrm dz\\&=\int_0^{+\infty}\frac{\require{cancel}\cancel{\ln^2(z)-\ln^2(z)}-4\pi i\ln(z)+4\pi^2}{(z+1)^3}~\mathrm dz\end{align}$$
Thus,
$$\int_0^{+\infty}\frac{\ln(z)}{(z+1)^3}~\mathrm dz=-\frac1{4\pi}\Im\left[\oint f(z)~\mathrm dz\right]$$

Also, check your residue calculations.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

I'll comsider the following branch-cut, along $\ds{\left(-\infty,0\right]}$, for the $\ds{\ln}$-function:

$$
\ln\pars{w} = \ln\pars{\verts{w}} + \,\mrm{arg}\pars{w}\ic\,,\qquad -\pi < \mrm{arg}\pars{w} < \pi\,,\quad w \not= 0
$$
With this definition, it turns out that $\ds{\ln\pars{1 - z}}$ has a brunch-cut along $\ds{\left[0,\infty\right)}$ such that I'll perform an integration along a
key-hole' contour $\ds{\,\mc{C}}$ which 'takes care' of the $\ds{\ln\pars{1 - z}}$-branch cut.

\begin{equation}
\mbox{Note that }\ \underline{when\,\,\, x > 1}:\
\left\{\substack{%
\ds{\left.\vphantom{\large A}\mrm{arg}\pars{1 - z}
\right\vert_{\large\ \Im\pars{z}\ =\ 0^{+}}\ =\ -\pi}
\\[3mm]
\ds{\left.\vphantom{\large A}\mrm{arg}\pars{1 - z}
\right\vert_{\large\ \Im\pars{z}\ =\ 0^{-}}\ =\ \phantom{-A}\pi}}\right.
\label{1}\tag{1}
\end{equation}

The integrand has a single pole, inside the contour, at $\ds{z = 0}$. Namely,
\begin{align}
\oint_{C}{\ln^{2}\pars{1 - z} \over z^{3}}\,\dd z & =
2\pi\ic\,\lim_{z \to 0}\bracks{z\,{\ln^{2}\pars{1 - z} \over z^{3}}} = 2\pi\ic
\label{2}\tag{2}
\end{align}

\begin{align}
\mbox{Moreover, ( see \eqref{1} )}&
\\[2mm]
\oint_{C}{\ln^{2}\pars{1 - z} \over z^{3}}\,\dd z & =
\int_{1}^{\infty}{\bracks{\ln\pars{x - 1} - \pi\ic}^{\,2} \over x^{3}}\,\dd x +
\int_{\infty}^{1}{\bracks{\ln\pars{x - 1} + \pi\ic}^{\,2} \over x^{3}}\,\dd x
\\[5mm] & =
-4\pi\ic\int_{1}^{\infty}{\ln\pars{x - 1} \over x^{3}}\,\dd x\label{3}\tag{3}
\end{align}
By simplicity, I omitted the integration 'around' $\ds{z = 1}$ indented path which trivially vanishes out.

\eqref{2} and \eqref{3}
  $\ds{\implies \int_{1}^{\infty}{\ln\pars{x - 1} \over x^{3}}\,\dd x =
{2\pi\ic \over -4\pi\ic} = \bbx{-\,{1 \over 2}}}$.
Answer: Here is a real approach
Preliminary Results
$$
\int_1^\infty\frac{\log(x)}{(1+x)^3}\,\mathrm{d}x
=-\int_0^1\frac{x\log(x)}{(1+x)^3}\,\mathrm{d}x\tag{a}
$$
$$
\frac{1-x}{(1+x)^3}=\sum_{k=0}^\infty(-1)^k(k+1)^2x^k\tag{b}
$$
$$
\begin{align}
\int_0^ax^k\log(x)\,\mathrm{d}x
&=\frac1{k+1}\int_0^a\log(x)\,\mathrm{d}x^{k+1}\\
&=\frac1{k+1}\left[a^{k+1}\log(a)-\int_0^ax^k\,\mathrm{d}x\right]\\
&=\frac1{k+1}\left[a^{k+1}\log(a)-\frac1{k+1}a^{k+1}\right]\tag{c}
\end{align}
$$

Main Result
$$
\begin{align}
\int_1^\infty\frac{\log(x-1)}{x^3}\,\mathrm{d}x
&=\int_0^\infty\frac{\log(x)}{(1+x)^3}\,\mathrm{d}x\tag{1}\\
&=\int_0^1\frac{(1-x)\log(x)}{(1+x)^3}\,\mathrm{d}x\tag{2}\\
&=\lim_{a\to1^-}\int_0^a\frac{(1-x)\log(x)}{(1+x)^3}\,\mathrm{d}x\tag{3}\\
&=\lim_{a\to1^-}\sum_{k=0}^\infty(-1)^k(k+1)^2\int_0^ax^k\log(x)\,\mathrm{d}x\tag{4}\\
&=\lim_{a\to1^-}\sum_{k=0}^\infty(-1)^ka^{k+1}\left[(k+1)\log(a)-1\right]\tag{5}\\
&=\lim_{a\to1^-}\left[\frac{a\log(a)}{(1+a)^2}-\frac{a}{1+a}\right]\tag{6}\\[3pt]
&=-\frac12\tag{7}
\end{align}
$$
Explanation:
$(1)$: substitute $x\mapsto x+1$
$(2)$: apply $\text{(a)}$
$(3)$: introduce a limit for later
$(4)$: apply $\text{(b)}$
$(5)$: apply $\text{(c)}$
$(6)$: evaluate series
$(7)$: evaluate limits


Facebook comments box for site loading very slowly

Question: Hi I'm using a Facebook comments module for my Drupal 6 website on aws.
I've noticed that especially during mobile visits the loading of the Facebook comments box is last and is slowing down the page load time.
How do I find out if this comment Facebook code is loading asynchronously and how to speed it up? Any way to update the Facebook comments module?
Thanks!
Answer: Connect your phone's browser to the Developer Tools on your computer. Check the network tab and check what's slowing down the requests.
It might be that you have too many requests, and the comment requests are being given a lower priority in order to render the actual page first.
Here are the links for Android and iOS
https://developers.google.com/web/tools/chrome-devtools/remote-debugging/
https://developer.apple.com/library/content/documentation/AppleApplications/Conceptual/Safari_Developer_Guide/GettingStarted/GettingStarted.html
For Apple's link, go down to the section named 'Safari on iOS'

Safari's network tab

Chrome's network tab


How do I find this trace?

Question: Let matrices be $X=\begin{bmatrix}2&2\\5&1\end{bmatrix}$ , $Y=\begin{bmatrix}4&5\\3&4\end{bmatrix}$ and $Z=\begin{bmatrix}4&-5\\-3&4\end{bmatrix}$, then what is the value of $$\sum_{k=0}^{\infty}\frac{tr(X(YZ)^k)}{2^k}$$
What do I already know: $tr(A)$ symbolises the Trace of matrix $A$ that is, the sum of it's primary diagonal element. But, how am I suposed to find the trace of such a summation? Please help.
(I'm new to eigenvalue concepts so kindly explain them, if required in solution of this question)
Comment: $YZ=I$  (the unit matrix), so it shouldn't be too hard…
Comment: So basically I did a blunder in multiplication. Thank you for pointing that out @Bernard
Answer: Since $YZ$ is the identity matrix, so is $(YZ)^k$. So the top size of the fraction is basically $tr(X)$.
$$\sum_{k=0}^\infty \frac{\text{tr}(X)}{2^k} = 3\sum_{k=0}^\infty \frac{1}{2^k} = 6$$
The last step is a well known result, but can be done explicitly by using the sum of a geometric series.

How do I find this trace?


Incorporar Video mudo do youtube

Question: Estou tentando fazer o video ficar iniciar mudo mas não esta dando certo, sera que esta correto o código?

Comment: Tem que ser obrigatoriamente em iframe?
Comment: Tem que respeitar os parâmetros do URL? width="100%" height="100%"  rel=0 etc...?
Answer: Tem 2 problemas no teu código:

Primeiro você esta adicionando o  manualmente e quem tem que adicionar isso é a API
Tem um erro de script, esta sobrando um } no final:
    var tag = document.createElement('script');
    tag.src = "https://www.youtube.com/iframe_api";
    var firstScriptTag = document.getElementsByTagName('script')[0];
    firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

    function onYouTubeIframeAPIReady() {
        var player = new YT.Player('player', {
            events: {
                'onReady': onPlayerReady,
                'onPlaybackQualityChange': onPlayerPlaybackQualityChange,
                'onStateChange': onPlayerStateChange,
                'onError': onPlayerError
            }
        });
    }

    function onPlayerReady(event) {
        event.target.mute();
    }
} <--- AQUI esta sobrando

Primeiro troque o iframe por:

E corrija o javascript (eu organizei a identação do código para facilitar a leitura), fora que deve adicionar o ID e o tamanho no Javascript também:
height: '360',
width: '640',
videoId: 'M7lc1UVf-VE',

Resultado:

você também pode mudar o código para isto:

Exemplo básico
Veja o exemplo funcionando no jsfiddle, segue o código:

Nota: o playVideo(); não funciona em todos ambientes, conforme dito em https://developers.google.com/youtube/iframe_api_reference?hl=pt-br:
Devido a esta restrição, funções e parâmetros, como autoplay, playVideo() e loadVideoById(), não funcionarão em todos os ambientes de dispositivos móveis.
Answer: Não sei se o autor queria exatamente com os parâmetros do URL do iframe, ou seja:
`width="100%" height="100%"` - toda a area da tela

`rel=0` - remover vídeos relacionados do final dos vídeos incorporados

`controls=0` não exibir os controles do player

`playlist: 'cMekP6Jm_lY'`  Outro vídeo na sequencia

E lógico, que esteja sem som!
CSS
 body,
    html {
        width: 100%;
        height: 100%;
        overflow: hidden;
    }

    * {
        padding: 0;
        margin: 0;
    }

    iframe {
        width: 100%;
        height: 100%;
        overflow: hidden;
        border: none;
    }

HTML + SCRIPTS

FONTE
Comment: e o que isto complementa a resposta ou difere?
Comment: Se quiser falar sobre assuntos extras experimente isto https://pt.stackoverflow.com/help/self-answer
Answer: Adicione ao seu script: player.mute()
Comment: tentei com player.mute() mas não deu também

Incorporar Video mudo do youtube


Transforming continuous variable to ordinal for estimation with ordered logit

Question: I currently have a continuous variable. However, I would like to transform it into 5 intervals using cutpoints of my choosing to carry out an ordered logit estimation.
That is:

Will this affect the estimation?
Comment: Why would you want to do that? You will always get better estimates if you use $y_i^*$ directly if you have the luxery that that variable is available.
Comment: Thank you for your reply @MaartenBuis. I was hoping to assess the effect of education on what grade is achieved, as opposed to the score underlying that grade, as this would be more beneficial to interpretation.Is there another method you know of?
Answer: Ordinal regression, if programmed efficiently, can handle any number of discrete values of $Y$.  For example, in the R rms package, the orm function can fit a variety of ordinal models (proportional odds, proportional hazards, probit, ...) when there are thousands of possible $Y$ values.  Categorization is arbitrary and information-losing.  The only issue is that the information matrix is sparse and you need to capitalize on that so as to never have to invert huge matrices to get the covariance matrix.  orm does that.


Unexpected answer to an expected value problem

Question: Suppose you start on the zero notch of the line of integers. You flip a coin. If you get heads, you move to the integer on the right (+1), and if you get tails, you move to the integer on the left (-1). It turns out that the expected number of flips to reach +1, from 0, is infinity. Why?
Comment: It may help to try to describe $E(x)$ first.
Answer: Suppose $X$ be Number of flips to reach $+1$ from $0$ as starting point,
$Y$ be Number of flips to reach $0$ from $-1$ as starting point,
$Z$ be Number of flips to reach $+1$ from $0$ as starting point,
and $W$ be Number of flips to reach $+1$ from $-1$ as starting point.
Now if we start from $0$, we have two:
$$E(X)= \frac{1}{2}.1 + \frac{1}{2}.E(W)$$
Now obviously for reaching $+1$ from $-1$ we must pass the $0$, So we have:
$$E(W)= E(Y+Z)=E(Y)+E(Z)$$
By symmetry we know:
$$E(X)= E(Y)= E(Z)$$
So by:
$$E(W)= 2E(X)$$
And therefor:
$$E(X)= \frac{1}{2}.1 + \frac{1}{2}.2E(x) \Longrightarrow E(X)= \frac{1}{2} +E(X)$$
That has no finite solution!
Comment: Thanks! This makes sense.
Comment: Indeed, it only has the solution $+\infty$ if you allow yourself to work in the extended real numbers.
Answer: Let's try to calculate this expected value. First of all, observe that, by parity, one can only reach $+1$ in an odd amount of flips, as the parity of the integer you're at is always equal to the number of flips you've done. Now, notice that, in order to reach $+1$ in $2k+1$ flips, we must stay at $0$ or below for $2k-1$ flips, then cross $0$, and cross to $+1$. If we write our sequence of heads and tails down, encoding each tails with a left parenthesis '(', and each heads with a right parenthesis ')', our first $2k$ flips must encode a balanced sequence of brackets, and furthermore, there must be a bijection between these bracket sequences of length $2k$ and our sequences of $2k+1$ flips that get us to $+1$.
The number of balanced bracket sequences of length $2k$ can be calculated as the $k$-th Catalan number $C_k$, and the number of ways to flip our coin $2k+1$ times equals $2^{2k+1}$, which means that our expected value equals $$\sum_{k=0}^\infty \frac{C_k(2k+1)}{2^{2k+1}}.$$ $$=\sum_{k=0}^\infty \frac{(2k+1)!}{k!(k+1)!2^{2k+1}}.$$ For $k=3$, it turns out that the inequality $$\frac{(2k+1)!}{k!(k+1)!2^{2k+1}}<\sqrt{k+1}-\sqrt{k}$$ holds. Furthermore, for all positive $k$, $$\frac{\sqrt{k+2}-\sqrt{k+1}}{\sqrt{k+1}-\sqrt{k}}<\frac{2k+3}{2k+4}.$$ By combining both inequalities, and by a simple induction, we can conclude that $$\sum_{k=0}^\infty \frac{(2k+1)!}{k!(k+1)!2^{2k+1}}>\sum_{k=3}^\infty \frac{(2k+1)!}{k!(k+1)!2^{2k+1}}>\sum_{k=3}^\infty \sqrt{k+1}-\sqrt{k},$$ but this last sum is telescopic and clearly diverges. This implies that our expected value is infinite.
EDIT: There's a better way to do the last part. Notice first that $$\sum_{k=0}^\infty \frac{(2k+1)!}{k!(k+1)!2^{2k+1}}>\sum_{k=0}^\infty \frac{(2k)!}{k!^22^{2k+1}}.$$ The $n$-th partial sum of the latter sum can be proven by a simple induction to equal $$\frac{\Gamma(n+\frac{3}{2})}{\sqrt{\pi}\Gamma(n+1)}.$$ It's not hard to convince yourself that this diverges.


Prop. score matching with subsequent time-varying exposure

Question: I'm running basic propensity score matched cohorts and running a typical "intention-to-treat" analyses in patients with dementia, estimating mainly effects of treatment on e.g. mortality. Patients are matched on incident drug usage at time of dementia diagnosis (entry to study). However, I have also data on yearly usage AFTER dementia is diagnosed, however I have never ran across a study that would take the PS matched cohort (matched at start of the study) and then take into account that people can transfer from exposed to unexposed and vice-versa after the start time. Is this reasoning flawed and can even typical methods like cox or flexible parametric models be used? Or does one have to use marginal structural models with weighting? I'd like to keep the comparability of the exposed-unexposed cohorts achieved with PS matching with the ability to take into account time-varying nature of the exposure assignment.
Answer: Weighting for marginal structural models would be the ideal technique here. You could simply perform the weighting in the matched sample to retain the benefits of matching at the first time point and then use the weights to address time-varying confounding at later time points. You could also just forget the matching and use weighting entirely. Weighting also ensures the comparability of the exposed/unexposed groups at the first time point (and thereafter), so unless you have a particularly good reason to be so attached to matching over weighting, eschewing the matching entirely is a valid option. Given that you have a survival outcome, you should look into marginal structural survival models.
There are other techniques to address time-varying confounding. You could use longitudinal targeted maximum likelihood estimation (LTMLE), which is multiply-robust and uses flexible models to model the transition into exposure and the intermediate and final outcomes. The ltmle R package makes this possible. The literature on sequential/dynamic treatments would be a place to start.
Comment: Yes, because you still need to account for the fact that baseline confounders affect future treatment selections. For example, even though the first treatment is as-if randomized because of the matching, by the last year, only people with severe risk moved to one of the treatment arms. An MSM accounts for that, but other methods do too, like simply regressing the outcome on the treatments and covariates. That said, if unmeasured intermediate outcomes cause selection into treatment, you have unmeasured confounding that could bias your results.
Comment: Thank you Noah! One follow-up question - is MSM still the way to go if the only variable that is time-varying is the exposure? I have no information on the confounders of the treatment after the baseline time, i have only information on whether patients started or stopped using medication in yearly intervals. Thanks again.
Comment: Just to clarify based on - "like simply regressing the outcome on the treatments and covariates" - even a Cox model in the whole cohort with time-varying exposure and adjustment for baseline covariates would be better than PS matching?
Comment: It would be better than PS matching alone, but you could also do it in the PS matched dataset to add some robustness. If people die before they can take future treatments, though, that needs to be accounted for. If not, then a regular Cox model with covariates in the matched or unmatched sets should be basically fine (other than functional form issues and unmeasured confounding).
Comment: Ok, I'll go for the MSM with stabilized weights, and compare how the models fared in just basic adjustment vs the weighted one. Overall - big thanks.


Uncaught TypeError jquery function is not read anymore

Question: I've on a Drupal 6 site which run since 2 years, a new problem at first with CloudZoom but i start to think that it's a little more than that.
I've errors in the firebug console which says :
Uncaught TypeError: Object function ... has no method 'cookie'
or Uncaught TypeError: Object function ... has no method 'cloudzoom'
So Cloudzoom don't works anymore on some language... what is strange is that it still work in english.
I've take a look at the code and it's ok, it worked in the past ans still work in english. I also make sure that JS file are call in the right order jquery>librairies>myOwnJs.
what i need is to understand the error message "Uncaught TypeError: Object function" : what can generate that kind of error, where to search. I spend a lot of time on that and don't really know where to look now.
Comment: I answer my own question because i've found the problem, but still not the solution :( .

I've a web service that add a version of jquery if mine is different and on my drupal site i've a module which add the last version of jquery : so i've two jquery on my page (and it's not good). English version works well because it's not using that web service.

So now i've to find how handle that situation.
Answer: You got it - basically it means the function isn't defined or is conflicting. You have to load the jQuery file that you're going to use and not multiple or you'll get that type of strange behavior.
The workaround I've used, which does work -- assuming you're not using that particular function -- is to define the function yourself as an empty function and it'll reference that and just keep on going. This came up in the Adobe Edge beta as fnCycle() was giving the same error. After putting the empty function in my own .tpl.php is solved and didn't kill the js execution.
Note though that while this may work for that one situation, you will have others if you leave conflicting versions of jQuery in there.
Comment: Finaly it's solved, i call the team in charge of the web service and they fix it. I'll keep your advice in mind because i can't contact each team which provide a webservice.
Thank you.


Como fazer um daemon para o comando "mongod"

Question: Qual é o procedimento para deixar o Mongo rodando no servidor sem a necessidade de usar o comando mongod?
Existe algum comando especifico do Mongo para isto?
Comment: Provavelmente você pode instalar ele como serviço e rodá-lo. Uma curiosidade: você está usando linux?
Comment: Sim, linux no servidor.
Comment: Você precisa criar um usuário com nome sugestivo e programar o linux para que este programa rode naquele usuário sempre que o pc reiniciar.
Comment: Não precisa de nada disso, olha minha resposta. O próprio manual do Mongo tem a solução
Comment: Sem problemas Wallace Maxters. Obrigado pela ajuda.
Answer: Se tiver usando o Linux, você pode fazer o seguinte:
nohub mongod &

O Nohup fará com que o processo continue rodando em background, mesmo que você deslogue do servidor (se você estiver usando o SSH).
Existe também uma possibilidade de você configurar um serviço para rodar esse comando:
Veja aqui: https://stackoverflow.com/questions/19233529/run-bash-script-as-daemon
Atualização
De acordo com o Manual do MongoDB, a forma correta de fazer é usando o argumento --fork ao rodar o comando.

To run a mongod process as a daemon (i.e. fork), and write its output to a log file, use the --fork and --logpath options. You must create the log directory; however, mongod will create the log file if it does not exist.

Tradução meia-boca:

Para executar um processo mongod como um daemon, e escreva sua saída para um arquivo de log, use as opções -=-fork e --logpath. Você deve criar o diretório de log. No entanto, mongod irá criar o arquivo de log se ele não existe.

Para inicial o Daemon do mongo faça:
mongod --fork --logpath /var/log/mongodb.log

Para finalizar faça:
mongod --shutdown

Comment: Obrigado pessoal. Funcionou com mongod --fork --logpath /var/log/mongodb.log.
Comment: O Log é importante. Como você não vai estar acompanhando a saída do comando em realtime, você pode acompanhar erros ou qualquer outro evento ocorrido no Log.
Answer: Depende você tá rodando no linux ou no windows?
Se for no Windows só fazer um bat ou fazer ele virar um serviço e colocar pra iniciar junto com o Windows se for no linux ai depende de qual distro você está usando. Vou deixar alguns links no comentário apenas para referência.
Comment: Essas referências ficam boas na resposta.
Comment: O mais correto, ao invés de fazer um BAT é usar o agendador de tarefas e criar uma nova tarefa que execute esta aplicação sempre que o Windows inicializar, não sendo necessário que o usuário faça login.
Comment: http://stackoverflow.com/questions/7016880/run-mongodb-server-as-a-service-detached-from-terminal
Comment: http://stackoverflow.com/questions/2438055/how-to-run-mongodb-as-windows-service
Comment: http://serverfault.com/questions/563970/how-can-i-install-mongodb-as-a-service-in-centos
Comment: http://askubuntu.com/questions/61503/how-to-start-mongodb-server-on-system-start


context path and subpaths

Question: I have a problem with Context path condition. I would like on the conditions region to assign something like path/* where * indicates all its subpaths. For instance, if we have path/subpath1/subpath2 the context condition should match on path, subpath1 and subpath2.
Is it possible to do that on Context?
Thanks in advance!
Answer: I'm pretty sure that just checking it against path* should work.
So rather than path/* or path/*/* just run it against path*.

context path and subpaths


RSACryptoServiceProvider - Decrypt

Question: Usando a criptografia RSA, eu passo os dados encriptados do client para o server decriptar. Ao tentar decriptar, ele me devolve uma exceção CryptographicException com a mensagem:

Sinalizadores inválidos especificados.

Não tenho ideia de que Flag possa estar faltando.
Meu código se encontra da seguinte maneira:
byte[] decryptedMessage;
RSACryptoServiceProvider asr = new RSACryptoServiceProvider(128);
decryptedMessage = asr.Decrypt(buffer, false);

em System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
         em System.Security.Cryptography.Utils._GenerateKey(SafeProvHandle hProv, Int32 algid, CspProviderFlags flags, Int32 keySize, SafeKeyHandle& hKey)
         em System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
         em System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
         em System.Security.Cryptography.RSACryptoServiceProvider.Decrypt(Byte[] rgb, Boolean fOAEP)
Answer: RSACryptoServiceProvider não dá suporte a chaves de 128 bits:

Os tamanhos de chave de suporte de RSACryptoServiceProvider de 384 bits a 16384 bits em incrementos de 8 bits se você tiver o provedor de criptografia aprimorado Microsoft instalado. Suporta tamanhos de chave de 384 bits a 512 bits em incrementos de 8 bits se você tiver o Microsoft Base Cryptographic Provider instalado.

Fonte: MSDN - Propriedade RSACryptoServiceProvider.KeySize
Resposta original no SOen.
Comment: Essa parte tudo bem, já tinha lido sobre em outros lugares, mas qual a solução que tenho então para decryptar o dado ??
Comment: @EnzoTiezzi Seria possível modificar o client para usar um tamanho de chave maior? 128 bits para o RSA é terrivelmente inseguro... Caso contrário, imagino que será necessário buscar uma implementação alternativa, ou talvez delegar a tarefa a um sistema externo (tipo o openssl).
Comment: eu estou utilizando openssl, e mandando dados encryptados utilizando RSA para o servidor a partir de uma SSLStream

RSACryptoServiceProvider - Decrypt


Criar Observer na classe Mage_Core_Model_App para a função run

Question: Ao olhar para a classe app\code\core\Mage\Core\Model\App.php, temos a seguinte função:
public function run($params)
    {
        $options = isset($params['options']) ? $params['options'] : array();
        $this->baseInit($options);
        Mage::register('application_params', $params);

        if ($this->_cache->processRequest()) {
            $this->getResponse()->sendResponse();
        } else {
            $this->_initModules();
            $this->loadAreaPart(Mage_Core_Model_App_Area::AREA_GLOBAL, Mage_Core_Model_App_Area::PART_EVENTS);

            if ($this->_config->isLocalConfigLoaded()) {
                $scopeCode = isset($params['scope_code']) ? $params['scope_code'] : '';
                $scopeType = isset($params['scope_type']) ? $params['scope_type'] : 'store';
                $this->_initCurrentStore($scopeCode, $scopeType);
                $this->_initRequest();
                Mage_Core_Model_Resource_Setup::applyAllDataUpdates();
            }

            $this->getFrontController()->dispatch();
        }
        return $this;
    }

Para se adicionar um event/observer usamos o seguinte codigo:
<events>
  <EVENT_TO_HOOK>
    <observers>
      <module>
        <type>singleton</type>
        <class>company_module_model_observer</class>
        <method>methodToCall</method>
      </module>
    </observers>
  </EVENT_TO_HOOK>
</events>

Qual o evento que devemos adicionar para observarmos a função run da classe Mage_Core_Model_App?
Answer: Não é possível observar a função run da classe Mage_Core_Model_App através de um evento.
O único evento disparado nessa classe era o application_clean_cache. Confira a lista completa em http://www.nicksays.co.uk/magento-events-cheat-sheet-1-8/
Mas a listagem acima vale para a versão 1.8 - esse evento mencionado acima já não existe mais.
Um evento é disparado através do método dispatchEvent. Por exemplo:
Mage::dispatchEvent('application_clean_cache', array('tags' => $tags));

(fonte: http://freegento.com/doc/d8/d98/_app_8php-source.html#l01084)
No código da função run em app\code\core\Mage\Core\Model\App.php, postado na pergunta, vemos que não há nenhuma chamada a Mage::dispatchEvent. Isso significa que nenhum evento é disparado e, portanto, não há nenhum evento para ser observado e capturado aí.
A alternativa é estender a classe e fazer um override da função.
Ou então (embora não recomendável) alterar o código da função no Magento, acrescentando o disparo de um evento com dispatchEvent...


Django - User Uploaded CSV and JQueryCSVtoTable

Question: I have a small django app that requires users to upload a csv file. I would like to access the file itself and use it with jquerycsvtotable.
I have successfully uploaded the file. How do I bring it into the template in a way the library can access it.
Answer: Assuming you have something like a CSVFile model object, you'll want to pass that object to your template and access the file field's url property. Something like this:
Assuming something like this in your models.py:
class CSVFile(models.Model):
    ...
    file = models.FileField(...)

You'll need to lookup the object and pass it to your template in views.py:
def some_view(request, ...):
    ...
    obj = CSVFile.objects.get(...)
    return render('path/to/template.html', {'obj': obj})

And then get the url in template.html like so:
...

...

See the documentation on Django FileField for more information.


System_Daemon::setSigHandler

Question: I am using system daemon inside a class,
I am wondering if the following code for setting a handler is ok or not
System_Daemon::setSigHandler(SIGTERM, array($this, myShutdownHandler) );

in the documentation they don't mention how to pass an object method as a "handler"
here: array($this, shutdownHandler)
the qiven example in the docs:
System_Daemon::setSigHandler(SIGTERM, "ownShutdownHandler" );

function ownShutdownHandler($sig)
{
 //etc
}

Answer: Yes that looks OK.
Example code can be found on https://github.com/kvz/system_daemon/blob/master/examples/bug_test_b.php
Answer: The "handler" is known as a "callback" in the PHP world. Have a look at the documentation.

System_Daemon::setSigHandler


An expression of a conditional expectation using the law of iterated expectation

Question: Suppose that we have a discrete random variable $D$ with the support $\mathcal{S}_0=\left\{ d_1,\ldots,d_{20}\right\}$.
In addition, consider a subset of the support like $\mathcal{S}_1=\left\{d_1,\ldots,d_{10}\right\} \subset \mathcal{S}_0$.
Lastly, we have two continuous random variables $X$ and $Y$.
Here, I have two questions.
First, I want to express $\mathbb{E}\left[Y\middle|X,D=d_1\;or\;D=d_2\;or\;\ldots\;or\;D=d_{10}\right]$ as $\mathbb{E}\left[Y\middle|X,D\in \mathcal{S}_1\right]$.
Is this a valid expression? More compactly, is it possible to write
\begin{align*}
\mathbb{E}\left[Y\middle|X,D=d_1\;or\;D=d_2\;or\;\ldots\;or\;D=d_{10}\right]=\mathbb{E}\left[Y\middle|X,D\in \mathcal{S}_1\right]
\end{align*}.
Second, if the answer to the first question is yes, by the law of iterated expectation, the following derivation may be correct.
\begin{align*}
\mathbb{E}\left[Y\middle|X,D\in \mathcal{S}_1\right]&=\mathbb{E}\left[\mathbb{E}\left[Y\middle| X,D\in\mathcal{S}_1,D\right]\middle|X,D\in\mathcal{S}_1\right] \\[5pt]
&=\sum_{d\in\mathcal{S}_1}\mathbb{E}\left[Y\middle|X,D\in\mathcal{S}_1,D=d\right]\Pr\left[D=d\middle|X,D\in\mathcal{S}_1\right] \\[5pt]
&=\sum_{d\in\mathcal{S}_1}\mathbb{E}\left[Y\middle|X,D=d\right]\Pr\left[D=d\middle|X,D\in\mathcal{S}_1\right]
\end{align*}
Are any of the above statements incorrect?
In my shallow knowledge, the there is nothing wrong. But, I want to confirm my derivation.
Thank you.
Answer: It's correct, but faster:
$$\mathbb{E}\left[Y\middle|X,D\in \mathcal{S}_1\right]=\frac{1}{Pr(D\in S_1|X)}\int\limits_{D\in S_1}YdP_{\Omega/X}=\frac{\sum_{d\in S_1}\mathbb{E}[Y.I_{\{d\}}(D)|X]}{\sum_{d\in S_1}Pr[D=d|X]}$$
Comment: Your suggestion is so compact. Thank you for answering my question.


How to make responsive youtube video card/image with no black bars on top and bottom?

Question: I want to display the youtube video in card image with no black bars on top and bottom of it. Here is the code that I have for full card:

.media-video-container {
  position: relative;
  overflow: hidden;
}
.media-video-container img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

          {{item?.name}}

      <button *ngIf="item.type == 'video'" class="ytp-button ytp-large-play-button" aria-label="Play">
        <svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%">
          <path class="ytp-large-play-button-bg" d="..."
            fill="#212121" fill-opacity="0.8"></path>
          <path d="M 45,24 27,14 27,34" fill="#fff"></path>
        </svg>
      </button>

I would really appreciate any help :)
NOTE: I have already tried:

Responsive fullscreen youtube video with no black bars?
Responsive video iframes (keeping aspect ratio), with only css?
Comment: Possible duplicate of [Responsive video iframes (keeping aspect ratio), with only css?](https://stackoverflow.com/questions/25302836/responsive-video-iframes-keeping-aspect-ratio-with-only-css)
Comment: @ItayGal as I mentioned, I have already tried the question with link below my question and the one you linked. It didn't help so I am asking for suggestions
Comment: pretty sure I linked a different question... check it
Comment: @ItayGal I see. Thank you for your comment, I have already checked this too. It is with iframe. Anyway, I tried the solution they gave, didn't work out.
Answer: Try this, Thil will work, adjust the scale value as you wanted.
You can learn more about youtube image thumbnails here

.media-video-container {
  position: relative;
  overflow: hidden;
}

.media-video-container img {
  /*position: absolute;
  top: 0;
  left: 0;*/
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
  -webkit-transform: scaleY(1.2);
  -moz-transform: scaleY(1.2);
  -ms-transform: scaleY(1.2);
  transform: scaleY(1.2);
}

          {{item?.name}}

      <button *ngIf="item.type == 'video'" class="ytp-button ytp-large-play-button" aria-label="Play">
        <svg height="100%" version="1.1" viewBox="0 0 68 48" width="100%">
          <path class="ytp-large-play-button-bg" d="..."
            fill="#212121" fill-opacity="0.8"></path>
          <path d="M 45,24 27,14 27,34" fill="#fff"></path>
        </svg>
      </button>

Comment: thank you so much for taking your time and giving a solution. Unfortunately it didn't work. (I can't post a screenshot after your solution in comment)
Comment: Also the max width you give for ytImgContainer seems to be big. I have a card of 292.5x266
Comment: I had the same problem once. During that time I set `overflow:hidden` to the wrapper and scaled the thumbnail their I achieved the solution. Then after only I have learnt about the code that I have answered. If it didn't work, try to scale the thumbnail image
Comment: @Nodirabegimxonoyim I edited the answer in the manner that I mentioned. Please check it out
Comment: thank you so much. I have tried many options those unfortunately, didn't work. This solved the problem. Good luck!
Comment: Happy to help. Have a great journey in the field


Find limit of Fibonacci numbers.

Question: Let $\{a_n\}$ be the sequence of Fibonacci numbers, i.e. $a_1 = a_2 = 1, a_n = a_{n-1} + a_{n-2}, n \ge 3$. Find $$\lim_{n\to\infty}\sqrt[n]{a_n}.$$
Comment: The Fibonacci sequence is unbounded. Are you sure this is the question? Specifically, are you *positive* the question is not asking for the limit of the ratio between successive terms, i.e. $\displaystyle \lim_{n \to \infty} \frac{a_{n+1}}{a_n}$?
Comment: Thanks. I've already edited the question.
Comment: That makes more sense.
Comment: I'm guessing this approaches the golden ratio.
Answer: All terms are strictly positive, hence a strictly increasing sequence of integers. Conclude.
UPDATE after problem statement modified.
Using the well known formula $F_n=\frac1{\sqrt5}\left(\phi^n-\frac1{(-\phi)^n}\right)$ obtained by solving the linear recurrence, you easily get that the limit is $\phi$.
Comment: The question has been edited.
Comment: Thanks. I've already edited the question.
Comment: (You should mention that the term $\frac1{(-\phi)^n}$ goes to zero because $\frac1\phi\approx0.618<1$. Remember that if $\lvert z\rvert<1$, $z^n$ goes to $0$.)
Comment: That's what I meant by "easily".
Comment: Oh, thank You. For me, this formula became well known 30 minutes ago. :-)
Answer: Hint : for every $n \in \mathbb N$  ,  $F_n =\frac {(1+\sqrt 5)^n- (1-\sqrt 5)^n}{2^n\sqrt 5} $

Find limit of Fibonacci numbers.


What are the benefits of Views 3?

Question: I am exploring a reason to upgrade from Views 2x to 3x.
What major benefits Views 3x provides?
Are there any major API changes?
Answer: There are hundreds of improvements. There are also many API changes, but they would only affect custom code using Views hooks, not the views themselves, which are converted upon update.
Some major features:

Functionality similar to Semantic Views.
Group-by support and aggregate functions: you can do queries like "give me the count of nodes written by each user, sort by the amount of nodes DESC."
Views OR: you can separate different filter conditions by OR.
Pluggable pagers.
Pluggable exposed filters: expose items per page, sort.
Header, Footer, and Empty Text as pluggable areas.
Pluggable caching.
More argument, filter, and sort handlers.
Pluggable backends Flickr API, Apache Solr, RDF, etc.
Displays can now be disabled, renamed, and reordered, cloned.
A new UI in the Drupal 7 version.

Most importantly, it provides a much smoother upgrade to Views 7.x-3.x.
See the CHANGELOG.txt for a complete list of changes.

What are the benefits of Views 3?


Federated Authentication, JWT, ASP.Net WebAPI and Ajax using ThinkTecture IdentityServer and IdentityModel

Question: In my setup I have three applications running on three different domains:

idsrv.mydomain.com - ThinkTecture IdentityServer
api.mydomain.com - a RESTful API implemented using ASP.Net WebAPI
app.mydomain.com - a light weight HTML/javascript application

I would like the user to log into the app.mydomain.com, and the javascript ajax calls to go to api.mydomain.com
I have enabled federated authentication on both api.mydomain and app.mydomain, and switched to JWT tokens in IdentityServer as described here
I also have enabled CORS on the api.
Now I can login to app.mydomain.com and see the initial page, but the ajax requests going to the API are not authenticated so the calls to the API still fail. The problem is I have no idea where to go from here. I realize that I have to get the token that was passed to app.mydomain.com and make that available to the javascript on that page, and send that token along with each request to my API, but I don't know how to get the token and how to send it to the API. Any help would be appreciated.
Thanks
Answer: Check the sample given by the author, MVC and Web API (JWT)


.htaccess hiding missing images (and space the image was supposed to fill)

Question: I found this piece of code here to hide a missing image, it works well, although I am wondering if it could be adapted to do 2 things...
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule \.(png|gif|jpg|jpeg|bmp)$ /images/empty.gif [L]

1) Limit the action of this script to one folder only (I tried to create a .htaccess in the folder in question with no success), this script does not work unless it is in the root folder, and it applies to the whole site.
2) This script replaces the image with another one (even transparent), but if the image had width and height, in some context, we see the space of the image, could we adapt the script so it hides the space?
Note, I saw some jquery or javascript that does it, but it is not a good solution for me.
Thanks for your help
Answer: Transparency and image resizing cannot be handled by rewrite rules unless input image provides this information and you have different empty images as replacements.
For requirement #1 you can place this in `/admin/.htaccess/:
RewriteEngine on
RewriteBase /admin/

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.+?\.(png|gif|jpe?g|bmp)$ /images/empty.gif [L,NC]

Replace folder1 with your actual folder name.


Iteration over a nested set gives the out-of-index error

Question: I am writing a tik-tak-toe game. In place of using a number of combinations such as
def check_win(self,mark):
    return ((self.bd[1]==self.bd[2]==self.bd[3]==mark) or
        (self.bd[4] ==self.bd[5] ==self.bd[6] ==mark) or
        (self.bd[7]==self.bd[8]==self.bd[9] ==mark) or
        (self.bd[1] ==self.bd[4] ==self.bd[7] ==mark) or
        (self.bd[2] ==self.bd[5] ==self.bd[8] ==mark) or
        (self.bd[3] ==self.bd[6] ==self.bd[9]==mark) or
        (self.bd[1] ==self.bd[5] ==self.bd[9]==mark) or
        (self.bd[3] ==self.bd[5] ==self.bd[7]==mark)
        )

Want to use smaller code, but it is giving me out in index error.
win_comb = ((1,2,3),(4,5,6),(7,8,9),(1,4,7),(2,5,6),(3,6,9),(1,5,9),(3,5,7))
def check_win(self,mark):
    #pdb.set_trace()
    for elem in self.win_comb:
        if self.win_comb[elem[0]]== self.win_comb[elem[1]]== self.win_comb[elem[2]]==mark:
            return True
    else:
        return False

ERROR:
if self.win_comb[elem[0]]== self.win_comb[elem[1]]== self.win_comb[elem[2]]==mark:IndexError: tuple index out of range

Comment: Your already looping through the individual tuples in `win_comb`, and then attempting to index `win_comb` with those elements (`win_comb[elem]`). Just use `elem[0]` directly.
Answer: Even with the code as following, it is always tie even any Player wins
def check_win(self,mark):
#pdb.set_trace()
for elem in self.win_comb:
    if elem[0]]== elem[1]== elem[2]==mark:
        return True
else:
    return False

e Player-1, Enter your position from 1 to 9 9
 X| O | X

 O| X | O

 X| O | X

This is a tie
play again(yes/no)
Answer: Your problem is that in the new loop-based version of your function, you never inspect the board state at all!  In other words, where is the reference to self.bd?  It's missing!


Prove that the set $A$ is measurable and find its Lebesgue measure.

Question: Let $A ⊂ [0, 1] × [0, 1]$ be the set of points $(x, y)$ with decimal representations $x = 0.x_1x_2 ..., y = 0.y_1y_2 ...$
such that $x_ny_n = 5$ for all $n ∈ \mathbb{N}.$ Prove that the set $A$ is measurable and find its Lebesgue measure.
Okay so I know the straightforward way do this by taking open sets that go to measure zero.  However I have a slicker proof that seems to almost work.  Let $f(x, y) = 0$ if $(x,y) \notin A,$ and $= 1$ if it is.  Then $m(E) = \int_{I \times I}f(x,y)d(x \times y)$.  It is clear that $\int_I\int_I f(x,y)dxdy = \int_I\int_If(x,y)dydx = 0$.  This is because $x$ determines $y$ and vise versa so there is at most one $x$ for every $y$ so $\int_I\int_I f(x,y)dxdy = \int_I 0 dy$ and the same for the other one.  But, we don't know that $f(x,y)$ is measurable and in fact it is measurable iff $A$ is, so can we actually say anything about $\int_{I \times I}f(x,y)d(x \times y)$?
Thanks
Comment: You proved half: if it is measurable, then the measure is zero.  Now you have to do the other half.
Comment: I know, but I can't think of any way do do it other then just showing the measure is zero strait forward use of the definition, and then that makes this argument useless.
Answer: The map $x\mapsto x_n$ is measurable for each $n$ (it is ambiguous only on a set of measure zero, so the ambiguity doesn't matter). It follows that the set of $(x,y)$ with $x_ny_n=5$ is measurable for each $n$, and $A$ is a countable intersection of such.
Comment: What do you mean by the map $x \rightarrow x_n$?
Comment: Mapping the real number $x\in[0,1]$ to the $n$th digit in the decimal expansion of $x$.
Answer: Let $B=\{(x,y)\in [0,1]:\forall n (\{x_n,y_n\}\subset \{1,5\}) \}.$ $$\text { For each  } n \text { let } B(n)=\{ \sum_{j=1}^{j=n}b_j10^{-j}:b_j\in \{1,5\} \}. $$  Note that $B_n$ has $2^n$ members.For each $x\in B(n)$ let $I(x,n) = (x-10^{-n},x+10^{-n}).$ $$\text { Let } J(n)=\cup_{x\in B(n)}I(x,n).$$ $$\text { For every } n \text { we have }A\subset B\times B\subset J(n)\times J(n).$$ Let $\mu$ denote 2-dimensional Lebesgue measure.$$\text { We have } \mu (J(n)\times J(n))\leq \sum \{ \mu (I(x,n)\times I(y,n) : (x,y)\in B(n)\}=$$ $$=(2\cdot 10^{-n})^2(2^n)^2=2(2/10)^{2n}.$$ $$\text { Letting } n\to \infty \text { we obtain } \mu (A)\leq \mu (B\times B)=0.$$


Is it necessarily a closed subset?

Question: Let
$ f:X \rightarrow Y$ be a continuous map and $c \in Y$. Is $\{x \in X | f(x)=c\}$ necessarily a closed subset of $X$?
Attempt:
I was thinking about a contradiction. Can this be a counterexample?
$f(x) = \frac{1}{x^2+1}$ is continuous on the whole real line and and the image of the set $[0,\infty)$ is the set $(0,1]$. So we have found a closed set, whose image under a continuos function is not closed(and nor open).
Comment: The question isn't about the images of subsets of $X$: it's about the **inverse** images of singleton subsets of $Y$.
Comment: I believe it is not necessarily a closed subset.
so what can be a decent counterexample?
Answer: You will not find a counterexample where $Y$ is the real line.  This is because points are closed in the real line, and if $f$ is continuous then the inverse images of closed sets are closed.  (Note that $\{ x \in X : f(x) = c \} = f^{-1} [ \{ c \} ]$.)
Instead, you should consider topological spaces where points are not closed.
A good example would be $Y = \{ 0 , 1 \}$ with the indiscrete (trivial) topology. Now let $X$ be any space which has a non-closed subset $A$, and consider the mapping $f : X \to Y$ defined by $$f(x) = \begin{cases} 0, &\text{if }x \notin A \\ 1, &\text{if }x \in A.\end{cases}$$  That $Y$ is given the trivial topology means that any function $X \to Y$ is continuous, and taking $c = 1$ we have that $\{ x \in X : f(x) = c \} = A$ is not closed by choice.
Answer: If $Y$ is a $T_1$-space, so that singleton sets are closed, then $\{x\in X:f(x)=c\}$ is just the inverse image under $f$ of the closed set $\{c\}$ in $Y$, so by continuity of $f$ it is closed in $X$.
If there is a $c\in Y$ such that $\{c\}$ is not closed in $Y$, then $\{x\in X:f(x)=c\}$ need not be closed in $X$. For example, let $Y=\{0,1\}$, and let the open set of $Y$ be $\varnothing, \{1\}$, and $\{0,1\}$. ($Y$ is the Sierpiński space.) Note that $\{0\}$ is not open in $Y$, so $\{1\}$ is not closed. Define $f:\Bbb R\to Y$ by
$$f(x)=\begin{cases}0,&\text{if }x\le 0\\1,&\text{if }x>0\end{cases}\;;$$
it's easy to check that $f$ is continuous, but $\{x\in\Bbb R:f(x)=1\}$ is not closed in $\Bbb R$.

Is it necessarily a closed subset?


I am getting [object MediaError] while playing audio in html5 audio tag

Question: I am getting [object MediaError] while playing audio in html5 audio tag
I console the audio tag with code as below
myAudio.error.code

It displays 4 in console log.
Any one can assist me why I am getting this error. Even my audio tag is as below.
<audio id="scamper_music_sting_SFX" src="lib/game15/sounds/language/english/scamper_music_sting_SFX.mp3" type="audio/mpeg"/>

path is correct.
Comment: What is the MIME type returned by the server?
Comment: Hi Qantas , how can I display or get MIME type that is return from server.?
Comment: Hi Qantas, I found Content-Type equal to audio/mpeg
Comment: Just making sure that you're looking at the right one, could you place a screenshot and edit your question to attach that in?
Comment: Unable to attach screen shot, but here is the network content for the mp3 file

URL Method Result Type Received Taken Initiator Wait Start Request Response Cache read Gap
/vss/CCI_UX/lib/game15/sounds/language/english/scamper_music_sting_SFX.mp3 GET 304 audio/mpeg 210 B < 1 ms  5023 0 0 0 0 5601
Comment: Content-Type is actually audio/mpeg
Comment: Browser? There isn't enough information to answer  your question.
Answer: There may be some permission issues on the folder structure your audio file is in, you can test by moving the audio file into the same directory as your html file. Then test with the audio element below.
<audio id="scamper_music_sting_SFX" src="scamper_music_sting_SFX.mp3" type="audio/mpeg" />


Get the draft data in the webform hook_form_FORM_ID_alter()

Question: I'm building a multi page webform in Drupal 8 as shown below
(1) Consent to ask questions >>> (2) Chekcing eligiblity >>> (3) Consent to Participate >>> (4) Base line info >>> (5) Complete
multipage webform
In the 2nd page (Checking eligibility) as soon as the user clicks on Next Page > button, I need to validate the submitted values (which contains several radio buttons) and assess the user whether he is eligible to participate in a survey or not.
<code>/*
 * hook_form_FORM_ID_alter()
 */
function webform_form_webform_submission_registration_content_node_77_form_alter(&$form, FormStateInterface $form_state, $form_id) {
    ...
    if($form_id == 'webform_submission_registration_content_node_77_form')
    {
        $form['#submit'][] = 'webform_webform_submit_handler';

    }

}

function webform_webform_submit_handler($form, &$form_state) {
    /* This is not displaying any submited values mostly because I haven't clicked on Sumbit button yet */
       dpm($form_state['values']);
}
</code>
src: https://www.drupal.org/node/2634266
Is there any way to get the Form's draft values before submission?
Any better approach to process the values within the page(form) itself?
Any help much appreciated.
Comment: I recommend trying to use a WebformHandler plugin. https://drupal.stackexchange.com/questions/223342/add-custom-submit-handler-to-form
Comment: Sure, let me try that!
Comment: Perfect, this is what i want, Thank you jrockowitz!!
Answer: As jrockowitz suggested, the best way to get the webform's data and processing it is, to create custom WebformHandler. Please refer "Creating a custom webform handler plugin for drupal 8" section here for more details.


looking for "my-account/edit-address/billing" in woocommerce php files?

Question: hi,
I'm working on a WordPress project.
woocommerce in the page bellow has a billing address form that i want to edit and add server-side form validation.
but i cant find the form page location in woocommerce's php files.

/my-account/edit-address/billing/

Where is the form page location?
Is there any function that i can use for edit this page?
And how can i do that?
Thanks alot
Answer: You find the file in:

{wordpress-path}/wp-content/plugins/woocommerce/templates/myaccount/form-edit-address.php


Inverse of polynomial over a finite field

Question: The question is the following:
Can you deduce if ${2x + 1}$ is invertible in $\mathbb{Z}_3[x]/(x^2 + 2x + 2)$? In case of a positive answer, give its inverse.
Following the Wilson's theorem, for $K[X]/(f)$, any polynomial of degree $1 \leq deg < n$ will admit an inverse of degreee $1 \leq deg \leq n$ mod $f$. Since $n = 3$ because I'm working on $\mathbb{Z}_3$ and $deg = 2$, I guess $2x+1$ is irreductible in this case.
Once I want to find the inverse I've been following this post. The table using Euclidean algorithm is the following:
\begin{array}{r|r|r|r}
    & & (x+\frac{3}{2})/2 & (2x+3)/5 \\\hline
   1 & 0 & 1 & -(2x+3)/5\\\hline
   0 & 1  & -\big(\dfrac{x}{2} + \dfrac{3}{4}\big) & \dfrac{x^2}{5} + \dfrac{3x}{5} + \dfrac{29}{20}\\\hline
   x^2+2x+2 & 2x+1 & 5/4 & 0
\end{array}
So, finding the lineal combination I obtain this result:
$\dfrac{5}{4} = 1\times(x^2 +2x +2) - \big(\dfrac{x}{2}+\dfrac{3}{4}\big)\times(2x+1)\xrightarrow{}\dfrac{5}{4} = f(x) - \big(\dfrac{x}{2}+\dfrac{3}{4}\big)g(x)$,
Here is where I get stuck. I let 1 on the left side so I have the following result:
$1 = \bigg(\dfrac{4}{5}\bigg)(x^2+2x+2)- \bigg(\dfrac{2x}{5}+\dfrac{3}{5}\bigg)(2x+1)$
But once I arrive here I don't know how to get the value of the inverse.
Can anyone help me? Thank you very much.
My result, which I'm not absolutely sure is that the inverse of $2x+1$ is:
$-\big(\dfrac{2x}{5}+\dfrac{3}{5}\big)$ mod $x^2+2x+2$.
In the remote case it's correct, is there any way to get the final value instead of letting it in function of mod $f$?
Thank you again.
Bernat
Answer: Note that $-\frac15 = 1$ in $\Bbb Z_3$, and $3 = 0$, so your inverse candidate is equal to $2x$. And we can just check whether this is in fact an inverse, using that $3 = 0$ and $x^2 = x+1$:
$$
2x\cdot (2x+1) = 4x^2 + 2x = 4(x+1) + 2x\\
= 6x + 4 = 1
$$
So yes, that is indeed the inverse you're looking for.
Comment: Wow dude! I can't say anything but thank you. I didn't notice that equivalences in $\mathbb{Z}_3$. Thank you very much :)
Comment: @BernatPedrolVozmediano Taking the negative of a number is the same as multiplying by $-1$, and dividing by $5 = -1$ is the same thing. So taking the negative _and_ dividing by $5$ cancel, and we get $-\frac15 = 1$.
Answer: Hint: $0=x^2 + 2x + 2$ implies $0 = 2x^2+4x+4 = 2x^2+x+1 = x(2x+1)+1$
Answer: Since $\mathbb{Z}/3\mathbb{Z}$ is a field, we know that $\mathbb{Z}/3\mathbb{Z}[x]$ is an Euclidean domain with norm, $\deg f(x)$.
From now, I'll have worked with your example.
We can find $p(x), q(x) \in \mathbb{Z}/3\mathbb{Z}[x]$ which satisfies
$$
(x^2+2x+2) p(x) + (2x + 1)q(x) = 1
$$
It holds if $p(x) = 2, q(x) = -x$.
It means that
$$
(2x + 1)(-x) \equiv 1 \mod x^2+2x +2
$$


Pyspark dataframe - get count of variable in two columns

Question: I'm using pyspark dataframe with a goal to get counts of a variable which can be in multiple columns. Wrote a sql query to get this but unable to translate it for dataframes.
Given the below dataframe, need to get counts of "Foo", "Bar", "Air" in Col1, Col2.

+----------+----+-----+
|      ID  |Col1|Col2 |
+----------+----+-----+
|2017-01-01| Air| Foo |
|2017-01-02| Foo|  Bar|
|2017-01-03| Bar| Air |
|2017-01-04| Air|  Foo|
|2017-01-09| Bar|  Foo|
|2017-01-01|Foo |  Bar|
|2017-01-02|Bar |  Air|
|2017-01-01|Foo |  Air|
|2017-01-02|Foo |  Air|
+----------+----+-----+

Expected output

+-------+-----+
|Var .  |Count|
+-------+-----+
|    Foo|  7  |
|    Air|  6  |
|    Bar|  5  |
+-------+-----+
Answer: Try this:
Creating DataFrame
import pyspark.sql.functions as f

l1 = [('2017-01-01','Air','Foo'),
('2017-01-02','Foo','Bar'),
('2017-01-03','Bar','Air'),
('2017-01-04','Air','Foo'),
('2017-01-09','Bar','Foo'),
('2017-01-01','Foo','Bar'),
('2017-01-02','Bar','Air'),
('2017-01-01','Foo','Air'),
('2017-01-02','Foo','Air')]

df = spark.createDataFrame(l1).toDF('id', 'col1', 'col2')
df.show()
+----------+----+----+
|        id|col1|col2|
+----------+----+----+
|2017-01-01| Air| Foo|
|2017-01-02| Foo| Bar|
|2017-01-03| Bar| Air|
|2017-01-04| Air| Foo|
|2017-01-09| Bar| Foo|
|2017-01-01| Foo| Bar|
|2017-01-02| Bar| Air|
|2017-01-01| Foo| Air|
|2017-01-02| Foo| Air|
+----------+----+----+

First concat col1 and col2 with , as a separator. Split the column by , and then explode will give row for each word.
df.withColumn('col', f.explode(f.split(f.concat('col1',f.lit(','),'col2'),','))).groupBy('col').count().show()
+---+-----+
|col|count|
+---+-----+
|Bar|    5|
|Foo|    7|
|Air|    6|
+---+-----+


Vector version of the proof that $\overline{X}$ and $S^2$ are independent

Question: Assume that $X'_i$s are i.i.d distributed as $N(\mu,\sigma^2)$.
There is a famous theorem that the sample mean $\overline{X}=\frac{1}{n}\sum_{i=1}^n X_i$ and the sample variance  $S^2=\frac{1}{n-1}\sum_{i=1}^n (X_i-\overline{X})^2$ are independent.
I know there are already numerous answers about this theorem. Here I want ask a specific method of the proof.
Step1: Let $X=\{X_1,X_2,...,X_n\}'$, $\iota=\{1,1,...,1\}'$, $P=\iota(\iota'\iota)^{-1} \iota'$
Then, $\overline{X}= {1\over n} \iota' X$
Step2: $S^2= {1\over n-1} X'(I-P)X$
Step3: $S^2$ is a function of $(I-P)X$
Step4: $\iota' X$ and $(I-P)X$ are independent
Step5: Therefore, $\overline{X}$ and $S^2$ are independent.
In this method, I can understand step1 ~ step4. However, I cannot understand why step5 holds. Specifically, I don't know the logical bridge between step 3 and step5. Although $S^2$ is a function of $(I-P)X$, since $S^2$ is not multiplied by a constant with $(I-P)X$, can't we say that $\overline{X}$ and  $S^2$ are independent just because  $\overline{X}$ and $(I-P)X$ are independent?
Comment: @martian03 $I-P$ is idempotent, then $S^{2}=(n-1)^{-1}X^{\top}(I-P)X=(n-1)^{-1}\bigl((I-P)X\bigr)^{\top}\bigl((I-P)X\bigr)$ hence is a function of $(I-P)X$.
Comment: Thank you! @Q9y5, If you write this as an answer, I will select it correct answer.
Comment: If $X$ and $Y$ are independent, $g(X)$ and $f(Y)$ are independent for any measurable functions $g$ and $f$.
Comment: Thank. @d.k.o. Actually, I cannot have confident that $S^2$ is a function of $(I-P)X$.  $S^2$ is a function of $(I-P)X$ and $X'$. Hence, how can I guarantee that if $(I-P)X$ and $Y$ are independent, $g((I-P)X, X')$ and $Y$ are independent? For example,  if $(I-P)X$ and $Y$ are independent, can we say that $X$ and $Y$ are independent?
Comment: Further question: For the step4, my manual uses the fact that $E[(I-P)X(\iota'X)']=0$. However, I cannot understand how this can guarantee independence of $(I-P)X$ and $(\iota' X)$
Answer: For $P\equiv \iota(\iota^{\top}\iota)^{-1}\iota$, it's symmetric and we have $P^{2}=\iota(\iota^{\top}\iota)^{-1}\iota=P$, meaning it's idempotent. Using this result, we deduce $(I-P)(I-P)=I-P-P+P^{2}=I-P$, thus $I-P$ is also idempotent.
Therefore,
$$S^{2}=(n-1)^{-1}X^{\top}\underbrace{(I-P)}X=(n-1)^{-1}X^{\top}\underbrace{(I-P)(I-P)}X=(n-1)^{-1}\bigl((I-P)X\bigr)^{\top}\bigl((I-P)X\bigr),$$
hence a function of $(I-P)X$.

Update for your question:
Note that $(I-P)X$ and $\iota^{\top} X$ are all normal distributed, hence uncorrelated$\iff$independent.
$$
\mathrm{Cov}\bigl((I-P)X,\iota^{\top}X\bigr)=\mathbb{E}[(I-P)X(\iota^{\top}X)]-\mathbb{E}[(I-P)X]\mathbb{E}[\iota^{\top} X]=0-(I-P)\mu(\iota^{\top}\mu)=0.$$


How to stop cron process without rebooting my server?

Question: I have tried the following:
drush php-eval "\Drupal::lock()->release('cron');"

This had no effect. I'm still seeing "Attempting to re-run cron" errors pile up in the log.
I also tried the mysql query:
DELETE FROM semaphore WHERE name = 'cron';

The query ran fine, but had no effect. I'm still seeing "Attempting to re-run cron" errors pile up in the log.
I also checked the processes:
ps aux | grep cron

I saw a number of Drupal-related cron processes, and killed them all.
I then repeated...
drush php-eval "\Drupal::lock()->release('cron');"

None of this has had any effect.  I clear the log, and then new "Attempting to re-run cron" errors appear.
Comment: Did you ensure to set the poor man's cron to "execute never" at /admin/config/system/cron?
Comment: That was it exactly.  Once I switched that to "never," and then ran the drush command in my question, it stopped.
Answer: Check if the "Automated Cron" core module is enabled. If so, you'll find a setting at /admin/config/system/cron where you can set the so called poor man's cron (cron triggered by site traffic) to be executed "never".
If no other cron has been configured, like a server cron executing drush cron for example or external service that periodically visits the hashed cron URL (which can be found on the same page as the poor man's cron),  setting poor man's cron to be executed "never" should then completely stop any cron running on your site.