Blackjack-reminiscent cards question

Question:
Suppose I have a deck of cards. This deck of cards has an infinite amount of cards that are labeled 1,2,3,4,5. You can assume there is an infinite amount of each card. The game works as follows: I pull two cards from this deck. You then must choose one of the two cards to add to your score (You can see the cards). Your score starts as 0, and we will play 3 rounds of this game. If your score ends up becoming ≥ 7, you have "busted" and your score will become and remain 0 for the rest of the game.
a. How would you play this game if your goal is to maximize your score?
b. What if we don't know the distribution of the deck the cards are pulled from?
c. What if cards can be negative too?
d. What if there is one of each card, but they are replaced after each round?
e. What if you play an opponent and you get paid 10 if your score is strictly greater, otherwise nothing?
f. What if you can wager before each turn? When do you wager?
g. What if you can wager for the game against an opponent and you know their cards? What about if you don't? What about if you know if they have wagered?

This was from an interview. For a strategy for the first pick, I thought that if the maximum of the two cards was less than 3, I'd pick the bigger one. If the maximum was greater than 3, I'd pick the smaller one. I calculated this by finding E(L), which would be the expected value of the lower card, and I found E(L) by summing up E(L | H = i)P(H = i) for all i, 1-5, where H is the value of the higher card. However, after calculating the expected value of the first pick using this strategy, I get that it's 3.8, and E(L) is 2.2, which means that you are always expected to lose, which doesn't sound right. I arrived at this strategy by reasoning that since your expected score over the last 2 picks will be 4.4, 1 or 2 will always be a safe choice for the first pick. However, if your max is greater than or equal to 3, then you would want to pick the smaller one to decrease your odds of busting as much as possible.
I got more lost on the followups, in part due to not understanding wording, i.e. for e), wouldn't your strategy just remain the exact same?
Comment: In general, having an infintie deck seems confusing. You would still need to specify the probabilities within that deck.  Clearer, I think, to just say you have  two fair five sided dice that you toss.
Comment: @lulu Alternative: if after two rounds, your score is $~\geq 6,~$ then you must go busted.  So, I would examine the $~4~$ cases of score after two rounds being an element in $~\{2,3,4,5\},~$ and calculate the exprected value based on this.   Then, I would recurse to the expected value if your score after one round was some element in $~\{1,2,3,4,5\},~$ and so on.
Comment: Seven questions is six questions too many.
Comment: @PaulSinclair My understanding was that the cards would be replaced after the two was drawn, so it would change the odds, i.e. $3, 3$ would be a possible draw with the infinite deck but not with only 5 cards
Comment: In any case, I suggest working out various explicit strategies.  First, I'd start with a two round game.
Comment: The last round has no optionality in it...your choice is always determined.  So you only need to consider the first two rounds.  I'd start simple, just take the minimum in all cases.  Get the expected value of that strategy.  Then try to do better.
Comment: My response to (b) is to make my original answer to (a) my answer to it instead, and then re-answer (a) with the pretense that I do know the distribution. (d) is an obvious "that doesn't change anything". (e) is I cannot do any better than (a) or (b), whichever holds, so I still do the same thing.
Comment: That is not what it says. The wording is ambiguous. I would interpret it as after each time a card is drawn, it is returned to the deck (and the deck randomized) before the next draw. But this is an interview question, so that and other ambiguities in the question may be intentional to see how you handle them - in particular, whether you will ask for clarification, or plow forward on an assumption. Interview questions like this are not really about "can you solve the problem", but about "how do you respond to situations".
Answer: Currently the question is a tad ambiguous with its wording, so I will assume the game is identical to being given two $5$-sided dice with numbers $1$, $2$, $3$, $4$, $5$, which are assumed to be uniform for (a).
For (a), the key observation is that on the last round, if your score is $\leq n$ for some $n \in \{2, 3, 4, 5\}$, the probability you can choose a number that gets you to a score of $m$ for some $n < m \leq 6$ is always $\frac{2m - 3}{25}$ regardless of $n$. Hence, your expected score increases with a smaller score at the end of round 2. Thus, the optimal strategy is to always choose minimum number for round 1 and round 2, and choose the largest number keeping you under the threshold for round 3.
Calculating the probabilities and expected values explicitly:
Let $E_n$ denote the expected score after ending Round 2 on a score of $n$. Then
\begin{align*}
E_5 &= \frac{9}{25} \cdot 6 = \frac{54}{25}\\
E_4 &= \frac{9}{25} \cdot 6 + \frac{7}{25} \cdot 5 = \frac{89}{25}\\
E_3 &= \frac{9}{25} \cdot 6 + \frac{7}{25} \cdot 5 + \frac{5}{25} \cdot 4 = \frac{109}{25}\\
E_2 &= \frac{9}{25} \cdot 6 + \frac{7}{25} \cdot 5 + \frac{5}{25} \cdot 4 + \frac{3}{25} \cdot 3 = \frac{118}{25}
\end{align*}
Let $p_n$ denote the probability of ending round $2$ on a score of $n$, utilising the minimisation strategy:
\begin{align*}
p_2 &= \frac{9}{25}\cdot \frac{9}{25} = \frac{81}{625}\\
p_3 &= 2\cdot \frac{9}{25} \cdot \frac{7}{25} = \frac{126}{625}\\
p_4 &= 2\cdot \frac{9}{25} \cdot \frac{5}{25} + \frac{7}{25} \cdot \frac{7}{25} = \frac{139}{625}\\
p_5 &= 2\cdot \frac{9}{25} \cdot \frac{3}{25} + 2\cdot \frac{7}{25} \cdot \frac{5}{25} = \frac{124}{625}
\end{align*}
This gives overall expected score of
\begin{align*}
E &= \sum_{i = 2}^5 p_i E_i = \frac{42359}{15625} \approx 2.711
\end{align*}
For (b), if we don't know the distribution, I would expect this strategy to still be optimal since you maximise your chances of not disqualifying.
For (c), I would need more information regarding what the negative card values are but it means there are a lot more of the final round cases left to check, so its possible that "smaller score = better" idea doesn't hold anymore.
For (d), the key observation holds true again, except the probability is $\frac{m - 2}{10}$. Hence, the same strategy holds but the probabilities and expected values change:
Let $E_n$ denote the expected score after ending Round 2 on a score of $n$. Then
\begin{align*}
E_5 &= \frac{4}{10} \cdot 6 = \frac{12}{5}\\
E_4 &= \frac{4}{10} \cdot 6 + \frac{3}{10} \cdot 5 = \frac{39}{10}\\
E_3 &= \frac{4}{10} \cdot 6 + \frac{3}{10} \cdot 5 + \frac{2}{10} \cdot 4 = \frac{47}{10}\\
E_2 &= \frac{4}{10} \cdot 6 + \frac{3}{10} \cdot 5 + \frac{2}{10} \cdot 4 + \frac{1}{10} \cdot 3 = 5\\
p_2 &= \frac{4}{10}\cdot \frac{4}{10} = \frac{4}{25}\\
p_3 &= 2\cdot \frac{4}{10} \cdot \frac{3}{10} = \frac{6}{25}\\
p_4 &= 2\cdot \frac{4}{10} \cdot \frac{2}{10} + \frac{3}{10} \cdot \frac{3}{10} = \frac{1}{4}\\
p_5 &= 2\cdot \frac{4}{10} \cdot \frac{1}{10} + 2\cdot \frac{3}{10} \cdot \frac{2}{10} = \frac{1}{5}\\
E &= \sum_{i = 2}^5 p_i E_i = \frac{3383}{1000} = 3.383
\end{align*}
For (e), we see that the (a) strategy should still be able to maximise your score, and you can't really do better than the strategy in (a), so I would keep with the strategy.
For (f), you can use Kelly Criterion to size your bets after round 2, so you should be making wagers if you end round 2 on $2, 3,$ or $4$ (assuming $1:1$ betting). You can do similar for the end of round 1 and before the start of the game.
For (g), knowing their cards changes the probabilities of victory but you can still use the Kelly Criterion to size the bets. If you don't know their cards, the best you can do is basically the same as (f), but now you account for probabilities of winning as well. If you know what they wager, then that again changes your betting strategy since the bet sizes gives you information on their cards (assuming they are a rational agent, and thus will also use the Kelly Criterion).

Blackjack-reminiscent cards question


How can I get Nginx to tell Firefox to cache my content?

Question: The following headers (from a static media response) don't lead to caching in Firefox. In Chrome they do.
HTTP/1.1 200 OK
Server: nginx
Date: Sat, 22 Dec 2012 21:20:39 GMT
Content-Type: application/x-javascript; charset=utf-8
Last-Modified: Fri, 21 Dec 2012 19:28:54 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: public, max-age=86400
Content-Encoding: gzip

My Nginx server for static content looks like this:
server {
    listen 80;
    server_name static.example.com;

    # Logs
    access_log /var/log/nginx/static.example.com.access.log;
    error_log /var/log/nginx/static.example.com.error.log;

    # Root
    location / {
        alias /var/www/app/deps/current/repo/src/example/static/;
        add_header Cache-Control "public, max-age=86400";
    }
}

I've also tried using expires 24h;, in place of add_header ..., without luck.
I've found numerous, similar complaints on the Internet, but no solutions, nor any ideas of why this is, other than one person's mention of how Firefox purposely strays from the specification for handling HTTP 1.1 Cache-Control headers.
Is there any way to get Firefox to cache my static media, via a header or multiple headers? I don't want 75% of my server's static media requests to come from 20% of my users, just because Firefox is busted.
Note, I'm using Firefox 17.0.1 with default settings, but with Firebug installed and open to the Net tab.
Update:
Using, instead:
expires 1d;
add_header Cache-Control public;

Causes the headers to include:
Expires: Wed, 26 Dec 2012 19:54:20 GMT
Cache-Control: max-age=604800, public

This also doesn't cause Firefox to cache the content.
Comment: See comments on cnst's answer below. "Web Developer" was disabling all cache.
Answer: How do you determine that Firefox is not caching your files?
When a Last-Modified header is present in a reply, the browser is supposed to be making all subsequent requests for the same URL with a If-Modified-Since header, and then the response from a server may only contain a header (with no body) if the file has not been modified since.
IIRC, Gecko also looks at how old the Last-Modified date is.  If it's relatively recent, then it only makes sense that the content changes all the time, and has to be re-requested (with a If-Modified-Since or the like) quite often.  On the other hand, if the date is several weeks, months or years old, then the content is likely to be cached for an extended period of time.
Another thing to look at:  do you actually have the correct timezone and time on your Firefox machine?
Comment: So... it appears that the "Web Developer" plugin for Firefox actually disables caching altogether, for whatever reason :/ thanks so much for your continued comments, which are what lead me to search for the correct thing and find that.
Comment: Thanks! That's a great help. Do you know if there is a way to prevent Firefox (via my server, assuming FF has default settings) from sending any request after the initial one? Even with just a body returned, this is wasteful, as I have about 12 media items per view and about 20-20 page views per user in my UI.
Comment: Not sure you should really worry about this.  First of all, I would be surprised if Gecko would be sending these subsequent requests (with `If-Modified-Since`) all the time, it's probably only done with the recently-modified files and only every couple of requests or so; second, if it's just static files, these requests are probably really cheap to complete due to nginx efficiency and inode cache.  Just for the sake of the experiment, try temporarily changing the modified date of the files with `touch(1)`, and follow the links without doing any manual refresh of any page, and cache will be OK.
Comment: What I meant is, try temporarily changing the modification date to something really old (like 2005), and then try browsing the site without explicitly causing any refresh actions -- just follow the links back and forth, and use the Back and Forward buttons in the browser.  I'm pretty sure you'll see that the cache is working just fine in Firefox, and it won't be re-making 20 request for static content for every page.  But if you start clicking Refresh here and there, then of course it better make sure that the content on the server has not changed since being cached!
Comment: I just checked and Firefox is indeed requesting without a `If-Modified-Since`, and is indeed being served the file contents, not just headers. If the file is 200Kb, it'll take about 150ms to download. I'm afraid that Firefox might be a piece of junk. Chrome will cache the content on the first request, even if I don't include any caching headers. Why would Mozilla want their browser to be slow and destroy my users' browsing experience byte by byte? Also, I am just clicking back and forth between links, and back-forward buttons, not refreshing (a refresh will cause even Chrome to re-download).
Comment: Again, how do you determine that the requests are without `If-Modified-Since`?  200 status code in the logs instead of `Not Modified` `304`?  tcpdump?  Gecko certainly has a cache, and it's certainly supposed to work in Firefox with documents that have correct `Last-Modified` dates in the headers.
Comment: I can tell because A) there is no `If-Modified-Since` header sent ("Live HTTP Headers" plugin), B) the response headers are 200, and C) the time it takes to receive each response is on par with how large the file is (e.g., a 500k file takes 3-5 times as long as a 100k file to finish, which wouldn't be the case if they were simply read from disc - I have an SSD). Also note, I'm not refreshing the page, just clicking around on links within the pages. I'm telling you, I don't think Firefox caches content anymore, for real. This happens on every site I visit, no matter the headers. Chrome caches.
Comment: Must be something wrong with your Firefox settings or bogus plugins, and then it's not a serverfault jurisdiction whatsoever.  Try `about:cache` and also search for "browser.cache" preferences in `about:config` that are modified from default (such appear in bold typeface) and appear to have any remote effect on Gecko's ability to cache.  If in doubt, `Reset` all such non-default entries.  Also, make sure to disable plugins (`plugin.disable` set to `true` works great, make sure to restart the browser).
Comment: Also, to the contrary of your experience, it's actually oftentimes impossible to access the cache entries of Chrome.  I've personally experienced a situation where a deleted documented I wanted to retrieve was cached by Chrome, yet going offline and trying to access it through the URL didn't work.  I found that the response was cached as gzipped, and Chrome offered absolutely no way to receive it as regular document again, or even as binary body.  There is non-JS code online that will let you decode such documents, but as a user I would strongly disagree that G Chrome caching actually "works".
Answer: server {
    expires    1d;
    add_header Cache-Control public;
    listen 80;
    ....
}

Try it this way please like described in nginx docs

So i was courious and tried caching myself With config below.
What i have changed is that i started a app on localhost:4567.
Whereas in external website a proxypass is configured.
More or less like most caching examples i could find.
user nginx; worker_processes 2;
error_log /var/log/nginxtesterror.log; pid /run/nginx.pid;
events { worker_connections 1024; }
http { include /etc/nginx/mime.types; default_type
    application/octet-stream;
    log_format main '$remote_addr - $remote_user [$time_local]
                      "$request" ' '$status $body_bytes_sent
                      "$http_referer" ' '"$http_user_agent"
                      "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    sendfile on; #tcp_nopush on; keepalive_timeout 65;
    proxy_cache_path
    /var/www/app/deps/current/repo/src/example/static/ levels=1:1:2
    keys_zone=one:200m max_size=1000m loader_files=2000 inactive=60m;
    proxy_temp_path /var/www/app/deps/current/repo/src/example/tmp;
    proxy_cache_valid 1d;
    gzip on; gzip_disable msie6; gzip_static on; gzip_comp_level 4;
    gzip_proxied any; gzip_types text/plain text/css
    application/x-javascript text/xml application/xml
    application/xml+rss text/javascript;
    server { listen 80; server_name static.example.com;
        proxy_set_header Host $host; proxy_set_header X-Real-IP
        $remote_addr; proxy_set_header X-Forwarded-For
        $proxy_add_x_forwarded_for;
        proxy_pass_header Set-Cookie ;
        location ~*
                .(?:ico|css|js|gif|jpe?g|png|pdf|zip|tar|t?gz|mp3|wav|swf)$
                { expires max; add_header Pragma public; add_header
                Cache-Control public; }

        location / { proxy_pass http://localhost:4567; proxy_cache_key
            $cache_key; proxy_cache one; add_header Cache-Control
            public; proxy_cache_valid 1d; proxy_cache_use_stale error
            timeout invalid_header http_500 http_502 http_504
            http_404; }
    }
    server {
        root /var/www/app/deps/current/repo/src/example/static/;
        listen 127.0.0.1:4567; set $cache_key
        $scheme$host$uri$is_args$args;

        # Logs access_log
        /var/log/nginx/static.example.com.access.log; error_log
        /var/log/nginx/static.example.com.error.log;

        # Root
        location / {
            alias /var/www/app/deps/current/repo/src/example/static/;
            }
       }
}

Comment: I just tried this. See the update to my question.
Comment: Did that work for you? I just tried, without luck :( I'm not looking to cache things in Nginx btw, just serving static content and wanting the browser to cache it. I checked in Chrome, and it's still caching correctly.
Comment: My example does server static content as well but on localhost:4567.
Proxy is fetching and caching. Did you try to use different Firefox Profiles just to be on the safe side that its not related to browser settigns?
Comment: Does it cause Firefox to cache content for you though? It doesn't for me. My Firefox settings are factory default.


how can I know if this specific thread is still running on the server?

Question: I am using a thread in my ASP.Net application to be run in the backGround every 2 hours, using C# See code below, but my question is how can I know if this specific thread is still running on the server ?? Note: I am using Windows server 2008 R2 Standard
note : but I wanna check i on the server because it is a production server. Windows 8 R2 Standard
<code> // Create runner Thread and start it
     System.Threading.Thread OrderStatusFromThread = new       System.Threading.Thread(new System.Threading.ThreadStart(OrderStatusChange));
        OrderStatusFromThread.IsBackground = true;
        OrderStatusFromThread.Name = "OrderStatusFromThread";
        OrderStatusFromThread.Start();
    }

   static void OrderStatusChange()
    {
        while (!ShutDown)
        {
          System.Threading.Thread.Sleep((1000 * 60)*10);
          UpdateOrderStatusFromAPI();
        }
    }
</code>
Comment: You may want to consider running your code as a service then the standard service management tools will show you its state. Also look at scheduled tasks, these have history and will note if the process failed.
Answer: Use Thread.isAlive to determine f thread is running. You can get the syntax from
http://msdn.microsoft.com/en-us/library/system.threading.thread.isalive%28v=vs.110%29.aspx
Comment: I'm trying to find a tool similar to the Windows Task Manager utility which can show details on all threads running in a given process, such as their names, IDs, etc ..., I wanna check i on the server because it is a production server.


how to convert date format in jquery

Question: i need jquery code for converting date format below is the example
i need to convert from FORMAT 1 to FORMAT 2
FORMAT 1: Wed Apr 20 07:05:00 PDT 2016
FORMAT 2: 2016-04-20 07:23:42.476

Comment: FYI, jQuery doesn't handle date, javascript do
Answer: Try this:
var DateCreated = new Date(Date.parse("Wed Apr 20 07:05:00 PDT 2016")).format("yyyy-mm-dd h:i:s");

Comment: There is no native `Date.prototype.format()` method. I guess you are referring to any external lib (moment js???)
Comment: @Dhara  .format() is not working. because im not using supported extnl lib js for this. so can u give some other way without extnl lib

how to convert date format in jquery


regression when a dependent variable is a proportion (with known numerator/denominator)

Question: I have a question concerning regression analysis with a dependent proportional variable.
In our study we have an outcome variable called Study-quality.
Study-quality is determined by looking at 11 criteria which are present or absent. When a criterium is met, a study can gain +1 point. So a study can gain a total score between 0 and 11. higher amount of points = better studyquality.
Some criteria are not applicable for certain studies, when this is the case, the total amount of points that can be gained is 9 or 10.
To make a fair comparision, we counted the total gained points per study and devided them by the total points one study could gain. (so for example 7/10 or 4/11).
this proportion is our outcome variable Studyquality.
leading to my question:
we have collected several variables (year, sample size, funding source, study setting, etc.) we think are associated with Studyquality.
e.g. the more recent the study is published, the more likely studyquality would be higher
What type of regression analysis could be best used to test possible associations with a proportional outcome var? (wihtin STATA software?)
Thank you!
Answer: Your data can be simply modeled using logistic regression. Logistic regression can be used also for data in other format then 0's and 1's, for example in R you can use it with three different (but equivalent) formats of data. In fact you can view your data as successes and failures in some number of trials. Even if you have only the aggregated data (total number of successes) accompanied with the number of criteria that were used, you can still use logistic regression for such data. The model that you assume is modeling $k$ successes in $n$ Bernoulli trials, where the probability of success $p$ is unknown and to be estimated, i.e. you are dealing with binomial distribution and logistic regression is designed for such problems.
The overall effect may be viewed as the per-study effect estimated using logistic regression. Moreover, logistic regression, or alternatively generalized mixed effects model with logistic link, may enable you to study the influence (control for) of other variables.


Commerce file description not showing

Question: I'm using Commerce License and Commerce Files to sell digital downloads (zip files). Usually this works completely fine, so I'm thinking this might be a bug on my site on not in the modules themselves - but I'm not sure.
On one specific product the file description (and therefore the download link) doesn't appear on the user's file tab.
The orders that needs to download are in 'pre-order' paid state (using Commerce Pre-oder, which isn't a problem on other products on our site.
Here's the pre-order rule in case that's causing this:
<code>{ "commerce_preorder_checkout_complete_generate" : {
    "LABEL" : "Generate pre-order pending orders on checkout completion",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "10",
    "OWNER" : "rules",
    "TAGS" : [ "Commerce Pre-order" ],
    "REQUIRES" : [ "rules", "commerce_preorder", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "commerce-order" ], "field" : "commerce_preorder_order" } },
      { "data_is_empty" : { "data" : [ "commerce-order:commerce-preorder-order" ] } }
    ],
    "DO" : [
      { "commerce_preorder_generate_pending_orders" : {
          "USING" : { "commerce_order" : [ "commerce-order" ] },
          "PROVIDE" : { "pending_orders" : { "pending_orders" : "Pending orders" } }
        }
      }
    ]
  }
}
</code>
Any ideas as to how to investigate the issue?
Answer: You can check the rules that change the order state into: 'pre-order'.
This would be my first guess that the rules are not configured ok.
Hope that i helped.
Comment: thanks for the input. I've inserted that rule in the original question. But since it works on other pre-order products I'm thinking it's caused by something else?

Commerce file description not showing


Conditions for membership of $H^2$

Question: I'm looking for conditions for a function $u$ defined on a bounded domain $\Omega\subset\mathbb{R}^n$ to be an element of the Sobolev space $H^2(\Omega)$. I heard the other day that if $u$ is harmonic and satisfies Dirichlet boundary conditions then it is automatically in $H^2(\Omega)$, and a similar result holds for Neumann boundary conditions. Is this true, and if so, where might I find such a result proved? (Googling yields little of use, unfortunately.)
If it is not, can anybody point me to any conditions they know of? Excluding, of course, the trivial $H^2(\Omega)\subset H^2(\Omega)$!
Answer: One needs to assume something about the regularity of the boundary and of the boundary data. Simply saying "satisfies Dirichlet boundary conditions" is not useful without further information on the boundary data.
Example
Let $\Omega\subset \mathbb{R}^2$ be the unit disk. Thinking of $\mathbb{R}^2$ as complex plane $\mathbb{C}$, let $u(z)  = \operatorname{Re}((1-z)^{p})$ where $0<p<1$. This is a harmonic function in $\Omega$, and is continuous on $\overline{\Omega}$. However, it's not in $H^2(\Omega)$. Indeed, its second derivatives behave like $|1-z|^{p-2}$ near $1$, and since $2(p-2)<-2$, they are not square-integrable.
Regularity theorems
A standard reference is Theorem 8.12 in Gilbarg-Trudinger, which asserts that $u\in H^2(\Omega)$ if it solves the PDE $\Delta u=f$  with boundary conditions $u=g$ where

$f\in L^2(\Omega)$
$\Omega$ has $C^2$-smooth boundary
$g$ is the trace of some $H^2$ function on $\Omega$

The latter assumption is most troublesome to check, unfortunately. It is used to subtract off such $H^2$ function and then deal with homogeneous boundary condition.
Another reference is section 6.3.2 in PDE by Evans; he immediately goes to the homogeneous case.
Comment: Thank you. I don't have access to a library at the moment. Please could you clarify a little how the $C^2$-condition on the boundary takes effect in the proof, if possible? Could it be replaced by the same condition, but only piecewise?

Conditions for membership of $H^2$


$\lfloor (25x-2)/4 \rfloor =(13x+4)/3$

Question: This problem is designated for those who have the basic knowledge of floor brackets
I know the answer will be 6. But tell me how.
Comment: Edit it is 25x.
Answer: $$\lfloor (25-2)/4 \rfloor =\lfloor (23)/4 \rfloor=\lfloor 5.75 \rfloor=5=(13x+4)/3$$
$$\Rightarrow (13x+4)/3=5$$
$$\Rightarrow (13x+4)=15$$
$$\Rightarrow (13x)=11$$
$$\Rightarrow x=\frac{11}{13}$$
It's not $6$!
Comment: Oops it 25x, on editors part
Comment: Mina, could you do it in the form of 25x?
Answer: It is clear that $\dfrac{13x + 4}{3}$ must be an integer so $x$ must have the form of $2 + 3k$.
Substitute this into the equation and now we must solve:
$$\left\lfloor\frac{48+75k}{4}\right\rfloor = \left\lfloor 12 + \frac{75k}{4}\right\rfloor = 12 + \left\lfloor \frac{75k}{4}\right\rfloor = 13k + 10$$
$$ \left\lfloor \frac{75k}{4}\right\rfloor = 13k - 2$$
Find an approximate solution by solving $\frac{75k}{4} = 13k - 2$ and reaching $k = -\frac{8}{23}$.
We will now look for solutions on intervals around this point.
$$ \left.\left\lfloor \frac{75k}{4}\right\rfloor\right|_{k = -8/23} = -7$$
Let $13k -2 = -8,$ $k = -\dfrac{6}{13}.$
Let $13k -2 = -7,$ $k = -\dfrac{5}{13}.$
Let $13k -2 = -6,$ $k = -\dfrac{4}{13}.$
Let $13k -2 = -5,$ $k = -\dfrac{3}{13}.$
From these possible values of $k$ we find that $x = \dfrac{8}{13}, \dfrac{11}{13}, \dfrac{14}{13}, \dfrac{17}{13}$.
Plugging in to the original equation to verify we find two extraneous solutions and that $\boxed{x = \dfrac{14}{13}, \dfrac{17}{13}}$.
This method will not work well in all cases. Because $\frac{75}{4} = 18.75 \not\approx 13$ I assumed that there are a maximum of four solutions. In a case where we must solve $ \lfloor \frac{75k}{4}\rfloor = 19k - 2$ there are five solutions. In $ \lfloor \frac{75k}{4}\rfloor = 18.75k - 2$ there will be infinitely many.
Answer: $\left[{p}\right]=\left[\frac{\mathrm{25}{x}−\mathrm{2}}{\mathrm{4}}\right]=\frac{\mathrm{13}{x}+\mathrm{4}}{\mathrm{3}}={n}\in{Z} \\ $
${x}=\frac{\mathrm{3}{n}−\mathrm{4}}{\mathrm{13}}\Rightarrow\frac{\mathrm{25}{x}−\mathrm{2}}{\mathrm{4}}=\frac{\mathrm{75}{n}−\mathrm{74}}{\mathrm{52}} \\ $
$\left\{{p}\right\}=\frac{\mathrm{75}{n}−\mathrm{74}}{\mathrm{52}}−{n}=\frac{\mathrm{23}{n}−\mathrm{74}}{\mathrm{52}} \\ $
${n}\in\left\{\mathrm{4},\mathrm{5}\right\}\Rightarrow{x}\in\left\{\frac{\mathrm{8}}{\mathrm{13}},\frac{\mathrm{11}}{\mathrm{13}}\right\} \\ $
Yes, it's not 6

$\lfloor (25x-2)/4 \rfloor =(13x+4)/3$


2 graphs sharing same x-axis

Question: I have recently started to use amchart for one of my project. Seeking help on a issue from anyone with experience from AMchart.
I have a dataset supposing to show two series on a smooth line graph by amchart. I managed to get it to show 2 series, but this two series are not sharing the same x-axis.
So any idea how can I make it to share the same x-axes.
I have attached the code below. In the picture, there is a line of json which is returned by the function load_dashboard_leads() in my code.

 <?PHP echo load_dashboard_leads();?>

Comment: Any chance of posting your actual data in `leadsGrowthData`?
Comment: in latest version this problem solved https://www.amcharts.com/kbase/display-multiple-graphs-in-the-same-stock-chart-panel/
Comment: one chance is test Graph1.id = "g1"; Graph2.id = "g2";
Answer: strongly suggest that you start you project from package in AmCharts website and download samples that prepare to work offline mode...
when you define title and id the diffrent name its worked
        var durationGraph1 = new AmCharts.AmGraph();
        durationGraph1.id = "g1";
        durationGraph1.title = "g1";
        durationGraph1.valueField = "value1";
        chart.addGraph(durationGraph1);

        var durationGraph2 = new AmCharts.AmGraph();
        durationGraph2.id = "g2";
            durationGraph2.title = "g2";
            durationGraph2.valueField = "value2";
            chart.addGraph(durationGraph2);

then use:
 chartData.push( {
                          date: d3,
                          date2: strdate ,
                          value1: distance,
                          value2: distance2
                        } );

in your function that generate numbers
if you want to have animation on it you must set:
.amcharts-graph-g2 {
  stroke-linejoin: round;
  stroke-linecap: round;
  stroke-dasharray: 500%;
  stroke-dasharray: 0 \0/;    /* fixes IE prob */
  stroke-dashoffset: 0 \0/;   /* fixes IE prob */
  -webkit-animation: am-draw 40s;
  animation: am-draw 40s;
}
            .amcharts-graph-g22 {
  stroke-linejoin: round;
  stroke-linecap: round;
  stroke-dasharray: 500%;
  stroke-dasharray: 0 \0/;    /* fixes IE prob */
  stroke-dashoffset: 0 \0/;   /* fixes IE prob */
  -webkit-animation: am-draw 40s;
  animation: am-draw 40s;
}

Answer: one way to solve this problem is : upgrade to last version of AMCharts ver 3
like
https://www.amcharts.com/demos/duration-on-value-axis/?theme=black

2 graphs sharing same x-axis


Javascript Return Value in graphql

Question: I have an apollo-server setup in my backed, I want to use a post request API inside one of my resolvers and then use the response from that API to return it to my client. but the problem am having is the return statement is running before the API response get returned. there is my code sample bellow.
module.exports = {
    Mutation: {
        checkFace: async () => {
            console.log("Checking.....");

            let confidence;

            var parameters = {
              image_url1: "link to image 1",

              image_url2: "link to image 2",
            };

            facepp.post("/compare", parameters, function (err, res) {
                if (!err) {
                    confidence = res.confidence;
                } else {
                    console.log(err);
                }
            });

            return confidence
        },
    },
};

Answer: That's because the faceapp.post is probably running asynchronously. Your checkFace function is correctly used as async that's fine, but inside where you call the POST you should await the response and then return it
confidence = await res.confidence;

Also when using the function make sure you await for it to finish, so call it with
let someResponse = await Mutation.checkFace();
console.log(someResponse);

or
Mutation.checkFace().then(response => {
    console.log(response);
});

Whichever you prefer depending on your situation.
https://nodejs.dev/learn/modern-asynchronous-javascript-with-async-and-await
Comment: Thanks for your quick answer, but the problem is I cant call the mutation function with await because its being called in the graphql schema, and If I decided to remove the return statement outside the faceapp POST request, then I cant get the return value sent to the client.
Comment: `facepp` is some freely available library or something custom?
Comment: Its its a node package for face++
Comment: @Johndev247 couldn't find documentation for it.. I'd start there and check how `facepp.post` should work and how it should be called in order to return data. I presume it's asynchronous and that's why you need to await the data.

Javascript Return Value in graphql


Having trouble using topicMetadataRequest api to use for momitoring topic partictions in Kafka

Question: We are setting up kafka (v0.8) with zookeeper for our log processing.  I am trying to use APIs defined at https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-TheAPIs  specifically, trying to use Metadata API to get info on all topics and partitions.  The doc says the Metadata request can be directed to any broker in the cluster.  I am not clear on how to direct the request (or how to identify one of the brokers that the request can be directed to.). The code I am writing is in Java and is for setting up a comprehensive monitoring system in place.
Does anyone have a sample code for that by any chance pls?
Can anyone provide a sample code for using any of those APIs that are for monitoring and are NOT related to consumers or producers?
I have seen code in Scala, but I don't know Scala and I have to write in Java for our shop.
Would really appreciate anything that might help.
Comment: I remember seeing the same question a couple of days ago. Have you by any chance removed a previous question and asked a new one?
Comment: No, I have not.  I don't see any other question talking about similar issue either.  Hope someone can help with using Java and querying Kafka broker for info on its topics and partitions.
Comment: sorry, then most probably it was my mistake. I will remove my comments.
Answer: the place where you can set the broker is with the Consumer.
You can use Kafka's SimpleConsumer Example on their documentation.
Here's some sample code
<code>// some sample values
String CLIENT_NAME = "_YOUR_CLIENT_NAME";
int DEFAULT_FETCH_SIZE = 300000; // 0.3 MB, default from kafka
int BUFFER_SIZE = 64 * 1024;
int CONSUMER_TIMEOUT = 5000;

SimpleConsumer consumer = new SimpleConsumer(YOUR_HOST, YOUR_PORT, CONSUMER_TIMEOUT, BUFFER_SIZE, CLIENT_NAME);

List<String> topics = Collections.singletonList("myTopic");
TopicMetadataRequest req = new TopicMetadataRequest(topics);
kafka.javaapi.TopicMetadataResponse response = consumer.send(req);
</code>
Can you elaborate what kind of information you are looking for?
The information could be in TopicMetadata, PartitionMetadata, etc.


Issues using sumifs() in VBA

Question: I'm trying to basically translate a formula from excel into VBA. I'm using the SUMIFS() command and I have it referring to columns in an already established table. This is what I have so far but I keep getting an object error.
Cells(2, 14).Value = 60 * Application.WorksheetFunction.SumIfs([Hours],[Operators], [@Operators], [Forging], [@Forging], [Operation], [@Operation], [Job No], [@[Job No]], [Time], ">" & [Time] - Time(1, 0, 0), [Time], "<" & [Time] + Time(1, 0, 0), [Workcenter], [@Workcenter])

I'm guessing that this isn't how you use SUMIFS() so how do you modify this so that it can function as it does in excel.
Any help is appreciated!
Answer: It's difficult to exploit the power of the structured formula from VBA. Since you have a tested and working formula, you can let the cell evaluate it as is and then fix the value. for example:
With sheet1.Cells(2, 14)
  .Formula = "=SUMIFS([Hours],[Operators], [@Operators], [Forging], [@Forging], [Operation], [@Operation], [Job No], [@[Job No]], [Time], "">"" & [Time] - Time(1, 0, 0), [Time], ""<"" & [Time] + Time(1, 0, 0), [Workcenter], [@Workcenter])"
  .Value = .Value * 60
End with

only thing to be careful about here was: double-up any double-quotes inside the initial formula.
Comment: I ran this and got a type mismatch error on the .formula line

Issues using sumifs() in VBA


Access denied to all users after migrating site to new server

Question: Please don't consider this as a duplicate post. I have tried all the solutions that worked for others, but still struggling to fix the problem (all users including admin taken to 403 page). This is a Windows server running Drupal 7.
Things I have tried -

No base_url value given
No cookie_domain value given
Session table truncated
Cache tables truncated
No file permission differences
Tried Reset password email but the link takes to 403 page
Deleted browser cache

Please let me know if anyone has experience with a similar issue or what else I could try.
This is what I can see in watchdog table.

Thanks
Answer: I finally figured it out!
We are enforcing secure flag on our cookie and therefore had to disable the corresponding rewrite rule from IIS, as we didn't have a SSL certificate in new server.
Answer: Check the user table in the DB. sometimes when importing DBs it starts auto-numbering from 1, so you don't have a user with the id of 0, which Drupal uses for its anonymous user.


Matrix minimization problem

Question: I have the following minimization problem:
$$\min_{||w||=1}\Big(w^{T}X^{T}Xw\cdot{}w^{T}Aw-2w^{T}X^{T}XAw\Big)$$
where $w$ is a $n\!\times\!1$ vector, $X$ is a $n\!\times\!n$ symmetric matrix, and $A$ is a $n\!\times\!n$ diagonal matrix. Is there a closed-form solution? If not, what kinds of iterative methods should I use to solve this?
Answer: $
\def\a{\alpha}\def\b{\beta}
\def\g{\gamma}\def\t{\theta}
\def\l{\lambda}\def\s{\sigma}
\def\L{\ell} \def\LP#1{\L^{#1}}
\def\bR#1{\Big(#1\Big)}
\def\BR#1{\Big(#1\Big)}
\def\LR#1{\left(#1\right)}
\def\op#1{\operatorname{#1}}
\def\trace#1{\op{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\o{{\tt1}}\def\p{\partial}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\fracLR#1#2{\LR{\frac{#1}{#2}}}
$Consider an unconstrained vector $u$ and how perturbations
affects its length
$$\eqalign{
\LP2 &= \|u\|^2 = u^Tu \qiq \L\:d\L = u^Tdu  \\
}$$
By constructing $w$ from $u$
$$\eqalign{
w &= \LP{-1} u \qiq w^Tw = \LP{-2}\LR{u^Tu} = \o \\
dw &= \LP{-1}du \;-\; u \LP{-2}d\L \\
 &= \LP{-1}du \;-\; u \LP{-2}\LR{\LP{-1}u^Tdu} \\
 &= \LP{-1}\LR{I - ww^T}du \\
}$$
the constraint can be eliminated, leaving a fully unconstrained problem.
For typing convenience, define the matrix variables
$$\eqalign{
B &= X^TX \\
C &= BA \\
S &= \fracLR{C+C^T}2 \qiq w^TSw = w^TCw \\
M &= \a B-AB \;+\; \b A - BA \\
  &= (\a I-A)B \;+\; (\b I-B) A \\
}$$
and the scalar variables
$$\eqalign{
\a &= w^TAw &\qiq d\a = 2Aw:dw \\
\b &= w^TBw &\qiq d\b = 2Bw:dw \\
\s &= w^TSw &\qiq d\s = 2Sw:dw \\
}$$
Rewrite the objective function and calculate its gradient
$$\eqalign{
\phi &= \a\b - 2\s \\
d\phi &= \a\:d\b + \b\:d\a - 2\,d\s \\
  &= \LR{2\a B + 2\b A - 4S}w : dw \\
  &= 2\LR{\a B + \b A - AB - BA}w : dw \\
  &= 2Mw : dw \\
  &= 2Mw : \LP{-1}\LR{I - ww^T}du \\
  &= 2\LP{-1}\LR{I - ww^T}Mw : du \\
\grad{\phi}{u} &= 2\LP{-1}\LR{I - ww^T}Mw \\
}$$
Use this gradient expression in any Gradient Descent
algorithm to numerically calculate the optimal $u$ vector,
after which the corresponding $w$ vector can be obtained by normalization.
Alternatively, one could set the gradient to zero to produce
$$\eqalign{
Mw = w\LR{w^TMw} = \l w \\
}$$
which looks like an eigenvalue problem,
except that $(\l,\,M)$ are both functions of $w$.
Nonetheless, a modified Power Iteration is another possible solution algorithm.

In several steps above, a colon is used to denote the Frobenius product
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{A^TB} \\
A:A &= \|A\|^2_F \\
}$$
This is also called the double-dot or double contraction product.
When applied to vectors $(n=\o)$ it reduces to the standard dot product.
The properties of the underlying trace function allow the terms in a
Frobenius product to be rearranged in many useful ways, e.g.
$$\eqalign{
A:B &= B:A \\
A:B &= A^T:B^T \\
C:\LR{AB} &= \LR{CB^T}:A &= \LR{A^TC}:B \\
}$$

Matrix minimization problem


deploying a node.js on a new domain

Question: I have a server that runs different websites on different ports. All of them (but one) are Apache servers and thanks to webmin, I managed to have, for instance, example.com point to 184.108.40.206:80 and example.fr to 220.127.116.11:8000, somehow automatically
I am now running a nodejs server on the same machine, so the 80, 8000, and many other ports are already taken. My nodejs listens on 8008. I have another domain name, say example.org, and I want it to point to my nodejs website, but I simply don't know how to do that! I have updated the DNS and everything is pointing to 184.108.40.206 (my server's IP). I want to avoid using an ugly example.org:8008/ for everything on this node server. How can I make it point implicitly to the 8008 port?? I must add that I cannot afford to take down the apache servers ;)
Comment: You want DNS to point to the 8008 not 80... Am I understanding this right? If so, no-can-do. DNS can't do that. You can probably do a redirect in Apache to the :8008 site - so hitting one domain will go to this odd port server. Google "redirect Apache domain odd port"
Answer: DNS only provides name to ip address mapping. It cannot handle ports. What you can do instead is to set up a proxy server listening on port 80. The proxy server can then return data based on the host header.
Your best option is to just redirect the request from Apache. Otherwise you can use a reverse proxy like Nginx. Also, you can write a lightweight proxy in node... check out this page

deploying a node.js on a new domain


Incremental Gaussian Process Regression

Question: I want to implement an incremental gaussian process regression using a sliding window over the data points which arrives one by one through a stream.
Let $d$ denote the dimensionality of the input space. So, every data point $x_i$ has $d$ number of elements.
Let $n$ be the size of the sliding window.
In order to make predictions, I need to compute the inverse of the gram matrix $K$, where $K_{ij} = k(x_i, x_j)$ and k is the squared exponential kernel.
In order to avoid K getting bigger with every new data point, I thought I could remove the oldest data point before adding new points and this way I prevent the the gram from growing. For example, let $K = \phi(X)^{T}\Sigma\phi(X)$ where $\Sigma$ is the covariance of the weights and $\phi$ is the implicit mapping function implied by the squared exponential kernel.
Now let $X=[x_{t-n+1}|x_{t-n+2}|...|x_{t}$] and $X_{new}=[x_{t-n+2}|...|x_{t}|x_{t+1}]$ where $x$'s are $d$ by $1$ column matrices.
I need an effective way to find the $K_{new}^{-1}$ potentially using $K$. This doesn't look like the inverse of a rank-1 updated matrix problem that can be efficiently dealt with Sherman-Morrison formula.
Answer: There have been several recursive algorithms for doing this. You should take a look at kernel recursive least squares (KRLS) algorithm, and related online GP algorithms.

Van Vaerenbergh, S., Santamaria, I., Liu, W., and Principe, J. C. (2010). Fixed-budget kernel recursive least-squares. In Acoustics Speech and Signal Processing (ICASSP), 2010 IEEE International Conference on, pages 1882-1885. IEEE.
Lazaro-Gredilla, M., Van Vaerenbergh, S., and Santamaria, I. (2011). A Bayesian approach to tracking with kernel recursive least-squares. In Machine Learning for Signal Processing (MLSP), 2011 IEEE International Workshop on, pages 1-6. IEEE.
Perez-Cruz, F., Van Vaerenbergh, S., Murillo-Fuentes, J. J., Lazaro-Gredilla, M., and Santamaria, I. (2013). Gaussian processes for nonlinear signal processing: An overview of recent advances. IEEE Signal Processing Magazine, 30(4):40-50.
Answer: Stepwise estimation of GP models is well studied in literature.
The underlying idea is instead of conditioning on all new observations you want to predict, condition on the one-step ahead point and do this repeatedly. This becomes somehow close to kalman filtering.
Comment: This answer would be improved if it cited a book, article, or other scholarly publication.

Incremental Gaussian Process Regression


Spring in Action III - 1 chapter 1 example and app is not working

Question: I just started learning Spring with Spring in action 3rd edition and I already have a problem with first chapter - example about a knight. Everything was ok, but when I wrote the code in beans.xml with aop my application stopped working, here's a source code of beans.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation=
   "http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop.xsd">

<bean id="knight" class="com.mol.spring.action.classes.BraveKnight">
    <constructor-arg ref="dragonquest" />
</bean>

<bean id="dragonquest" class="com.mol.spring.action.classes.DragonSlayingQuest" />
<bean id="damselquest" class="com.mol.spring.action.classes.DamselResquingQuest" />
<bean id="minstrel" class="com.mol.spring.action.classes.Minstrel" />

<aop:config>
    <aop:aspect ref="minstrel">
        <aop:pointcut id="embark" expression="execution(* *.embarkOnQuest(..))" />
        <aop:before method="singBeforeQuest" pointcut-ref="embark" />
    </aop:aspect>
</aop:config>
</beans>

Everything worked fine, until I wrote the <aop:config> and app works if I comment the <aop:before /> tag. If other classes are needed, I'll include them.
Error message:
kwi 03, 2014 1:29:45 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3abc8690: startup date [Thu Apr 03 13:29:45 CEST 2014]; root of context hierarchy
kwi 03, 2014 1:29:45 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
kwi 03, 2014 1:29:46 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14b05b39: defining beans [knight,dragonquest,damselquest,minstrel,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,embark]; root of factory hierarchy
kwi 03, 2014 1:29:46 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@14b05b39: defining beans [knight,dragonquest,damselquest,minstrel,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,embark]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'knight' defined in class path resource [beans.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:454)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.mol.spring.action.BraveKnightTest.main(BraveKnightTest.java:12)

I cut out everything that's below, I don't think it matters.
Comment: and what is the error?
Answer: I think you are missing the aspectj JARs in your classpath.
Try adding this to your POM.XML
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjrt</artifactId>
    <version>1.6.12</version>
</dependency>
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.6.12</version>
</dependency>

Just check if the versions are compatible.
Btw if you are not using Maven try adding the respective JARs.


Vídeo em HTML5 sem menu de contexto

Question: Como desativar menu de contexto do botão da direita do mouse em vídeos, para não aparecer o menuzinho do vídeo?
<code>$('#nome').contextmenu( function() {
    return false;
});
</code>
O código acima, mas não funciona no internet explorer, o vídeo fica com fonte inválida.
Answer: Tente o código seguinte:
<code>$('body').on('contextmenu', '#nome', function(e){ return false; });
</code>

Fonte original: https://stackoverflow.com/a/10864321/194717
Comment: Haha, excelente a resposta no SO ser do Zuul :)
Comment: Conte se funcionou ou não funcionou.
Comment: Tá funcionando no chrome e no firefox, mas no ie não, já limpei os cookies e tudo e nada...fonte inválida..
Comment: há, funcionou sim, tava bugado...

Vídeo em HTML5 sem menu de contexto


Counting and Ordering of Numbers

Question: Are there differences between 'counting' and 'ordering'? As such, the whole of rational number is countable, or they order-able too? In what cases counting and ordering are same or not?
Answer: "Counting" means finding the cardinality; "ordering" means establishing an order. Certainly, there is a difference: for a simple example, while there is only one possible answer to "How many elements does the set $\{x,y\}$, with $x\neq y$, have?" (namely, "2"), there are at least two different answers to "What is an ordering of the set $\{x,y\}$, with $x\neq y$?" ( either "$x$ smaller than $y$" or "$y$ smaller than $x$"; if you admit partial orders, then there is even a third possible answer, "$x$ and $y$ incomparable").
Now, the rational numbers are already ordered, in their "usual ordering" as a subset of the reals. But that is not what you really mean, I think. Rather, you want to think about a specific "counting" of the rationals (that is, a bijection to the nonnegative integers) as providing a way to "order" the rationals (or any other set that is "countable"; i.e., bijectable with $\mathbb{N}$).
Yes: if you have a set $X$, and you know that $X$ is countable (there exists a bijection $f\colon X\to\mathbb{N}$), then you can use the bijection to endow $X$ with a "total ordering" (in fact, a well ordering): first, pick a bijection $f\colon X\to\mathbb{N}$; then, given $x$ and $y$ in $X$, define $x\preceq y$ if and only if $f(x)\leq f(y)$ (the latter being the "usual" ordering of the natural numbers). But this ordering is "non-canonical": if you choose a different bijection $f$ (and there are many, many bijections if there is at least one) you get a different order.
Comment: There is an underknown bijection between the naturals and the non-negative rationals using the binary representation on one hand  and the Stern-Brocot tree of mediants (of rationals) on the other. See Graham,Knuth, Patashnik, Concrete Mathematics or Wilf and Calkin, Recounting the Rationals.
Comment: Guru, you have well-ordered them by omega^2, which is a countable ordinal.
Comment: Guru, it is an infinite succession of infinite lists.  So we have omega omegas and that's omega^2.
Comment: @Dan, @Guru: To be a bit more precise: it is a countable list of countable lists, each list ordered as the naturals, the list of lists ordered as the naturals.
Comment: I had to loan you some $ ;-)
Comment: Wonderful answer. I will wait to see other answers as well. The reason for my question is, countability of rational numbers, I am confusing the the method to show rational numbers are countable with a kind of ordering. What are we doing when we write 1, 1/2, 1/3, 1/4.... 2/1, 2/2, 2/3... ?
Comment: @Dan, if you permit, may I ask, how omega^2?
Comment: @Asaf: Thank you: my connection flaked on me and I had to wait until my wireless modem reset itself.
Comment: @Arturo: Sure, what is a $ between friends? :-)
Comment: I guess, I am getting it. Thanks Dan. Thanks Arturo!
Comment: @Guru: Of course, what you describe is not *really* an ordering of the rationals: your list only contains positive naturals, and moreover, it contains the same rational several times. One would have to use this list in order to define a *surjection* from $\mathbb{N}$ to the positive rationals, and then use this to define a bijection and from there an ordering.
Answer: All infinite countable sets have cardinality $\aleph_0$ (which "counts" them) and can be put into one-to-one correspondence with any countable infinite ordinal, the smallest being $\omega$ (which "orders" them), so there is no difference in this case.  If you assume the Axiom of Choice, a more general property is true for all sets: the
Well-ordering principle.  The rational numbers are countable and can be well-ordered by $\omega$: imagine laying them out in a table (according to each numerator and denominator), and then zig-zagging diagonally starting at the corner.
Cantor's diagonal argument explains why the reals are uncountable.  The Well-ordering principle says we can well-order the reals by some uncountable ordinal, but it doesn't say which one.  If you assume the Continuum Hypothesis, then we can use the first uncountable ordinal to order them.  But even with all of these assumptions, it is impossible to visualize the correspondence in the same way as the case of countable ordinals.  Some countable ordinals can be difficult to visualize too, such as  $\epsilon_0$.
Comment: +1. thanks for answer. I got confused with orderable and countable. For the fact, can you explain how real numbers are orderable / uncountable? (not in comments please, in above answer)
Comment: Most ordinals are very complicated to imagine, in the case of $\epsilon_0$ or well-ordering of the reals it all the same after you get used to the idea of well orders. Also there are (strictly) weaker principles such that "every set can be linearly ordered" and "every set can be densely linearly ordered". These are orderings as well, in spite not necessarily being well-founded. Not to mention partial orders.

Counting and Ordering of Numbers


Help with confidence intervals

Question: I am trying to understand confidence intervals better.
If two different labs ran the same experiment, with the same number of samples and both got the same mean values but their 95% CI differed.
Lab 1 got a mean value of 1.6 & 95% CI: 1.0 to 2.2
Lab 2 got a mean value of 1.6 & 95% CI: 1.5 to 1.7
What could you actually deduce from this?
If you took both results separately, would you be any more confident that the true mean was 1.6 from the results from lab 2? I feel like I am not really understanding what a CI is and misinterpreting it.
Comment: @mkt I suspect you intended to write the opposite of some of the things you did.  First, it is clear that the variance was much *smaller* in the Lab 2 sample than in the Lab 1 sample. Second, your reference to "probability density" sounds like you are taking these to be Bayesian *credible intervals* rather than confidence intervals, because it isn't clear to what "probability density" actually refers.  As such, your comment might confuse the issue more than clarify it.
Comment: This is a problematic question because although you *can* deduce something about the mean by combining these CIs, something else unrelated to CIs is going on.  Because one interval is so much narrower than the other, you have produced significant evidence that the *variances* observed by the labs differ.  That would make one hesitate to interpret the CIs (or to combine them) until the reason for this difference in variances is better understood.
Comment: @whuber Fair points, that was sloppy writing. I am deleting my previous comment.
Comment: As whuber said, in your case it means that there is a significant difference in variance between the samples. A rule of the thumb is that, when the C.I. of the samples do not overlap, then there is a significant difference between the sample statistics (not your case). Another one is that, when a C.I. contains 0 in its range (i.e. one of the intervals is negative), then you simply don't have good enough data to estimate an interval at that confidence level.
Comment: @Digio Please be careful, lest you confuse readers even more.  Although it's correct that non-overlap of CIs often implies significance, the inverse is not true.  See https://stats.stackexchange.com/questions/18215. Moreover, a CI has nothing whatsoever to do with containing zeros or not: you must be thinking of using a CI in a particular kind of null hypothesis test, one that is not germane to this discussion. Your characterization of a CI is [disputed by almost everyone;](https://stats.stackexchange.com/questions/26450) in particular, (1) is misleading and (2) is strikingly false.
Comment: @whuber you must have misunderstood my comment on the [inclusion of zero](http://onlinestatbook.com/2/logic_of_hypothesis_testing/sign_conf.html) in a CI because what I was trying to explain is more or less [common knowledge](https://stats.stackexchange.com/questions/120949/why-does-a-confidence-interval-including-0-mean-the-difference-is-not-significan). Also, I said exactly the same thing as you did: non-overlapping intervals _imply_ significant difference between two sample statistics - I'm not sure what you mean by "the inverse is not true" but I didn't mention anything like that.
Comment: @whuber, My first interpretation of CI is formally wrong as the population mean is a constant and not a random variable, nonetheless, it is the standard interpretation in the applications of CI, e.g. in regression analysis it is the ["estimate of an interval in which future observations will fall, with a certain probability"](https://en.wikipedia.org/wiki/Prediction_interval).
Comment: My second interpretation is actually a [textbook definition](https://stattrek.com/estimation/confidence-interval.aspx) and perhaps one of the strictest since "confidence" is not interpreted as "probability". As described [here](http://onlinelibrary.wiley.com/doi/10.1002/asi.23744/abstract): _"The confidence interval describes the level of uncertainty of a sampling method. The statistic and the margin of error define an interval estimate that describes the precision of the method"_.
Comment: The above definition (2) can be extended using the property of [long run relative frequency](http://www.stats.org.uk/probability/frequency.html) and, under the assumption that our sampling method is unbiased, we can derive interpretation (1), where "confidence" is viewed as a probability and the sample statistic as the population parameter (I can cite [sources](https://www.amazon.co.uk/Statistical-Methods-Epidemiologic-Research-Merrill/dp/1284050203) for this reasoning too). If you still find my comments misleading then I will remove them.
Comment: Your statement beginning "if you repeat..." simply is untrue.  Repetition of an experiment does not ensure that an estimate will fall within a confidence interval.  The estimate will vary according to its sampling distribution and the confidence interval is uncertain.  What do you think will happen if that CI happens to be one of the 5% that does not cover the true parameter?  When the experiment is repeated, then most of the time the estimate will *not* lie within that particular CI.
Comment: The repetition of an experiment an _infinite_ number of times is a theoretical condition required to interpret a frequency as a probability, but I didn't say that it affects the frequency. From a frequency of infinite repetitions you can deduce the probability of having the population parameter inside the CI of a single experiment. A very similar explanation is provided [here](https://stackoverflow.com/questions/42799002/how-to-interpret-the-upper-lower-bound-of-a-datapoint-with-confidence-intervals). I would change my wording to avoid all confusion but since I can't edit I will just remove.
Comment: [Edited] Interpretations: (1) A confidence interval is associated to a population statistic, i.e. it is the range of values in which the population statistic lies, within a certain probability (confidence); (2) A confidence interval is associated to a sampling method, i.e. if you repeat the same sampling process for an infinite number of times, the fraction of intervals that contain the true population parameter will be equal to (e.g.) 95%.
Answer: Confidence intervals are tricky things, but your intuition is right. The fact that lab 2 gets a smaller interval means that they are more confident that the true mean is close to 1.6. The tricky part is what confidence actually means in this case.
What it does NOT mean is that there is a 95% probability that the true mean falls within this interval. What it does mean is that 95% of the intervals constructed in this way will contain the true mean. Whether or not your interval is one of those 95% or one of the unlucky few 5% one cannot say.
If a confidence interval gets smaller it means that it is "harder" to hit the true mean with 95% of these intervals, therefore if you still hit the mean in 95% of the cases with a smaller interval you have a more precise measurement. The usual way to achieve this is by increasing your sample size.
I personally find this video from Dr. Nic explains it rather well.
Comment: +1. Though I would say that both interpretations are generally acceptable depending on the branch of statistics.

Help with confidence intervals


Desabilitar documentação automática web api c#

Question: Olá, estou desenvolvendo uma Api em c#.
Existe uma documentação que ele gera automática conforme imagem a baixo, só que quando eu for subir a API em produção gostaria de desabilitar essa documentação, pois qualquer um que acessar o link raiz da minha api conseguirá ver todas minhas chamadas.
Como consigo desabilitar essa função?
Comment: Que documentação? Vc diz os links "learn more", "getting started", "get more libraries" e "web hosting"?
Answer: Sei que tem um flag que desativa a documentação gerada em XML, espero que ajude.


I need to spam the "C" Button until the Game Restarts

Question: Hello i need to programm a Game with pygame for school. I nearly finish the Game but when i want to Press the "C" button in the Gameover loop then nothing happends and the game will not restart.
unti i spam the "C" Button. I dont think that there is a problem with the detection of pressing the button because i made a print command thatalways prints something when i press the "C" Button and it always print something out.
I hope you can help me with the Problem :)
from turtle import pos
import pygame
import time
from pygame.locals import *
import random
pygame.init()

dis_width = 600
dis_height = 400
pos_x = 303
pos_y = 370
x_change = 0
y_change = 0
enemie_pos_x = random.randint(180, 420)
enemie_pos_y = 30

clock = pygame.time.Clock()
screen=pygame.display.set_mode((dis_width, dis_height))
font_style = pygame.font.SysFont("bahnschrift", 25)
time_font = pygame.font.SysFont("bahnschrift", 25)

running=True
obj = False
obj2 = False
enemie = False
game_over = False
crash = True

start = time.time() + 0.1
tolleranz = 40
speed = 5
timer = 5
score = 0
displayscore = 0
highscore = 0
ROT = (255, 0, 0)
BLACK = (0, 0, 0)

pygame.display.update()

def stopwatch(time):
    value = time_font.render("Time: " + str(time), True, ROT)
    screen.blit(value, [0, 0])
    value2 = time_font.render("Score: " + str(score), True, ROT)
    screen.blit(value2, [0, 30])
    value6 = time_font.render("HighScore: " + str(highscore), True, ROT)
    screen.blit(value6, [0, 60])

def enemies():
    counter = 1
    global enemie_pos_x, enemie_pos_y, speed, aTimeRound, timer, displayscore, highscore
    enemie_pos_y += speed
    if aTimeRound > timer:

        speed += 5
        timer += 5
    if enemie_pos_y > 430:
        enemie_pos_y = 0
        enemie_pos_x = random.randint(180, 420)
        global score
        score += 1
        if highscore <= score:
            if highscore != score:

                highscore += 1
        displayscore = score

def gameoverF():
    global score, start, speed, timer, game_over, displayscore, highscore
    screen.fill(BLACK)
    value3 = time_font.render("GAMEOVER", True, ROT)
    screen.blit(value3, [230, 100])
    value6 = time_font.render("Score:" + str(displayscore), True, ROT)
    screen.blit(value6,[230, 150])
    value4 = time_font.render("Highscore: " + str(highscore), True, ROT)
    screen.blit(value4,[225, 200])
    value5 = time_font.render("Press 'C' to play again OR Press 'Q' to Quit", True, ROT)
    screen.blit(value5,[70,250])
    score = 0
    start = time.time()
    speed = 5
    timer = 5
    pygame.display.update()

while running:
    while game_over == True:

        for event in pygame.event.get():        # Bei jeden GameLoop die Liste an Events abfragen
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
                quit()
            if event.type == pygame.KEYDOWN:    # Prüfen, ob der Eventtyp ein Tastendruck ist
                if event.key == ord("c"):  # Prüfen, ob die Cursor-Links-Taste gedrückt wurde...
                    game_over = False
                    speed = 5
                    timer = 5
                    score = 0

                    print("GEDRÜCKT!!!!!!!")
                if event.key == ord("q"):
                    pygame.quit()

        gameoverF()

    #Messung der Zeit
    aTime = time.time()-start
    aTimeRound = round(time.time()-start,1)
    #print(aTime)

    #Malen der Steuer Kugel und der Linien
    pos_x += x_change
    screen.fill(BLACK)
    pygame.draw.line(screen, ROT, (150,0),(150,400), 10)
    pygame.draw.line(screen, ROT, (450,0),(450,400), 10)
    pygame.draw.circle(screen, [255,255,255],(pos_x,pos_y), 25)

    stopwatch(aTimeRound)
    enemies()

    pygame.draw.circle(screen, [255,255,255],(enemie_pos_x,enemie_pos_y), 25)

    #print( enemie_pos_x - pos_x)
    check_x = pos_x - enemie_pos_x
    if check_x < 0:
        check_x = check_x * -1
    print(check_x)

    if check_x < tolleranz and pos_y - enemie_pos_y < tolleranz:

        game_over = True

    clock.tick(30)
    if pos_x  <= 192:
        pos_x = 192
    if pos_x  >= 410:
        pos_x = 410
    for event in pygame.event.get():        # Bei jeden GameLoop die Liste an Events abfragen
        if event.type == pygame.QUIT:
            running = False
            pygame.quit()
            quit()
        if event.type == pygame.KEYDOWN:    # Prüfen, ob der Eventtyp ein Tastendruck ist
            if event.key == pygame.K_LEFT or event.key == ord("a"):  # Prüfen, ob die Cursor-Links-Taste gedrückt wurde...
                x_change = -10
                y_change = 0                # Aktion bei Cursor-Links

            if event.key == pygame.K_RIGHT or event.key == ord("d"):
                x_change = 10
                y_change = 0

    pygame.display.update()

gameoverF()

Answer: Played your game got highscore of 22 oh I mean I read the code and and I debugged it
Well actually playing was the debugging haha. The problem is that after you press C game restarts as it should but the enemy which hit you is not removed and it instantly kills you again and moves tiny bit lower. By spamming C you move it out of screen and game continues
Simple fix to reset enemy pose when C is pressed
if event.key == ord("c"):
    enemie_pos_y = 30 # Reset enemy pose

Keep up the good work!
Comment: `if event.key == pygame.K_c`  might be more intuitive.


Iteratively generating subplots in matplotlib by row and column - only final axes plotting

Question: I am writing code to plot cross correlations of every time-series in my data against all others, with two for-loops to index the row and column position respectively (column loop nested within the row loop).
Currently only the final axes (i.e. bottom right corner) of the figure is displaying any data, and each iteration of the loop appears to be plotting on this axes. I am wondering if I have made any obvious mistakes with the order of commands in the nested for loops, or if I am misinterpreting the input arguments to matplotlib functions like subplots....
The code is as below:
fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)

for n in range(data_num):  #row index
    for p in range(data_num):  # column index
        x = data_df.iloc[:,n]  #get data for ROI according to row index
        print(x.head())
        x = x.values
        y = data_df.iloc[:,p]  #get data for ROI according to column index
        print(y.head())
        y = y.values
        axes[n,p] = plt.xcorr(x,y,normed=True)     #axes [row,column] = cross correlation plot of above data
        print(f'plotting at index [ {n} , {p}]')

Answer: You can use the flatten() command, e.g,:
fig, ax = plt.subplots(3, 4, figsize = (15, 20))

for m in np.arange(0, 12):
    ax.flatten()[m].plot(stuff)

Answer: It's a, perhaps unfortunate, way that pyplot and matplotlib works: you have to create the plots on the respective axes, not assign the result from a pyplot.xcorr call to an axes. Thus: axis[n,p].xcorr(...). So the interface is suddenly somewhat more object-oriented than the usual direct pyplot calls.
All the plots ends up in just the last figure, because you are calling
plt.xcorr(x,y,normed=True)

It doesn't matter if you then assign the return value to the axes array elements, which you shouldn't, as that destroys the original axes array.
plt.xcorr will then plot all the data in the same plot on top of each other, because pyplot generally acts on the currently active axes, which is the last one created via plt.subplots().

That's for an explanation. Here's an example solution (with random data and a simple scatter plot):
import numpy as np
import matplotlib.pyplot as plt

data_num = 3

x = np.random.uniform(1, 10, size=(data_num, data_num, 20))
y = np.random.uniform(5, 20, size=(data_num, data_num, 20))

fig, axes = plt.subplots(nrows=data_num, ncols=data_num, sharex=True, sharey=True)
for n in range(data_num):  #row index
    for p in range(data_num):  # column index
        # Call `scatter` or any plot function on the
        # respective `axes` object itself
        axes[n,p].scatter(x[n,p], y[n,p])
        print(f'plotting at index [ {n} , {p}]')
plt.savefig('figure.png')

and figure.png looks like (sorry, no colour or symbol variation, just bare bones scatter plots):
Comment: @user140259 Use `plt.subplots(..., squeeze=False)` to get rid of the error.
Comment: Brilliant, it was literally a case of changing that one line from 'axes[n,p] = plt.xcorr .......'   to 'axes[n,p].xcorr(....'

Really helpful, thank you!
Comment: @ImportanceOfBeingErnest Thanks for the example. You would know how it could work if nrows or ncols was equal to 1 since it gives error in that case (IndexError: too many indices for array). Thanks a lot in advance!


PHP: simple math function returns null instead of integer

Question: I got a function:
- which should add to number $x random number from -25 to 25
 - if result is higher than 255 or lower than 0, the function should be called again to generate acceptable result.
What I got is:
function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
    {
        changeParam($base_val); //is it correct?
    }
    else
    {
        $new_val = $base_val + $plus;
        return $new_val;
    }

}

Why this:
$x = changeParam(255);
var_dump($x);

does give me null sometimes?
I've tried to check it, but I didn't find the reason:
function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
    {
        changeParam($base_val);
    }
    else
    {
        $new_val = $base_val + $plus;
        echo 'Is there a problem? ' . $new_val;   // this line shows correct new_val
        var_dump($new_val);                       // correct, for instance: 'int 250'
        return $new_val;                           // but in the same time, the result = 'null'
    }

}

Answer: If you really want to go with recursion, you have to add a return before the call to changeParam($base_val);. So it would look like this:
function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
    {
        return changeParam($base_val); // CHANGED HERE
    }
    else
    {
        $new_val = $base_val + $plus;
        return $new_val;
    }

}

However, recursion in such a case can potentially be bad. (If the search for the random variable happens to return "bad" values too many times, you might run into a stack overflow exception. The probability of this happening in this specific case is pretty low - but you should always consider such a case.)
Instead, you should go with an iterative approach, for example like this:
function changeParam($base_val)
{
    $plus = mt_rand(-25, 25);

    while (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
    {
        $plus = mt_rand(-25, 25);
    }

    $new_val = $base_val + $plus;
    return $new_val;
}

Comment: Thank you @Hauke. I didn't know that return is required before calling function again. Since 'while' is much cleaner solution for this - I will use it. Thanks again!
Answer: function changeParam($base_val)
{

    $plus = mt_rand(-25, 25);

    if (($base_val + $plus) > 255 || ($base_val + $plus) < 0)
    {
        $new_val = changeParam($base_val);
    }
    else
    {
        $new_val = $base_val + $plus;
    }

    // return here
    return $new_val;

}


Propogation of error in a matrix inversion

Question: I'm trying to find the deterministic error bounds for some parameters calculated through distance geometry.
The equation can be simplified to the following form:
$ \left[\begin{matrix} x_1 \\ x_2 \\ x_3 \\ x_4 \end{matrix}\right] = D^{-1}\left[\begin{matrix} 0\\0\\0\\1\end{matrix}\right]$
Where $D^{-1}$ is $4 \times 4$ matrix. $D$ contains some distances indirectly obtained from another set of distances. I am able to calculate an error for each element of $D$ and I would like to figure out how those errors affect the solution. The uncertainty of $x_4$ is of particular interest to me.
Some online searching lead me to the concept of a matrix condition number which would seem ideal for such purposes. However, the vector on the right hand side ($\left[\begin{matrix} 0 & 0 & 0 & 1\end{matrix}\right]^{T}$) is exact and will have no errors. As such I cannot see how I could use the condition number for $D$ to find uncertainties in $x$.
Another thing that might be worth noting is that the final column and the final row of D are also exact (no uncertainty) and they are equal to $\left[\begin{matrix} 0 & 0 & 0 & 1\end{matrix}\right]^{T}$ and $\left[\begin{matrix} 0 & 0 & 0 & 1\end{matrix}\right]$ respectively.
Comment: Condition number of a matrix shows how much the error will amplify during calculations. You don't need the vector on the right hand side to have any errors, $D$ itself already introduces errors. If the errors of distance are additive (that is, each element is measured as true distance + error), then you should be able to use condition numbers to analyse
Comment: Instead of taking an inverse $D^{-1}$, you can solve a system of linear equations $D x = y$. In that case you can find exact value of $x_4$.
Comment: Hm, doesn't it follow immediately from the last paragraph that $x_4 = 1$? Then, indeed, $x_4$ should have no errors.
Comment: Finally, even if you have to measurement errors, there is precision loss induced by out digital floating points. Not every number can be represented exactly, which gives some (extremely) small error, roughly, for each number you calculate. If your condition number is extremely huge, you can suffer a major loss of precision even if you assume your numbers are exact.
Comment: The errors of my distance are additive, and their is a distinct error term for each element of $D$. So each element of $D^{-1}$ should also have an error. That is what I'm trying to find. Yet as you mentioned yourself, because of the exactness of the vector on the right, using a condition number would not let me determine an error in $x$. This cannot be correct though. This would mean no matter how inaccurate my measurement devices are, my final result will have no error.
Comment: No, I didn't say that having measured right hand vector exactly would give you exact result, neither it would prevent you from estimating errors introduced by uncertainty in $D$ using condition number. And, your numerical procedure could indeed come up with a noised solution for $x_4$. Yet, if you know the last row and column of $D$ exactly, you can (seemingly) write out an exact solution for $x_4$ with **no uncertainty**.
Comment: I know the last row and column of $D$ exactly, but once I take the inverse the last row and column  of $D^{-1}$ will have uncertainty introduced into them so $x_4$ would also have an uncertainty.
Comment: Just to be perfectly clear: you are telling us that among your four equations is $x_4=1.$  Your problem disappears.  This inconsistency with the rest of the post, which is concerned about errors in (other, irrelevant) components of $D$ leads me to suspect perhaps you haven't described your question correctly.
Answer: I'd like to point you to this paper, 'Inversion error, condition number, and approximate inverses of uncertain matrices' by Laurent El Ghaoui
https://people.eecs.berkeley.edu/~elghaoui/Pubs/InvErr_LAA02
Comment: Could you provide more information as to how this paper answers the question? Link only answers dont provide much context.


ExpandableListView doesn't expand at all

Question: I have ListView with 10 elements, and the last element is ExpandableListView, but when I click on the last element to expand, it doesn't expand at all, i can see only one child item where as there should be at least 5 child elements.
I tried to set layout height dynamically, but i don't know how to get real children items height.
Thanks in advance!
Comment: listviews doesnot work properly inside scrollview
Comment: you have an expandablelistview inside a listview ?
Comment: this scrollview doesn't work.
Answer: Do you mean you have an ExpandableListView inside a ListView? If so, I don't think it is how it should be done. What you should have is only an ExpandableListView with an ExpandableListAdapter that only return child for your 10th element. I think the documentation ( http://developer.android.com/reference/android/widget/ExpandableListAdapter.html ) explains pretty well how to create such an Adapter, but in case you need it I could paste an example.
Comment: Is this only way ? Cannot I measure height of children items, and then when i click expand icon the layout height will change dynamically ?
Comment: If you have a wrap_content, when you expand, it should grow. Anyway, I think I don't completely get your problem. Could you post some code?


RNN model for predicting room temperatures

Question: I am currently doing a project in Machine Learning where I am trying to predict the temperature of a room in future.
I have a 1-year dataset of a house with 12 rooms. Data is collected at 10 min interval. Hence, 6 points at every 1 hr interval.
The dataset contains the following features -

Outdoor Temperature [degC]
Global solar radiation [W/m2]
Rain Status  [Yes/No]
Outdoor Wind Speed [m/s]
Outdoor Wind Direction [deg]
Individual Room Temperature of all the room [degC]
Individual Occupancy information for all the rooms [Yes/No]
Individual Electricity consumption of all the rooms [W]
Individual Light power consumption of all the rooms [W]

I plan to predict the Room Temperature of 1 Specific Room, using input features (total - 18 features)

Outdoor Temperature
Global Solar radiation
Outdoor Wind Speed
Outdoor Wind Direction
Specific room Occupancy
Specific room Electricity consumption
Specific room Light power
Room temperature of all other 11 rooms

I am planning to train an RNN model to predict the temperature of the specific room.
Now, in the house, we also have a floor heating system, that will heat the room to achieve a setpoint temperature.
The idea with the model is to guide the floor heating system to make it act upon the future room temperature in the room.
Now my doubt is if a model trained on data collected without floor heating, can also predict in presence of floor heating?
I am hoping that the model will learn the relation between the different input features with room temperature.
Hence, even if I change the room temperature, the model will still be able to predict.
Let me know your thoughts.
Answer: I'll have a try. Since we don't use all samples as timesteps in RNN, we learn "patterns" from history and make prediction based on recent timesteps. The predition won't be really bad even we use naive history average method, not to speak of RNN.
I don't know whether the pattern will change after you adopt the new heating system, if so, the last year's data is somehow useless  no matter what method you use. From my experience, you can try to train a model to predict and iterate its version if you have new system's data to have better performance.
Comment: What I was hoping that the model will learn the relationship between all the input features and the room temperature. So even if the room temperature is changed, because the model learned the relationship, I was hoping that it will still be able to predict. But ya, as you said, I will also try.


Sphere in $C^3$ is not compact?

Question: Let $A=\{(x,y,z) \in \mathbb{C}^3 \mid x^2+y^2+z^2=1\}$ is not compact with Euclidean topology?
My attempt — it is not bounded since we can choose $x$ and $y$ to be arbitrarily large and this forces value of $z$ which is in $\mathbb C$ because it is algebraically closed.
Comment: What do you mean by Euclidean topology? This is defined for real spaces, which is not the case here.
Comment: @mathcounterexamples.net Topologically, this *is* a real space: $\mathbb{C}^3\cong\mathbb{R}^6$. (A bit more precisely: the "Euclidean topology" on $\mathbb{C}^n$ is the one gotten by "pulling back" the Euclidean topology on $\mathbb{R}^{2n}$ along the obvious bijection.)
Comment: @NoahSchweber Understand! Just a naive question... why not just defining the associated quadratic form on $\mathbb R^6$?
Comment: @mathcounterexamples.net No particular reason - depends what feels best, I suppose. (Although I do think it's important to develop comfort with "transporting structure," so I tend to emphasize that approach when reasonable.)
Comment: The set you are analyzing is sometime called "Lie sphere" and the analytic functionals defined on it have been studied extensively by Mitsuo Morimoto and his school.
Comment: The "real" sphere of $\mathbb{C}^3$ would be $\{(z_1, z_2, z_3) \in \mathbb{C}^3: |z_1|^2 + |z_2|^2 + |z_3|^2= 1\}$. And it corresponds to what you'd get in $\mathbb{R}^6$ which is homeomorphic in a standard way (using real and imaginary parts) to $\mathbb{C}^3$.
Answer: That's right! Maybe a slightly cleaner way to say the same argument it would be, "Since $\mathbb{C}$ is algebraically closed, for any $a, b\in\mathbb{C}$ the polynomial $P(z)=a^2+b^2+z^2-1$ has a root; so for every $a, b$ there is some $c$ such that $(a,b,c)\in A$, which means $A$ is not bounded and hence not compact."
(Depending on what level of detail is wanted, you may also need to justify the conclusion that $A$ is not bounded. But this isn't hard: just show that $A$ contains points arbitrarily far from the origin, and no bounded set contains points arbitrarily far from the origin.)
A slightly different spin you can put on the same idea is: you've shown that since $\mathbb{C}$ is algebraically closed, the projection of $A$ onto $\mathbb{C}^2$ - the set $\{(x,y)\in\mathbb{C}^2: \exists z((x,y,z)\in A)\}$ - is all of $\mathbb{C}^2$, and hence not compact. You can now conclude that $A$ itself is not compact from the following two facts (which are themselves important):

The projection map $(x,y,z)\mapsto(x,y)$ is continuous.
The continuous image of a compact set is always compact (so contrapositively, if a set has a non-compact set as a continuous image, then the original set is also non-compact).

This is overly abstract, certainly, but it's a good "toy example" of how to apply general principles about the behavior of topological properties (in this case, how compactness and continuity interact).
Answer: Yes, it is not bounded. But there is no need to mention $z$ or the fact that $\mathbb C$ is algebraically closed. Just note that $A$ contains all vectors of the form $\left(ix,\sqrt{1+x^2},0\right)$, with $x\in\mathbb{R}$. And$$\left\|\left(ix,\sqrt{1+x^2},0\right)\right\|=\sqrt{1+2x^2}.$$
Comment: @mathcounterexamples.net No, the norm here isn't just the square root of the sum of the squares of the coordinates (that wouldn't always yield a real value - consider e.g. $(1+i,0,0)$). It's the square root of the sum of the squares *of the norms* of the coordinates.

Sphere in $C^3$ is not compact?


Cout calls a method with operator <<

Question: #include <iostream>
using namespace std;

int main()
{
    char sample[] = "something really weird about c++";
    cout << sample << " - huh?";
    return 0;
}

Here is simple c++ code that print something on screen, as I'm from python, it seems really weird for me that an object (according various sources 'cout' is object of class ostream) I just wonder how object can output something on screen or do something like statement and function without calling any method, my best guess << is overloaded under the hood and calls a method on it, if I'm right, would you like to make an object that that do something like 'cout' such as multiply some value without calling a method or by overloading <<?
Comment: Same as if you had typed: `cout.operator<<(sample).operator<<(" - huh?");`  The `<<` is just syntactic sugar for a method call.
Answer: Also in Python you can overload operators. For example you can implement the special method __add__ and then call it via a + b (see eg  here for details). In principle the answer wouldn't be that different if your question was about Python instead of C++. Applying an operator is calling a function.

This
cout << sample;

is a short form of writing
cout.operator<<(sample);

ie it calls a method of cout which is a std::ostream.

You can provide an overload for the output operator for your custom type like this:
struct foo {};

std::ostream& operator<<(std::ostream& out, const foo& f) {
    // do something with out and f
    // expected is: write contents of f to out
    // possible is: anything
    return out;
}

Note that operators are not necessarily members. Some can only be implemented as member tough. More on operator overloading in C++: What are the basic rules and idioms for operator overloading?

For your specific request

if I'm right, would you like to make an object that that do something like 'cout' such as multiply some value [without calling a method or] by overloading <<?

struct multiplier {
    int value = 1;
    multiplier& operator<<(int x) {
        value *= x;
        return *this;
    }
 };

 multiplier m;
 m << 2 << 3 << 7;
 std::cout << m.value; // prints 42

However, operator overloading should be used with caution and the principle of least surprise should be kept in mind. In the above example it would be much more natural to overload operator*= instead, because thats the operator that is expected to multiply something on the given object.

Cout calls a method with operator <<


Abandoned webform log

Question: I'm building a huge form with Webform module and need advice for a way to save not fully submitted forms even without Showing "Save draft" button options is enabled and button is visible (which is another PITA).
Comment: Unclear what you're asking.
Answer: You'll need to write a custom module that calls an AJAX function after each field of the Webform has been changed that fires the same function that the Save draft button does.
Shouldn't be too complicated, there is a starting point at Use AJAX to auto save a draft which should hopefully push you in the right direction, plus Webform Ajax might also help

Abandoned webform log


Como salvar e retornar imagens com Web Api?

Question: Como enviar e retornar imagens de um Web Api apartir do Controller de uma aplicação Asp.net MVC?
No meu Controller do projeto Asp.net MVC eu recebo da View uma imagem do tipo HttpPostedFileBase e preciso enviar ao Web Api utilizando PostAsJsonAsync. Ex.:
    var response = await client.PostAsJsonAsync("api/image", image);

Obs.: eu preciso salvar no banco de dados somente o caminho da imagem e o nome dela, o arquivo deve ser salvo em uma pasta no servidor.
Obrigado.
Answer: Salvar
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace UploadApplication.Controllers
{
    public class UploadController : ApiController
    {
        public async Task<HttpResponseMessage> Post()
        {
            // Ver se POST é MultiPart?
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            // Preparar CustomMultipartFormDataStreamProvider para carga de dados
            // (veja mais abaixo)

            string fileSaveLocation = HttpContext.Current.Server.MapPath("~/Diretorio/Do/Servidor");
            CustomMultipartFormDataStreamProvider provider = new CustomMultipartFormDataStreamProvider(fileSaveLocation);
            List<string> files = new List<string>();
            try
            {
                // Ler conteúdo da requisição para CustomMultipartFormDataStreamProvider.
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    files.Add(Path.GetFileName(file.LocalFileName));
                }
                // OK se tudo deu certo.
                return Request.CreateResponse(HttpStatusCode.OK, files);
            }
            catch (System.Exception e) {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
    }

    public class CustomMultipartFormDataStreamProvider : MultipartFormDataStreamProvider
    {
        public CustomMultipartFormDataStreamProvider(string path) : base(path) { }

        public override string GetLocalFileName(HttpContentHeaders headers)
        {
            return headers.ContentDisposition.FileName.Replace("\"", string.Empty);
        }
    }
}

Retornar
Aí depende de como você quer fazer. Se a imagem fica hospedada no servidor, creio que o tradicional (de retornar o caminho no JSON) seja o mais adequado.


Optimizing online photo gallery for retina devices

Question: I have an existing website (a photo blog) that loads the majority of the photos from Flickr. I'd like to enhance the experience for users with high resolution screens and load higher res versions of photos, but I'm not sure what would be the best way to go.
Since the images in question are not UI elements, there is no sensible way to solve this problem with CSS. That leaves either client side JavaScript, or a server side find-and-replace for specific image patterns (since they come from Flickr, it's easy to detect and easy enough to figure out the url for a double-sized image).
For client side, my concern is that even the regular sized images are 500-800 KB in size, there there can be 10-30 images per gallery, causing lots of excess bandwidth use for retina users.
For server side, it's obviously tricky to determine if the request comes from a retina device or not. One idea I had (which I have yet to test out), was to run a JavaScript function that checks window.devicePixelRatio and sets a cookie accordingly, and then on each successive page request the server would know if the device is high res or not. That leaves the entry page with non-retina images, but at least all the next ones will have high res images loaded right away.
Are there any pitfalls to this proposed solution? Are there better ways to handle it?
Answer: You can generate CSS on server that will have links to both regular size and double-sized images in background-image property. This CSS can easily be different for every page by including it in


Display a flag link in views based on whether the node has an associated taxonomy term

Question: All of my nodes of a certain content type are given a category by assigning a taxonomy term. I would only like to add the flag, "My Fruits" if the content has the term "Fruit" assigned to it.
So far I've attempted using a views PHP field to add the flag:
This works to simply print the flag:
<?php
print flag_create_link("basket_01_t01_fruit", $row->nid);
?>

But this, I'm not able to get working:
<?php
if ($row->field_item_produce_type == '3') {
print flag_create_link("basket_01_t01_fruit", $row->nid);
}
?>

Any ideas would be appreciated.
Answer: You could achieve this easily using views without using views php field. More specifically you can create a view of content with an EVA (entity views attach) field display where you will add the flag link field and attach it to the nodes of that content type. Just make sure to:

Add a contextual filter of Content:Nid
Add a relationship of "Content:Taxonomy terms on node"
Also add a "Flags: Node flag" relationship (uncheck the include flagged content only checkbox)
Add a filter "Content type:...your content type which nodes will have the flag link
Add a filter "Taxonomy term: Term ID" that will equal to the tid of the "fruit" term.

After that you can easily choose how to display this eva field on your nodes using Display suite.
Comment: Thanks, after some effort I was able to accomplish this with your suggestion.
Comment: Cheers. Glad to help.