Density of set of differences of cubes and primes

Question: Consider the set $A$ of natural numbers which are of the form $k^3-p$, for $k$ a positive integer and $p$ a positive prime. Does $A$ have a density (of any of the usual kinds for sets of natural numbers) and if so, what is it?
$A$ contains a lot of numbers, and it seems somewhat difficult to me to prove that a particular number is not in $A$, except that most cubes are not in $A$.
Answer: A naive approach would be to say that the chance $n$ is equal to $k^3-p$ for a given $k$ is about $\frac{1}{\ln(k^3-n)}$.  Then the chance $n$ is not equal to $k^3-p$ for any $k$ is $$\prod_{k=\sqrt[3]{n}}^\infty {1-\frac{1}{\ln(k^3-n)}}$$  as this goes to zero, "all" numbers should be in A.


Starting thread in Discord using Pycord

Question: I am trying to start a thread using the Pycord library. Aside from the official documentation, I couldn't find any real life examples of how this goes.
So far I am running into a Error 400 Bad Request (error code: 20035): Guild Premium subscription level too low.
I have tried the solutions mentioned here, but so far no luck.
Here is my current code, any idea of how could I approach it?
class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        self.comments = kwargs.pop("comments")
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        channel = self.get_channel(xxx)  # Your channel ID goes here
        for comment in comments:
            # await channel.send(comment['data']['author'])
            # await channel.create_thread(comment['data']['link_title'])

            await channel.create_thread(name="wop")

Also, my bot seems to have the correct permissions, as seen here:
Answer: Explanation
As per the error (Guild Premium subscription level too low), your server has not been boosted enough to use private threads, which is the default in pycord.
You can change this behaviour by modifying the type argument you pass to create_thread, as follows:
Code
from pycord.enums import ChannelType
class MyClient(discord.Client):
    def __init__(self, *args, **kwargs):
        self.comments = kwargs.pop("comments")
        super().__init__(*args, **kwargs)

    async def on_ready(self):
        channel = self.get_channel(xxx)  # Your channel ID goes here
        for comment in comments:
            # await channel.send(comment['data']['author'])
            # await channel.create_thread(comment['data']['link_title'])

            await channel.create_thread(name="wop", type=ChannelType.public_thread)

Note that ChannelType was imported from pycord.enums
References
ChannelType
create_thread
https://discord.com/developers/docs/resources/channel#start-thread-without-message

Creating a private thread requires the server to be boosted. The guild features will indicate if that is possible for the guild.

Starting thread in Discord using Pycord


How to make a .cat file from a .txt file

Question: I'm having trouble in converting a .txt file into a .cat file.
It's a dictionary (LIWC2007 italian)which separates words into categories; I have to load it on WordStat 6.1. WordStat won't see any non-.cat files when I try to load the dictionary.
How do I convert the file? Looking on the web wasn't helpful.
Thanks in advance for your time.
Comment: Do you need to change the format/content of the file, or just the name?
Comment: this isn't about programming.
Answer: Try using the 'ren' command. So ren filename.txt filename.cat.
Answer: You did not specify what OS you are on but on windows you can open the command prompt and use the move command to rename the file with the *.cat extention something like this should work move myfile.txt myfile.cat this may still not work however if the program is looking for more than just the extension.


Show that a set fails to be a manifold

Question: Spivak defines manifolds in this way:

A subset $M$ of $\mathbf R^n$ is called a $k$-dimensional manifold (in $\mathbf R^n$) if for every point $x\in M$ the following condition is satisfied:
$(M)$ There is an open set $U$ containing $x$, an open set $V\subset \mathbf R^n$, and a diffeomorphism $h:U\to V$ such that $$h(U\cap M)=V\cap(\mathbf R^k\times\{0\})=\{y\in V: y^{k+1}=\dots=y^n=0 \}.$$

And gives this theorem:

5-2 $\,\,\,$ Theorem. $\textit{A subset}$ $M$ $\textit{of}$ $\mathbf{R}^n$ $\textit{is a}$ $k\textit{-dimensional manifold}$ $\textit{if and}$ $\textit{only if}$ $\textit{for each point}$ $x\in M$ $\textit{the following}$ $\textit{"coordinate condition"}$ $\textit{is satisfied:}$
$\quad (C)$ $\textit{There is}$ $\textit{an open set}$ $U$ $\textit{containing}$ $x\textit{, an}$ $\textit{open set}$ $W\subset\mathbf{R}^k\textit{,}$ $\textit{and a}$ $1\textit{-}1$ $\textit{differentiable}$ $\textit{function}$ $f:W\to\mathbf{R}^n$ $\textit{such that}$  $$\begin{align}(1) \ & f(W)=M\cap U,\\ (2)\ & f'(y)\textit{ has rank }k\textit{ for each }y\in W,\\ (3) \ & f^{-1}:f(W)\to W\textit{ is continuous}.\end{align}$$

He then asks to make up a counterexample to Theorem 5-2 if condition $(3)$ is omitted and as a hint says "wrap an open interval into a figure six". But I don't have any idea on how to do that, nor do I have other ideas for counterexamples.
The only idea that I had is to translate Spivak's condition $(C)$ into more comprehensible (i.e., more comprehensible/familiar for/to me) language (see my other question) and then figure out what condition $(3)$ means in terms of the setting which I'm familiar with. But probably it's easier to do this problem directly, I don't know.
Comment: Can you see what his hint means pictorially even if you can't write down an explicit function?
Comment: @TedShifrin: I can see that "6" (the closed figure 6) is not a 1-dimensional manifold (in the most general definition).
Comment: So you need a mapping from an open interval $(a,b)$ to the plane so that the "junction point" of the 6 is $f(c)$ and $\lim\limits_{t\to b^-} f(t) = f(c)$?
Comment: Well, if this condition holds, then $f$ will fail to be continuous at $b$ from the right, but I don't see why is that what we need. We need $f$ to have nonzero derivative on the whole $(a,b)$ and its inverse must be discontinuous at some point.
Answer: See this question. The interval $(-\pi,\pi)$ is "wrapped" to form a figure eight via the map $(-\pi,\pi) \to \mathbb{R}^2$, $t \mapsto (\sin 2t, \sin t)$. This map is one-to-one and differentiable.
However, the inverse map from the image to $(-\pi,\pi)$ fails to be continuous for open neighborhoods of the "crossover point." This is easiest to think about in terms of limits. There are sequences in the image converging toward the crossover point, but the termwise preimage of the sequence coverges to $\pi$ or $-\pi$, not the preimage of the crossover point, which is zero.
EDIT: Answer to question in comment. Let $a_n$ be a sequence in $(-\pi,\pi)$ converging to $\pi$, for example $a_n = \pi - \frac{1}{n}$. Then $f(a_n)$ is a sequence in the figure-eight converging to the origin. Note that $f$ is injective, so it is bijective when we restrict the range to be the image of $f$. Also note that $f(0)$ is the origin. If $f^{-1}$ is continuous, then
$$
\lim_{n \to \infty} f^{-1}(f(a_n) ) = f^{-1} \big(\lim_{n \to \infty} f(a_n)\big)
$$
The LHS is $\lim a_n = \pi$, but the RHS is $f^{-1}(0,0) = 0$, so $f^{-1}$ can't be continuous.
Comment: How do I see that the preimage of such a sequence converges to $\pm \pi$?
Answer: Consider$$\begin{array}{rccc}f\colon&(-1,1)&\longrightarrow&\mathbb{R}^2\\&t&\mapsto&\begin{cases}(t,0)&\text{ if }t<0\\\left(\cos\left(-\frac\pi2+2\pi t\right),1+\sin\left(-\frac\pi2+2\pi t\right)\right)&\text{ otherwise.}\end{cases}\end{array}$$Then $f\bigl((-1,1)\bigr)$ is the union of the segment joining $(-1,0)$ to $(0,0)$ together with the circle centered at $(0,1)$ with radius $1$. It is not a manifold because of the point $(0,0)$. If you remoe it, then, yes, it is a manifold.
Comment: But $(C)$ says that the map should be from an open subset of $\mathbf R^k$, so probably you need to take the open interval?
Comment: @user531299 Sure. My mistake. I've edited my answer.
Comment: Thanks. It seems to be a hassle to check that this piecewise defined function has a nonzero derivative everywhere...
Comment: @user531299 Did you try it? It's really easy.

Show that a set fails to be a manifold


Block large number of IP addresses

Question: I am running a centos server with WHM and Cpanel and using CSF as the firewall. I would like to block a whole range of IP addresses.
I wanted to start off with China, and got a list of IP's from http://www.countryipblocks.net/ - this amounts to around 3500 ip addresses/ranges.
Using CSF, I noticed that the default for DENY_IP_LIMIT is set to 100. I can obviously increase this, but CSF states:
<code># Limit the number of IP's kept in the /etc/csf/csf.deny file. This can be
# important as a large number of IP addresses create a large number of iptables
# rules (4 times the number of IP's) which can cause problems on some systems
# where either the the number of iptables entries has been limited (esp VPS's)
# or where resources are limited. This can result in slow network performance,
# or, in the case of iptables entry limits, can prevent your server from
# booting as not all the required iptables chain settings will be correctly
# configured.
</code>
So, 3500 is a BIG increase over 100. Should I be concerned, and if so, are there any other alternatives?
Answer: CSF can do country blocks itself, from the config file:
<code>##############################################################################
# SECTION:Country Code Lists and Settings
###############################################################################
# Country Code to CIDR allow/deny. In the following two options you can allow
# or deny whole country CIDR ranges. The CIDR blocks are generated from the
# Maxmind GeoLite Country database http://www.maxmind.com/app/geolitecountry
# and entirely relies on that service being available
#
# Specify the the two-letter ISO Country Code(s). The iptables rules are for
# incoming connections only
#
# Warning: These lists are never 100% accurate and some ISP's (e.g. AOL) use
# non-geographic IP address designations for their clients
#
# Warning: Some of the CIDR lists are huge and each one requires a rule within
# the incoming iptables chain. This can result in significant performance
# overheads and could render the server inaccessible in some circumstances. For
# this reason (amongst others) we do not recommend using these options
#
# Warning: Due to the resource constraints on VPS servers this feature should
# not be used on such systems unless you choose very small CC zones
#
# Warning: CC_ALLOW allows access through all ports in the firewall. For this
# reason CC_ALLOW probably has very limited use
#
# Each option is a comma separated list of CC's, e.g. "US,GB,DE"
CC_DENY =
CC_ALLOW =

# An alternative to CC_ALLOW is to only allow access from the following
# countries but still filter based on the port and packets rules. All other
# connections are dropped
CC_ALLOW_FILTER =

# This Country Code list will prevent lfd from blocking IP address hits for the
# listed CC's
CC_IGNORE =

# Display Country Code and Country for reported IP addresses. This option can
# be configured to use the MaxMind Country Database or the more detailed (and
# much larger and therefore slower) MaxMind City Database
#
# "0" - disable
# "1" - Reports: Country Code and Country
# "2" - Reports: Country Code and Country and Region and City
CC_LOOKUPS = Default: 1 [0-2]

# This option tells lfd how often to retrieve the Maxmind GeoLite Country
# database for CC_ALLOW, CC_ALLOW_FILTER, CC_DENY, CC_IGNORE and CC_LOOKUPS (in
# days)
CC_INTERVAL = Default: 7 [1-31]
</code>
however the problem still remains, having that large an iptables setup will slow you down, so its better done on dedicated hardware if possible, depending on how powerful your server is and the amount of traffic you get will decide how feasible this is for you, low power and/or high traffic may make this option not a great idea.
the question I would ask though, is why do you need to block such a large range of IP's? if its just to stop attacks from them, its probably better to just let CSF&LFD do its job to auto block those attacking IP's as they come and go fairly frequently so your block list might not be all encompassing very quickly especially with bot nets

Block large number of IP addresses


IOS searchBar - Getting rid of the white space below

Question: I have a view which has two containers: Top_Container and Bottom_Container.
Each Container points to a VC with a TableView.
The Bottom_Container points to a TableView with a searchBar on top.
Whenever the searchBar gets activated in the TableView a white space appears below the searchBar between the searchBar and the greyed zone corresponding to the serachBarTableView (which superposes the TableView).
I have been trying with no success to get rid of this white space with no success.
Anybody has an idea how to customize:
- the white space which appears below the searchBar ?
- the greyed zone (searchBar TableView ?) on top of the TableView which appears whenever the searchBar gets active ?
Thank you.
Comment: Do you have an image of what your want to get rid of ?
Comment: Please mention version of iOS and Xcode.
Answer: Try with following code:
CGRect rect = self.searchBar.frame;
UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, rect.size.height-2,rect.size.width, 2)];
lineView.backgroundColor = [UIColor clearColor];
[self.searchBar addSubview:lineView];

It is fix.
Answer: I had similar problem and in my case it was caused by opaque NavigationBar. When I set NavigationBar to translucent, then the underlaying UITableView is correctly aligned to the active UISearchBar. (note: I'm using UISearchDisplayController in my view controller)
In your case maybe you can move (and animate) the underlaying table view in UISearchDisplayDelegate's methods willBeginSearch and willEndSearch. If you are using UISearchBar only, then you need to subclass it and override becomeFirstResponder and resignFirstResponder methods and implement the "table view moving" code there.
Answer: I just fixed this problem in my own code. For me, the issue was caused by 2 lines of code.
self.viewController.edgesForExtendedLayout = UIRectEdgeNone;
self.navigationBar.translucent = NO;
After removing both these lines, everything worked as expected.


Bottle framework generate pdf

Question: I need to generate PDF document using the Bottle framework.
I tried similar to Django but that didn't work:
@bottle.route('/pd')
def create_pdf():
    response.headers['Content-Type'] = 'application/pdf; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename="test.pdf"'
    from io import BytesIO
    buffer = BytesIO()
    from reportlab.pdfgen import canvas
    p = canvas.Canvas(buffer)
    p.drawString(100,100,'Hello World')
    p.showPage()
    p.save()
    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response

Answer: Bottle functions aren't supposed to return the response object, they're supposed to return an iterable (string, list, generator, etc.).
So you want this:
from io import BytesIO
from reportlab.pdfgen import canvas

@bottle.route('/pd')
def create_pdf():
    response.headers['Content-Type'] = 'application/pdf; charset=UTF-8'
    response.headers['Content-Disposition'] = 'attachment; filename="test.pdf"'

    buffer = BytesIO()
    p = canvas.Canvas(buffer)
    p.drawString(100,100,'Hello World')
    p.showPage()
    p.save()

    return buffer.getvalue()

Bottle framework generate pdf


Cubics with one real root

Question:
$(1) \quad f(x) = x^3- 3ax + b$
$(4) \quad f(x) = x^3 - 3hkx - (h^3 + k^3)$

By comparing the coefficients in equations $(1)$ and $(4)$, obtain two equations that relate $h$ and $k$ to $a$ and $b$.
One of these is solved to give $k$ in terms of $a$ and $h$.
Substitute this into the other equation and set $t = h^3$ to deduce a quadratic equation satisfied by $t$.
Choose $h^3$ to be one root of this quadratic and then show that the other root must be $k^3$.
By summing the cube roots of the roots of the quadratic one finds $x = h + k$.
If equation $(1)$ has exactly one real root, show that $h^3$ and $k^3$ are distinct real numbers.
I have worked out the quadratic to be $t^2 + bt + a^3$.
Not sure how to carry this forward.
Comment: See [**another answer**](http://math.stackexchange.com/questions/1616213/how-to-ind-the-complex-roots-of-y3-frac13y-frac2527/1617160#1617160)
Comment: Looks like you have a sign error -- the quadratic should be $t^2 + bt + a^3 = 0$?
Comment: You're right, thanks
Answer: Obviously,
$$a=hk,\\b=-h^3-k^3.$$
Then
$$k=\frac ah,\\b=-h^3-\frac{a^3}{h^3}=-t-\frac{a^3}t$$
or
$$t^2+bt+a^3=0.$$
From the Vieta formulas, the sum of the roots of this quadratic equation is $-b$, and from the definition,
$$t_1+t_2=-b=h^3+k^3.$$ So if $t_1=h^3$, then $t_2=k^3$.
Now $x=h+k$ is a root of the cubic because
$$(h+k)^3-3a(h+k)+b=h^3+3hk(h+k)+k^3-3a(h+k)+b=0$$ from the defintions of $h,k$.
The cubic equation has a single real root when it has no extrema, i.e.  the derivative doesn't cancel:
$$3x^2-3a$$ is never zero for $a<0$, so that $h^2=k^2=a$ is not possible.

A personal note.
I find this exposition rather disconcerting. If prefer this one:
To solve $x^3-3ax+b=0$, decompose in two terms, $x=h+k$. Then substituting, the equation becomes
$$h^3+3hk(h+k)+k^3-3a(h+k)+b=0.$$
If we set $a=hk$, only
$$h^3+k^3+b=0$$ remains.
Now in the form
$$h^3+k^3=-b,\\h^3k^3=a^3$$
we get a sum/product problem which is easily solved by means of a bicubic equation:
$$h^6+h^3k^3=-bh^3,\\
(h^3)^2+b(h^3)+a^3=0.$$

Cubics with one real root


Errors Running WebGoat 7 on Tomcat

Question: I am trying to run WebGoat on a standalone Tomcat7 server. I placed the "webgoat-container-7.0.1.war" in the Tomcat directory and renamed the file "WebGoat.war". The initial landing page, "http://10.1.1.1/WebGoat/" looks well, and I am able to login. However,after I login I start seeing errors and I am not able to access the lessons. Below is a screen capture of the errors that I receive.
WebGoat Screen Capture
Am I missing a dependency somewhere? What can I do to troubleshoot?
Thanks,
Brooks
Answer: I struggled with this for a while myself. It's possible that you are missing permissions to write the user database file. If your log entries show something like this:
<code>Caused by: java.io.FileNotFoundException: /var/lib/tomcat7/UserDatabase.mv.db (Permission denied)
</code>
Then it would be a matter of granting your tomcat user permissions to the folder listed.
Comment: Thanks for the reply. I ended up using Supervisor (http://supervisord.org/) to run the WebGoat "Easy Run" JAR. Supervisor keeps WebGoat "Easy Run"  running and starts it automatically on reboots.
Comment: Yeah, the runnable jar is very nice and convenient, glad you found a solution!

On a side note, the troubleshooting steps I followed were to look at the 'catalina.out' file for my tomcat instance, it ultimately led me to find the issue.

Errors Running WebGoat 7 on Tomcat


Select a Row a Table is Grouped by Pandas

Question: I am making a table and grouping it by a variable called 'passer_player_name'
data.loc[(data['play_type'] == 'pass') & (data['down'] <= 4)].groupby(by='passer_player_name')[['epa']].mean()
passer_index = data.loc[(data['play_type'] == 'pass') & (data['down'] <= 4)].groupby(by='passer_player_name')[['epa', 'success','yards_gained']].mean()
passer_index['attempts'] = data.loc[(data['play_type'] == 'pass') & (data['down'] <= 4)].groupby(by='passer_player_name')['epa'].count()

This gave the following output (a few example lines):
                      epa  success  yards_gained  attempts
passer_player_name
L.Jackson           0.336     0.48           6.9       335
K.Cousins           0.295     0.50           7.1       363
P.Mahomes           0.285     0.50           7.4       368

What I am trying to do next required me to grab/sort my table by using the 'passer_player_name' column, however that is technically not part of the table. I tried doing the following:
passer_index['passer_names'] = data.loc[(data['play_type'] == 'pass') & (data['down'] <= 4)].groupby(by='passer_player_name')['passer_player_name']

Unfortunately, this gave the following in the added column (this is one example row):
(L.Jackson, [L.Jackson, L.Jackson, L.Jackson, ...

How would I get a column that simply says the player's name once, like a column that would just have the output 'L.Jackson' (obviously different for each player's name)?
Comment: `passer_index.index`
Comment: please show your expected output
Answer: Have you tried incorporating:
df.sort_index()

When your format is the way you have it, you can sort by that
Answer: Here is the answer I found to my own question.
The line that gets the data that I a looking for is the following:
passer_index['passer_names'] = passer_index.index.values

Basically just putting the name of your array + '.index.values'. A more generic example to get this is the following (with 'df' being the dataframe's variable name):
df.index.values


iFrame and Javascript to parent document

Question: I have an iFrame with an external website. I know about the same domain rule, so I am trying to invoke some javascript via the src to the parent. Currently I have:

and I change the src using javascript as follows:

but using the parent does not work:

Does the same domain rule also apply for the parent or am I doing something wrong?
Comment: I'm confused. How is `src="javascript:parent.document.write("blah");"` going to work?
Comment: I think that is part of his question. :)
Comment: sorry, "blah" in the above is supposed to be single quoted. I hand-wrote it here. But in my editor it's correct.
Answer: This is either a workaround gone awry, or it's genius and I don't recognize it :) What exactly are you trying to achieve? Do you want to write into the sub-frame, or from the sub-frame into the parent document?
Comment: I actually thought it is something new, and tried the codes. Well, guess it is not genius. :P
Answer: I am guessing your intention is to write something to the document containing the iframe.
now, first off, your first snippet can't work because the double-quoted string inside the javascript is itself inside an attribute value, which is also enclosed in double quotes. It should read:

This is probably also wrong in your last snippet, so fix accordingly.
Still, I don't really see what you are trying to achieve. Care to explain why you are trying to use this?


Drupal 7: Database select query FROM cache_bootstrap brings server down

Question: The below query occasionally takes up to 24 sec and consumes the complete server resources.
SELECT cid, data, created, expire, serialized
FROM cache_bootstrap
WHERE cid IN ('variables');

I was informed today by my web hoster (I am on a shared server) that above select query brings down the whole node.
I have caching enable (with block caching disabled). JS- and CSS files are aggregated and cached pages are compressed. The site is running ok with no issues.
Any ideas how to track down the problem?
Comment: D7 or D6? Is the cache_bootstrap table InnoDB or MyISAM? If InnoDB what size is innodb_buffer_pool_size?
Comment: Thanks for taking the time, mikey! It's D7 (see title of question). It is InnoDB. How can I find/determine the innodb_buffer_pool_size? There is no such table in the database.
Comment: Run this Query:  `SHOW VARIABLES LIKE 'innodb_buffer_pool_size';`
Comment: Here is a screenshot of the largest tables in the database:
https://www.evernote.com/shard/s272/sh/e4b2c5c3-a72e-42fa-a3f7-8bbb5a83c846/e0387685c6cec210ef7bbafd3871457f
Comment: innodb_buffer_pool_size 68719476736
Comment: innodb_buffer_pool_size looks OK as it is 64GB vs the 8MB default... only issue that I see arising is if the MySQL server doesn't have enough ram to support that and is thus swapping. Your table sizes are small as well. What's the output of this query (it's going to have a lot of text) `show engine innodb status`
Comment: Also just to double check the indexes are there, what is the output of the cache_bootstrap query when you add EXPLAIN to it at the start. What version of D7 are you using, 7.26?
Comment: I tried show engine innodb status. But get: #1227 - Access denied; you need the SUPER privilege for this operation
Comment: Yes, Drupal 7.26. I ran

`Explain SELECT cid, data, created, expire, serialized FROM cache_bootstrap WHERE cid IN ('variables');`

here's the result:
https://www.evernote.com/shard/s272/sh/e5c23978-7982-440c-99bd-60f14ae6d854/e34cf8a3ab5022173a16133ac9cd0d8c
Comment: Interestingly the database is gradually growing in size (although no new data is added). Within 6 min it increased by 0.6 MB. Within the last 50 min by 2.4 MB.
Answer: If you can get memcache properly installed, that will help the most as it will shift queries from the cache tables in the db to your memcache server.
Try these 3 things (in order of importance):
Set the transaction isolation level to Read Committed - https://drupal.org/comment/8437127#comment-8437127 (look in your settings.php for the insertion point; it will be after the $databases variable has been set with the database credentials). This is helpful even if using memcache.
$databases['default']['default']['init_commands'] = array(
  'isolation' => "SET SESSION tx_isolation='READ-COMMITTED'"
);

Change your semaphore table to memory - https://drupal.org/comment/8469889#comment-8469889 (use the first code block "Have the name value be a primary key"). Note that this might not work if you are using MySQL 5.0 or lower due to BTREE indexes not working in Memory tables. Also noted that if you are using the memcache version of lock.inc this will not help.
ALTER TABLE semaphore ENGINE = MEMORY;
ALTER TABLE semaphore DROP PRIMARY KEY;
ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE;
ALTER TABLE semaphore ADD UNIQUE name (name) USING BTREE;
ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;
ALTER TABLE semaphore DROP INDEX expire;
ALTER TABLE semaphore ADD INDEX expire (expire) USING BTREE;

Apply this core patch - https://drupal.org/node/2193149 This will help to reduce database deadlocks from occurring only after the above 2 have been done. If using memcache this core patch will not help as this fixes an issue when using the database as a cache backend.
Comment: I have adjusted my settings.php like this:
https://www.evernote.com/shard/s272/sh/b5104e5c-393a-49aa-bea0-5bdf33d2b746/040c732a03e41628dd187e8527864500
Comment: After changing the semaphore table to memory I got an error: `#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USING BTREE' at line 1 `
Comment: Put the init_commands part after you set the database user/pass etc. What about if you use the 2nd code block for changing the memory table?
Comment: When I run the 2nd code block I get also an error:
`#1091 - Can't DROP 'PRIMARY'; check that column/key exists `
Comment: Do the rest of the SQL commands work?
Comment: `ALTER TABLE semaphore ENGINE = MEMORY;` ==> worked!
Comment: `ALTER TABLE semaphore ADD PRIMARY KEY (name, value) USING BTREE`==> didn't work
`#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USING BTREE' at line 1`
Comment: `ALTER TABLE semaphore DROP INDEX value;
ALTER TABLE semaphore ADD INDEX value (value) USING BTREE;`==> didn't work `#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'USING BTREE' at line 1 `
Comment: The index issue is odd as that should be proper syntax for MySQL 5.0+ http://dev.mysql.com/doc/refman/5.0/en/create-index.html
Comment: When I run `ALTER TABLE semaphore DROP INDEX value;` the SQL throws: `#1091 - Can't DROP 'value'; check that column/key exists`Not sure what's going on. Database version of the site: ´Database system version 5.0.51a-24+lenny5-log`
Comment: DB still growing. 0.5 MB in the last 30 min. Is this normal?
Comment: The semaphore table needs a PRIMARY index. If that query is failing you need to add it in manually:
http://imgur.com/DV936lR,Bh8dDH8#0 (2 images) Or try running this https://drupal.org/comment/8523869#comment-8523869
Comment: Also noted that the distro your database server is on is quite old http://archive.debian.net/lenny/mysql-client-5.0 and it no longer receives security updates https://wiki.debian.org/DebianLenny
Comment: Can you summarize the links a little?  Maybe extract relevant parts?  I may also do a pass at cleaning up the comments here.
Comment: You can't drop an index twice; that is what the second part is complaining about. Because your MySQL server doesn't like `USING BTREE` for some reason that index was never created. Use the modified syntax in https://drupal.org/comment/8523869#comment-8523869 where USING BTREE is not shown. You might also have to remove the DROP  queries depending on if MySQL complains about it.
Comment: MPD, I have cleaned up my comments. Only the relevant ones remain.
Comment: I ran the commands in #comment-8523869 but again to no avail:
`#1091 - Can't DROP 'PRIMARY'; check that column/key exists`

I will try to do it manually.
Comment: I ran the commands in the second table of #comment-8523869 one by one. Starting from the bottom up. Now all commands worked. Seems I got this patch in. Thanks Mikey!

I just looked at the database. In the last 8 hr it grew from 17 MB to 42 MB.
Comment: When I run cron the size of the DB doesn't change. When I clear the cache in the backend, the size goes down from 42 MB to 16.8 MB again.
Comment: No problems with cache_bootstrap anymore. The only issue is with cache_metatags but other than that the above steps seem to have worked.
Comment: metatags does have some performance issues. I have a patch here that fixes one aspect of it: https://drupal.org/node/2183203#comment-8425569


The confusing nature of direct sum for finite abelian groups

Question: I would first like to make sure of the following concepts, note that all groups are abelian. Let $A,B$ be subgroups of $G$.
(1) Cartesian product (a.k.a. external product): The Cartesian product of subgroups $A$ and $B$ is $A \times B = \left\{ (a,b) \:{:}\: a \in A, b \in B \right\}$ where the operation by components is the group operation.
(2) Internal product: The internal product of subgroups $A$ and $B$ is $AB = \left\{ ab \:{:}\: a \in A, b \in B \right\}$.
(3) Sum: The sum of subgroups A and B is $A + B = \left\{ a + b \:{:}\: a \in A, b \in B \right\}$.
So (2) and (3) are basically the same objects because (2) is used under the multiplicative notation and (3) is used under the additive notation.
(4) Direct product: The internal product $AB$ is called a direct product and denoted $A \times B$ (confusingly enough) if $A \cap B = \left\{ 1 \right\}$.
(5) Direct sum: The sum $A + B$ is called a direct sum and denoted $A \oplus B$ if $A \cap B = \left\{ 0 \right\}$.
So (4) and (5) are basically the same objects because (4) is used under the multiplicative notation and (5) is used under the additive notation.
I am aware that (1) and (4) (or (5)) are isomorphic and often used interchangeably. When the direct sum is used in a correct way, it causes no confusion at all such as $\mathbb{Z}_{15} = \left\{ 0,5,10 \right\} \oplus \left\{ 0,3,6,9,12 \right\}$.
But when it is used in a rather ambiguous way such as $\mathbb{Z}_2 \oplus \mathbb{Z}_2$, which should be $\left\{ 0+0,0+1,1+0,1+1 \right\} = \left\{ 0,1 \right\}$, which is of order $2$, but I have seen my lecturer saying it is of order $4$, so he must have interpreted it as the Cartesian product owing to the isomorphic nature.
I am really not happy with this as the definition of sum and direct sum clearly states otherwise. Could anyone shed some enlightening lights on this issue?
Comment: Direct sum and Direct products are exactly the same thing (like (1)), this as far as you use the direct sum only finitely many times.
Comment: about the $\mathbb{Z}_2\oplus\mathbb{Z}_2$, yes, as sets it is the product of $\{0,1\}$ with itself, with the addition given by $(a,b)+(c,d)=(a+c,b+d)$
Comment: You forgot the if part: $\mathbb Z_2\cap \mathbb Z_2\neq \{0\}$, so you can't treat direct sum as inner.
Comment: @Ennar I see, so strictly speaking $\mathbb{Z}_2 \oplus \mathbb{Z}_2$ shouldn't be used in the first place and should only be written $\mathbb{Z}_2 \times \mathbb{Z}_2$?
Comment: @Ennar what would be the correct definition of direct sum?
Comment: @Ennar That fails to take into account how those are identified as subgroups.
Comment: @James, no, you are just not using correct definition of direct sum. It should be: $$\bigoplus_{i\in I} G_i = \{ f\colon I\to \bigcup_{i\in I} G_i \mid (\forall i\in I)\, f(i)\in G_i,\ f(i)=e_i\ \text{for all but finitely many }i\in I\}.$$ Compare with the definition of direct product - it is obviously the same thing when we have finite indexing set $I$.
Comment: @Tobias Kildetoft, I'm not sure what you mean exactly. You can't really define $\mathbb Z_2\oplus\mathbb Z_2$ as internal sum of $\mathbb Z_2\oplus \{0\}$ and $\{0\}\oplus \mathbb Z_2$, that is circular.
Comment: @Ennar Sure, but you can easily describe a group which is the internal direct sum of those.
Comment: @Tobias, it is true that once you include those as subgroups of the direct sum and then check their internal direct sum, we will get the whole group. But this is not what James did, and my comment was directed at that.
Comment: @Ennar Ahh, I see.
Comment: @James, the definition might be more clear this way:
$$\bigoplus_{i\in I}G_i =\{ (x_i)\in\prod_{i\in I}G_i \mid x_i = e_i\ \text{for all but finitely many}\ i\in I\}.$$
Comment: @Ennar I greatly appreciate your help. Could you maybe answer my question by posting the correct definition of the direct sum with a few examples illustrating why it could fit into both internal and external notions of the direct sum?
Answer: Table of contents:

Direct products in general.
Direct sums in general.
Internal direct product (sum) in general.
A look at your examples.

Let $\{G_i\}_{i\in I}$ be a family of groups.
The direct product is defined as
$$\prod_{i\in I}G_i = \{f\colon I\to \bigcup_{i\in I}G_i\mid f(i)\in G_i,\ \forall i\in I\}$$
with multiplication defined as $(f\cdot g)(i) = f(i)g(i)$. When $I$ is finite set, it is customary to write elements of direct product as $n$-tuples. For example, if $I=\{1,2\}$, we have
$$G_1\times G_2 = \{ (g_1,g_2)\mid g_i\in G_i,\ i = 1,2\}$$ and this relates to the above definition as ordered pair $(g_1,g_2)$ can be thought of as a function $$g\colon\{1,2\}\to G_1\cup G_2,\ g(1) = g_1,\, g(2) = g_2$$ and given another ordered pair $(g'_1,g'_2)$ and corresponding function $g'$, we can see that ordered pair $(g_1g_1',g_2g_2')$ corresponds to function $g\cdot g'$, so everything checks out.
Even in infinite case, we usually don't write elements of direct product as functions, we write them the same way we would write sequences, i.e. $(g_i)_{i\in I}$ and when $I$ is clear, we usually drop it in notation and just write $(g_i)$. We would write multiplication as $(g_i)\cdot (g'_i) = (g_ig_i')$.
Direct product is naturally equipped with family of projection homomorphisms $$\{\pi_j\colon\prod_{i\in I}G_i\to G_j\}_{j\in I}$$ defined by $\pi_j(f) = f(j)$, or $\pi_j((g_i)_{i\in I}) = g_j$.

Let $\{G_i\}_{i\in I}$ be a family of groups.
The direct sum is defined as
$$\bigoplus_{i\in I}G_i = \{f\colon I\to \bigcup_{i\in I}G_i\mid f(i)\in G_i,\ \forall i\in I,\ f(i)\neq e_i\ \text{only for finitely many}\ i\in I\}$$
with multiplication defined as $(f\cdot g)(i) = f(i)g(i)$. As you can see, definition is very similar to that of the direct product, however, elements of the direct sum are non-trivial only on finitely many places.
It is immediate that when $I$ is finite, direct product and direct sum coincide, but in infinite case, direct sum is proper subgroup of direct product. Notational conventions are the same as with direct product.
Direct sum is naturally equipped with family of inclusion homomorphisms $$\{\iota_j\colon G_j\to \bigoplus_{i\in I}G_i\}_{j\in I}$$ defined by $\iota_j(x) = (g_i)_{i\in I}$, where $g_i = e_i$ for $i\neq j$ and $g_j = x$. This way we can think of all $G_j$'s as subgroups of the direct sum. We will use this later, we will identify $G_j$ with its image $\iota_j(G_j)$ and just say that $G_j$ is a subgroup of $\bigoplus_{i\in I}G_i$ when we really mean that $\iota_j(G_j)$ is a subgroup of $\bigoplus_{i\in I}G_i$. This is a common abuse of notation that one gets used to in time.
We will now assume that all the groups are abelian and switch to additive notation. Given $x\in\bigoplus_{i\in I}G_i$ and $x = (x_i)$, we can write $x = \sum_{i\in I}\iota_i(x_i)$. Note that this sum is well-defined even when $I$ is infinite because $\iota_i(x) = 0$ for all but finitely many $i\in I$, so what looks like infinite sum is really a finite one. This is a crucial difference between direct product and direct sum. There is much more to be said about this, but it wouldn't serve much purpose at this point. You will learn about it in due time. For now, just notice that when we work with vector spaces, this is similar to writing a vector as a linear combination of basis vectors.

When we have subgroups $A,B\leq G$, their internal sum $A+B$ is as you defined. But let me return to non-commutative case and instead of internal sum talk about internal product $AB$.
Here's the problem, in general, $AB$ is not a subgroup of $G$. The reason is simple, $(ab)(a'b')$ may not be an element of $AB$ because we don't know what to do with $ba'$. What we would like is to write $ba'$ in the form $a''b''$, and then we would have $(ab)(a'b') = (aa'')(b''b) \in AB$. Thus, if $AB = BA$, $AB$ is a subgroup of $G$. The converse is true as well, if $AB$ is a subgroup of $G$, then $AB = BA$ (can you prove it?)
Thus, let us work with the assumption that $AB = BA$ (note that this is trivially true in abelian case). The next question is if we can define a group homomorphism $AB\to A\times B$. The obvious candidate would be $ab\mapsto (a,b)$, but is this well defined? It turns out that assuming $A\cap B = \{e\}$ it is, because it gives us that $a_1b_1 = a_2b_2$ if and only if $a_1 = a_2$ and $b_1 = b_2$ (can you prove it?) and in that case $ab\mapsto (a,b)$ is a group isomorphism (can you prove it?)
Notice how all these considerations become trivial when you assume that $G$ is abelian.
However, we can also bypass all of this by not considering $A$ and $B$ as subgroups of $G$, but as subgroups of $A\times B$ (or $A\oplus B$, which is the same) via inclusions that I mentioned above, i.e. $A \equiv A\times\{e\}$ and $B\equiv \{e\}\times B$. Now we have that $AB = BA$ and $A\cap B = \{e\}$ inside $A\times B$, so we get that $AB = A\times B$. Again, we are identifying $A$ with $A\times \{e\}$ and $B$ with $\{e\}\times B$. Notice how we don't even have to have $A\cap B = \{e\}$ in the original group $G$, we could even have $A = B$, and still get that $A\times A$ is the internal product of $A\times\{e\}$ and $\{e\}\times A$. This is important to notice considering your examples.

So, what of your examples?
Your first example is $\mathbb Z_3\oplus \mathbb Z_5$. What you did here is exactly what I describe above, you identify $\mathbb Z_3$ with appropriate subgroup of $\mathbb Z_{15}$, and the same thing with $\mathbb Z_5$. However, there is important thing to notice here, that you might be missing: you are implicitly using the fact that $\mathbb Z_3\oplus \mathbb Z_5\cong \mathbb Z_{15}$ and this works only because $3$ and $5$ are relatively prime. Actually, what you've done is a disguised proof of $\mathbb Z_3\oplus \mathbb Z_5\cong \mathbb Z_{15}$, because when $\mathbb Z_3$ and $\mathbb Z_5$ are considered as subgroups of $\mathbb Z_{15}$, they do satisfy $\mathbb Z_3\cap \mathbb Z_5 = \{0\}$, $\mathbb Z_3+\mathbb Z_5 = \mathbb Z_5+\mathbb Z_3 = \mathbb Z_{15}$ and thus $\mathbb Z_{15} \cong \mathbb Z_3\oplus \mathbb Z_5$ by the above general discussion.
As you've seen yourself, it fails in your second example and this is because $\mathbb Z_2\oplus\mathbb Z_2\not\cong \mathbb Z_4$ (nor to $\mathbb Z_2$, for that matter). However, when you do this properly it works.
Let $A = B = \mathbb Z_2$ and identify $A$ with subgroup $A\oplus\{0\}\leq \mathbb Z_2\oplus \mathbb Z_2$ and $B$ with subgroup $\{0\}\oplus \mathbb Z_2\leq \mathbb Z_2\oplus \mathbb Z_2$. Explicitly, $A$ is identified with $\{(0,0),(1,0)\}$ and $B$ is identified with $\{(0,0),(0,1)\}$. Notice how as in general discussion we now have $A\cap B = \{(0,0)\}$ (with the identification in mind) and \begin{align}A+B &= \{(0,0)+(0,0), (1,0)+(0,0), (0,0)+(0,1), (1,0)+(0,1)\}\\ &= \{(0,0), (1,0), (0,1), (1,1)\} = \mathbb Z_2\oplus \mathbb Z_2.\end{align}
Also, what you noticed yourself, when $A$ and $B$ are not identified with appropriate subgroups of $\mathbb Z_2\oplus \mathbb Z_2$, but instead considered as subgroups of $\mathbb Z_2$, we don't have $A\cap B = \{0\}$ and instead we have $A + B = \mathbb Z_2 \not\cong \mathbb Z_2\oplus \mathbb Z_2$.
Comment: Wow..... I am speechless, thank you so much for spending your time and sharing your knowledge, I am so grateful. I shall take my time to digest it. Again, thank you so much.
Comment: @James, you are welcome. I think its a great question and that many students beginning to learn group theory might have similar problem. I've turned this answer into community wiki in hope that others will share my opinion and help improve the quality of it.
Comment: @James, this is a lot to read, so take your time and get back to me when you digest it. If there is something that is not clear, let me know and I will try to improve my answer.


js checking for idle time not working

Question: Im using the below code to check for idle time using javascript but the alert msg is not triggered when I click or keypress.
http://jsfiddle.net/wnm7cvhd/
code
$(document).ready(function () {
    alert('hi')
    var idleTime = 0;
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 30000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        alert('mouse moved')
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        alert('key pressed')
        idleTime = 0;
    });

});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 1) { // 20 minutes
        alert('No action')
    }
}

Comment: there is no click handler... keypress is working
Comment: Your comments make no sense. "30000" is not 1 minute, and `idleTime > 1) { // 20 minutes` is not 20 minutes. It's 1 interval of 30,000 milliseconds, or 30 seconds.
Comment: your fiddle is working.
Comment: strange..its not working on my machine
Comment: One problem I can see the scope of `idleTime`.. it is a closure variable in the dom ready handler so will not be accessible in `timerIncrement`
Comment: see http://jsfiddle.net/arunpjohny/adbrspqt/1/
Comment: @meagar most probably reduced the gap for testing purposes
Answer: Everything seems to be working for me. However, be aware that there is NO click handler, so you will not be able to intercept a click event. I have updated Your Fiddler in the following manner...

Moved the idleTime out of the ready function scope and made it global so that timerIncrement increment can also access it. Otherwise, you will get errors
Replaced all calls to alert with console.log...alert is a bit intrusive
Changed the setInterval timeout to 5 seconds for illustration purposes and avoid having to wait one minute to see the "No Action" message
Answer: Your event handler are working fine... based on your comment about the fiddle I posted above... I guess that the problem is the scope of the variable idleTime.
The variable idleTime is declared within the dom ready handler method, so it will be available inside the scope of the dom ready handler onlye... but the method timerIncrement is declared outside the scope of the dom ready handler... So it should give an error in your console saying Uncaught ReferenceError: idleTime is not defined.
The solution here is to more the method timerIncrement inside the dom ready handler so that it can access the closure variables defined in the dom ready handler
$(document).ready(function () {
    console.log('hi')
    var idleTime = 0;
    //Increment the idle time counter every minute.
    var idleInterval = setInterval(timerIncrement, 1000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).on('mousemove keypress click', function (e) {
        console.log('reset: ', e.type)
        idleTime = 0;
    });

    function timerIncrement() {
        idleTime = idleTime + 1;
        if (idleTime > 1) { // 20 minutes
            console.log('No action')
        }
        $('#result').html(idleTime)
    }
});

Demo: Fiddle
Comment: actually, `setInterval` is running on every second, to set it to one minute it should be 60000 (1000 * 60)
Comment: @Leo yes... but as a developer I don't like to wait for 60 sec to see whether it is working... those values can be changed later once the code segment is working fine
Comment: Got it, just thought I dropped a comment coz it might be misleading for someone else

js checking for idle time not working


Display only the value of a field in a content-type template

Question: I'm attempting to display a plain text field so that I can use it to embed youtube videos
In my template I have

However when it renders it produces a mess
<iframe width="420" height="315" src="https://www.youtube.com/embed/

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'field' -->
<!-- FILE NAME SUGGESTIONS:
   * field--node--field-video--beer.html.twig
   * field--node--field-video.html.twig
   * field--node--beer.html.twig
   * field--field-video.html.twig
   * field--string.html.twig
   x field.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/stable/templates/field/field.html.twig' -->

            <div data-quickedit-field-id=" node="" 15="" field_video="" en="" full"="">C0DPdy98e4c</div>

<!-- END OUTPUT from 'core/themes/stable/templates/field/field.html.twig' -->

" frameborder="0" allowfullscreen>

I understand that part of it is because I'm in debug mode, but it's also wrapping it in a quick edit field div. And even if it didn't I'd rather not exit debug mode just to work on this. Is there a way to output just the value and nothing more?
Like something similar to {{ content.field_video.value }}?
If I can't disable quick edit field by field, is there a way to print a field while keeping the HTML intact? When I put the entire iframe into field it turns the html tags into text.
I tried
{{ content.field_video|raw }}

but the output still showed the html tags as text. I tried
{{ content.field_video.value|raw }}

But that did not show anything.
Answer: I was able to print the value by using
{{ content.field_video[0] }}

Comment: Did the above worked in debug mode?
Comment: yes it did. It only printed the value, none of the surrounding debug info.
Comment: Sadly, in my use case, this just gets me a NULL. MAybe because it's D9, or a different content type
Answer: I ended up needing to use
fields.field_name.content|striptags|trim

but this was inside a views-view-field--view-name.html.twig template... so it might be a different use case. Drupal 9. Media oembed video content type.


How to populate SCRIPT_FILENAME and SCRIPT_PATH server vairables to php-cgi from the command line

Question: I'm trying to run cron php script from command line. The server does not have PHP CLI but php-cgi exists. I tried to pass PHP directly to php-cgi but this does not work because two server environment variables are missed ($_SERVER['SCRIPT_FILENAME'] and $_SERVER['SCRIPT_PATH']). I tried to fill variables using following recommendation but these variables are not populated. What is missed in this answer? How to make php-cgi populate these server values? The question is not platform specific, but execution script looks like this currently
#!/bin/bash

export REDIRECT_STATUS=200
export GATEWAY_INTERFACE="CGI/1.1"
export SCRIPT_FILENAME=/usr/local/www/owncloud/cron.php
export REQUEST_METHOD="GET"

/usr/local/bin/php-cgi

Please note that I'm not asking for workaround, I already added helper php file which fill necessary values. But this is temporary solution because next software update could show another issue with php-cgi call
UPDATE
It seems the issue is not with php-cgi execution but with the SCRIPT_FILENAME and SCRIPT_PATH server variables only. So solution works in common cases when you do not need them. Also the issue might be version specific (it works with PHP version prior to 5.5) or platform specific
Comment: do you require the additional `export GATEWAY_INTERFACE` line?
Comment: have you tried `setenv` instead of `export`?
Comment: no, it was mistake in the code. But it does not affect the php-cgi behavior. export is bash equivalent of setenv. And setenv command does not exist for bash
Comment: what you are doing is correct, tested and it works for me. have you checked if you have got sufficient permission?
Comment: Do you check your php can access mentioned variable? Is it filled with correct path?
Answer: I searched SO with question to these specific server variables and found following statement here:

You are just juggling variables now. SCRIPT_FILENAME is a part of the
  CGI spec. It will not be available if PATH_INFO is unavailable. As for
  REQUEST_URI, it's apache's mod_rewrite specific. – LiraNuna

So exporting PATH_INFO variable also populates values from SCRIPT_FILENAME and SCRIPT_PATH environment variables. Please note that SCRIPT_FILENAME is needed still to point php-cgi to php input file. Below is the final script
#!/bin/bash

export REDIRECT_STATUS=200
export GATEWAY_INTERFACE="CGI/1.1"
export REQUEST_METHOD="GET"
export SCRIPT_FILENAME=/usr/local/www/owncloud/cron.php
export SCRIPT_PATH=cron.php
export PATH_INFO=$SCRIPT_FILENAME

/usr/local/bin/php-cgi

Answer: Here is what i tested. i used root account on my home PC. My IP is masked from the output. cannot post this much as comment so posting as answer.
The script
#!/bin/bash

export REDIRECT_STATUS=200
export GATEWAY_INTERFACE="CGI/1.1"
export SCRIPT_FILENAME=/root/t.php
export REQUEST_METHOD="GET"

/usr/bin/php-cgi

PHP file
<?php
print_r($_SERVER);
?>

Output I get
X-Powered-By: PHP/5.3.8
Content-type: text/html

Array
(
    [HOSTNAME] => HomePC
    [SELINUX_ROLE_REQUESTED] =>
    [SHELL] => /bin/bash
    [TERM] => xterm
    [HISTSIZE] => 1000
    [SSH_CLIENT] => xx.xx.xx.xx 58196 22
    [SELINUX_USE_CURRENT_RANGE] =>
    [SSH_TTY] => /dev/pts/3
    [USER] => root
    [LS_COLORS] => rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.tbz=01;31:*.tbz2=01;31:*.bz=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.war=01;31:*.ear=01;31:*.sar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
    [SCRIPT_FILENAME] => /root/t.php
    [PATH] => /usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
    [MAIL] => /var/spool/mail/root
    [PWD] => /root
    [LANG] => en_US.UTF-8
    [REDIRECT_STATUS] => 200
    [SELINUX_LEVEL_REQUESTED] =>
    [HISTCONTROL] => ignoredups
    [HOME] => /root
    [SHLVL] => 2
    [LOGNAME] => root
    [SSH_CONNECTION] => xxx.xxx.xx.xxx 58196 192.168.1.2 22
    [GATEWAY_INTERFACE] => CGI/1.1
    [LESSOPEN] => ||/usr/bin/lesspipe.sh %s
    [REQUEST_METHOD] => GET
    [G_BROKEN_FILENAMES] => 1
    [_] => /usr/bin/php-cgi
    [PHP_SELF] =>
    [REQUEST_TIME] => 1379952948
)

Comment: Unfortunately if does not work for me. Also I do not see SCRIPT_NAME server variable in your output. It is also required by cron script
Comment: I think if you execute through CLI you get only `SCRIPT_FILENAME` http://www.php.net/manual/en/reserved.variables.server.php isn't `SCRIPT_FILENAME` good enough for your case?
Comment: cron.php fails with missed `SCRIPT_NAME` variable as well. Anyway I do not see `SCRIPT_FILENAME` in server variables as well. It could be PHP version specific, but I use newer version of PHP (`X-Powered-By: PHP/5.5.2`)
Comment: if you really want `SCRIPT_NAME` you can add `export SCRIPT_NAME=/root/t.php`. This also fills the `PHP_SELF` variable.
Comment: May be version specific. I cannot have access to PHP 5.5.x now. can check tomorrow morning my time.
Comment: I tested this in `fc18 PHP 5.4.19` and works for me. 5.4.19 is the latest version available for my distro (don't want to compile from source). Sry I may not be able to help further.
Comment: Thank you anyway. It seems I found the reason of such behavior
Comment: Please post what you have found as an answer and accept it. It may help someone


Long file name stops pull from github.com

Question: When creating a file through the github.com web interface, an accident occurred where the contents of the file were pasted into the new file name text box.  This created a really long file name in the github repository.  The filename contained double quotes, single quotes, utf-8 weird quotes from M$ Word etc...
After this file was created, a pull request would not work.  I got an error stating that git could not create this file.
As I can't pull this file on windows or linux, I can't remove/commit and push back to the repository.  Is there a way of remotely deleting files in a git repository in github.com?
Additional:
I can't edit the file in github, as clicking on the really long file name causes github to spin.
Comment: Is this file the only thing that changed in the commit? / Is undoing the commit an option?
Comment: I don't know if you can undo something if you can't clone the working repository?  Is it possible to do that?
Answer: Run these commands (assuming you are talking about the master branch):
git clone --no-checkout *my-repo*
cd *repo*
git branch -f master origin/master^
git push -f origin master

This clones the repo without checking out and then sets the master branch by one
commit.
Answer: In github web interface you can click Edit on this file. In Edit mode you can rename file.
Answer: I wrote to GitHub support about this, they said:

"Will,
Okay, yes. That is a long name. We should not let that happen. Thanks
  very much for pointing this out.
We don't currently have a way to delete a file from the web, but I
  think it's pretty obvious we've been thinking about it and going in
  that direction. I'm going to tell the people working in that area
  about this incident."

In case it helps anyone else out, for windows, I came up with a solution that uses the DOS 8.3 naming convention.  I created a file in DOS that the uses the first six characters of the long file name plus a tilde, and then the numeric index.
In this case, I created a file in my working directory called 02_RUL~2.  Then I could do git status, which showed the name change, then I could commit that, push to the repository, and then delete the new short file name, without ever having to pull the existing file down from the repository.  Who would have thought that stupid naming convention would help some day?


Estimates and C.I. of percentiles for a survival function

Question: In S-plus estimates of percentiles for a survival function can be obtained using the qkaplanMeier function (on the results of a call to kaplanMeier) like that:
kfit <-kaplanMeier(censor(TIME,STATUS)~1)
qkaplanMeier(kfit, c(.25, .5, .75))

How can I do this in R?. Those functions do not exist anymore. What if I also want the (asymptotic) confidence intervals for the percentiles? How can I get the mean for the survival time?
Answer: The CRAN task view on survival analysis says:
Kaplan-Meier:
The
survfit
function from the
survival
package
computes the Kaplan-Meier estimator for truncated and/or censored data.
rms
(replacement of the
Design$^\dagger$
package)
proposes a modified version of the
survfit
function.
The
prodlim
package implements a fast algorithm and some features
not included in
survival.
Various confidence intervals and confidence bands for the Kaplan-Meier estimator
are implemented in the
km.ci
package.
plot.Surv          of package
eha
plots
the Kaplan-Meier estimator.
svykm
in
survey
provides a weighted Kaplan-Meier
estimator.
nested.km
in
NestedCohort$^\dagger$
estimates the
survival curve for each level of categorical variables with missing data.
The
kaplan-meier
function in
spatstat
computes the Kaplan-Meier estimator from histogram data.
The
MAMSE$^\dagger$
package permits to compute a weighted Kaplan-Meier estimate.
The
KM
function in package
rhosp
plots the survival
function using a variant of the Kaplan-Meier estimator in a hospitalisation
risk context.
The
survPresmooth
package computes presmoothed estimates of the main quantities used
for right-censored data, i.e., survival, hazard and density functions.

$^\dagger$ Respective packages have now been removed from CRAN repository.
Answer: The other answers are correct, but needlessly complicated, IMHO. It's actually very easy to do this in R:
# We need the 'survival' package
library(survival)

# Estimate some sample data
n = 1000
x = rexp(n)
status = rep(1,n)

# Fit model
kfit = survfit(Surv(x, status) ~ 1)
kfit

The output is:
Call: survfit(formula = Surv(x, status) ~ 1)

       n   events   median  0.95LCL  0.95UCL
1000.000 1000.000    0.720    0.670    0.777

So the estimate of the median is 0.72, with a 95% confidence interval of 0.67–0.77. (The theoretical value for these data is qexp(.5) ≈ 0.69). If you want to extract the numbers for later use, or estimate other percentiles, you can use:
# Estimate and CI for the median
quantile(kfit, 0.5)

Change the 0.5 to calculate point estimates and CIs for other percentiles (e.g. to 0.75 for the upper quartile).
To estimate the mean, you can use print(kfit, print.rmean=TRUE), but do read ?print.survfit beforehand. What you're asking for may not make sense if you have censored observation times.
Answer: The bootkm() function in Hmisc provides bootstraped estimate of the probability of survival, as well as the estimate of the quantile of the survival distribution (through either describe or quantile applied onto the result of bootkm).


Why must a normed space homeomorphic to a complete metric space be complete?

Question: Why must a normed space $X$ homeomorphic to a complete metric space $Y$ be complete?
I've solved this in the case where Y is a normed space (considering open balls gives Lipschitz equivalence), but am not sure how to proceed in general. Can we use an adapted open-balls argument even when Y isn't normed?
Maybe there's an equivalent condition for completeness that will come in useful? In a normed space we can use (absolutely convergent)$\implies$(convergent) for series, but this won't work in a metric space.
I've tried using an explicit homeomorphism $f:X\rightarrow Y$ and taking pullbacks and pushforwards along $f$ of a Cauchy sequence in $X$, but without success.
Many thanks for any help with this!
Answer: I don't know if this works, but some thoughts:
It is well known that a metric space $(X,d_X)$ can be homeomorphic to a complete metric space $(Y,d_Y)$ and the metric $d_X$ on $X$ is not complete. E.g. $X = (0,1)$ in the standard metric, compared with $Y = \mathbb{R}$ in the standard (complete) metric.
However, for such spaces $X$ it is the case that they are a $G_\delta$ in their completion (they are what is known as topologically complete).
Every normed space $(X,\|\cdot\|)$ has a normed completion $(\hat{X},\|\cdot\|)$ in which $X$ embeds isometrically. So we know from the above that $X$ is then a $G_\delta$ in $\hat{X}$. We want to show that these spaces are actually equal.
So maybe it is possible to show that a dense $G_\delta$ linear subspace of a Banach space is the whole space?
Added (after comments by Sean Eberhard)
This is indeed the case: $X$ is a dense $G_\delta$ in $\hat{X}$, so if $y \in \hat{X}\setminus X$, $y + X$ and $X$ are both dense $G_\delta$'s and their intersection is empty (otherwise $y$ would a difference of members of $X$ hence in $X$). This contradicts Baire's theorem, so such a $y$ cannot exist and $X = \hat{X}$, and thus is complete already.
Comment: If $X$ is a proper dense $G_\delta$ subspace then so is $x+X$ for any $x\notin X$. But $X\cap(x+X)=\emptyset$, a contradiction to Baire's theorem.
Comment: That's true. If a subspace is dense $G_\delta$ then so is any translate, but then taking an intersection contradicts Baire's theorem.
Comment: What intersection do we take?
Comment: I just found that the Banach-Kuratowski-Pettis theorem applies: this says that if $X$ is a non-meagre topological group and $A$ is a subgroup that is a Baire space, $A$ is either meagre in $X$ or clopen in $X$. But this seems overkill, so anything simpler would be welcome.
Comment: Nice answer!  And @SeanEberhard: Nice observation!  I had also got as far as realizing that $X$ was a dense $G_\delta$ in its completion, but couldn't see how to proceed.
Answer: This question is not true:
$\mathbb{R}$ is homeomorphic to $(0,1)$. $\mathbb{R}$ is a complete metric space whit Euclidean norm and $(0,1)$ is a normed vector space which isn't complete!
Comment: $(0,1)$ is a vector space?


how to distribute load in group of activemq brokers

Question: I am trying to find a way to load balance requests to a group of similar configuration activemq brokers.
Suppose, i have 3 activemq brokers(A, B, C), each having (say) two queues (X,Y) operating.

Every activemq broker has same queues ie. X & Y.
Every activemq broker queues have a dedicated consumer. which consumes messages only from their respective broker's queue.
Now, I want to load balance requests to my 3 queues load balanced in round-robin. i.e. the 1st request should go to Queue A, then next request to queue B and then next request to queue C and so on.

Any guidance please.
Answer: Check out ActiveMQ's Networks of Brokers feature:  http://activemq.apache.org/networks-of-brokers.html.  I'd use as much of ActiveMQ's built-in functionality as possible before coming up with any custom round-robin code of your own.


Can I add select/option data type to field type in apostrophe cm widget?

Question: I have a column widget that I'm trying to create a prepopulated dropdown list that a user can choose from that will correspond to a value of bootstrap class names "col-md-6" etc.
<code>addFields: [
    {
      type: 'select',
      name: 'column1width',
      label: 'Column 1 Width',
      contextual: false,
      options: {
         name: '1 column',
         value: 'col-md-1'
       },
       {
         name: '2 column',
         value: 'col-md-2'
       }
    },
</code>
Answer: I figured out the answer
<code>  type: 'select',
      name: 'column1width',
      label: 'Column 1 Width',
      contextual: false,
      choices: [
        {
          label: '1 Column',
          value: 'col-md-1'
        },
        {
          label: '2 Column',
          value: 'col-md-2'
        }
      ]
</code>
Comment: Yep! FWIW, we often use snippets to speed up creating schemas. If you're using Atom or VS Code you can find those here:

https://atom.io/packages/apostrophe-atom
https://marketplace.visualstudio.com/items?itemName=punkave.apostrophecms-vs-snippets
Comment: I downloaded the snippets but wasn't sure how to get them to show up in atom. Also documentation isn't very clear how to set default value for select


reed strength for clarinet Vandoren M 13 mouthpiece

Question: For the  fullest sounding tone, what read strength would be best recommended for the Vandoren M 13 clarinet mouthpiece
Answer: Reed strength is more of a personal preference in terms of sound, but according to the Vandoren website, they recommend anywhere from a 3 1/2 to a 5 in reed strength for that mouthpiece.


Slope of a line in 2D Co-ordinates

Question: Does the slope depend on how the y of a straight line changes or on both x and y?
For example, A straight line 2x - y = 0 passing through origin has a slope m = 2.
Now, when
x = 1  |  y = 2
x = 2  |  y = 4
x = 3  |  y = 6

It looks like the value of y is increasing by 2, which is confusing me because m = 2.
In case 2, A straight line 2x + 3y = 18 has slope m = -2/3
and, when
x = 1 | y = 5.33
x = 2 | y = 4.66
x = 3 | y = 4

In this case it looks like the y is decreasing by -2/3
so, does the slopes of a straight line only effect y?
Answer: The slope of a straight line here is the change in $y$ divided by the change in $x$.  Your equation can be written as $y = 2x$ and, as your numbers show, each increase of $x$ by 1 leads to an increase in $y$ by 2.
Draw the lines $y = 2x$ and $y = x$ on co-ordinate axes with the $x$-axis horizontal and $y$-axis vertical, and you will see that the line with a larger slope is steeper.
Added later: On your second added question, you have correctly worked out the slope as close to $-2/3$. But this is not just the change in $y$.  If you had only the data
x = 1 | y = 5.33
x = 3 | y = 4

then the change in $y$ would be $-1.33$, but the change in $x$ would be $2$.  You have to divide one by the other. So the slope would be $-1.33/2 \approx -2/3$, as before.
Answer: The slope of the straight line is only affecting y in your case because you are deciding to measure y and not x, i.e. you are setting the values of x and calculating the values of y from there.
If you were to draw y = 2x while measuring y (that is, you are setting the values of y and calculating the values of x) you would find that x increases by 1/2 (i.e. 1/m).
y = 1 | x = 0.5
y = 2 | x = 1.0
y = 3 | x = 1.5

So in actuality m effects whichever value you are calculating, as you are setting the other value yourself (you're affecting the other value)

Slope of a line in 2D Co-ordinates


How on earth does he debug a running application like this, and more importantly, how can I?

Question: "Debugception!"
You may notice that within the first 15 seconds of this YouTube video (from 1:01:01 to 1:01:16), Markus Persson (aka "Notch", creator of Minecraft) has somehow managed to save/update an application and attach a debugger to it while it was already under the process of being debugged, supposedly all with a simple keyboard shortcut. The previously coded application somehow magically became the newly edited one, and seemingly without relaunching it or spawning a new process... It's possible that this is just some form of locally remote debugging, but something about it just doesn't seem quite right.
I've spent several days Googling and asking around on how he was able to do this, yet to no avail. I've found no such option under Eclipse preferences, and whenever I try to save & debug an already running application, it simply launches a separate instance of the newly updated application, side-by-side with the older, outdated one.
Am I missing something? How was this possible?
How was he able to utilize such an astounding, powerful debugging feature?
Thanks in advance!
Update
Okay, so this appears to be a standard feature specific to Eclipse.
Coming from a background in NetBeans and Visual Studio, I'm astounded that this doesn't seem to exist elsewhere (or at least in NetBeans!)...
Comment: This has been a feature of Netbeans for years - it is in the debug menu "Apply code changes".
Comment: For Eclipse it's as simple as altering something in the source code and saving after having launched in debugging mode
Answer: This is a built-in feature of Eclipse. If you edit a method while the program is running in debug mode, it will compile the new method, and replace the old method with the new version. If some thread was already running that method, it will jump back to the beginning (AFAIK; this might only happen when the program is paused).
You don't need to re-launch the program or set any special preferences. Just edit and save, and the magic will happen.
Eclipse can't always figure out how to merge your changes into the running program - usually if you changed anything outside a method body (including the method's parameters or return type). In this case, you will get a warning dialog, with the option to stop the program, restart the program or ignore the changes.
Comment: The Debug view will show a warning of some sort if you've made changes that couldn't be hotswapped.  It depends on what you've changed, and where the code is paused/running at the time - not all changes are compatible.
Comment: Strangely enough, I've tried doing this already and it didn't change anything in the running application... But I tried it again just now on another project, and it worked! Thanks!


Autodialing software?

Question: I need to have a computer automatically call my office and maintain the telephone connection for at least 2 minutes.  The reason for  this, is I've contracted with a squirrelly VOIP provider that I can expect will have downtime about 1% of the time (and not bother to warn me).  Is there software that can operate in either of the following configurations:

laptop with modem connection to plain old telephone network (which I could connect to home telephone line;
App for an Android phone that would automatically dial at the same scheduled time each day?

This actually ends up saving me about 5 minutes each day that me, or member of my staff, would spend calling in from a cell phone, and adding it to a log.
Comment: It would be useful to know what operating system(s) you're talking about, because I doubt there's any solution that applies to all of them.
Answer: You could try Dial Engine Pro using a script and running it from a scheduled task: http://www.phonedialerpro.com/#Engine
Answer: Warvox wasn't designed for this, but I think it could meet your requirements.
It's a wardialing tool, but instead of using a basic pots modem, it uses an IAX trunk.
It has logging and reporting facilities, which could help you to graph downtimes.
iWar is more basic, but maybe more scriptable. MySQL logging, modem & voip support.
Answer: You're doing it the hard way for sure. If you have Cisco equipment, you can use IP SLA to generate voice streams and measure jitter, latency, MOS score, etc.
Comment: and Juniper has an equivalent called RPM that works fairly well, thought its not as in depth, IMHO.

Autodialing software?


Angular 8 ctrlKey and metaKey equivalent?

Question: I have a web application written in Angular 1.x which allows the user to ctrl-click (or cmd-click on Mac) on an anchor link to open it in a new tab. An unmodified click changes the DOM content instead of reloading the page at the new path. The Angular 1.x code looks like:
{{::e.title}}

And in the Angular 1.x controller:
if (e.ctrlKey == 1 || e.metaKey == 1) {
    // allow page to be opened in a new tab
    return false;
}
e.preventDefault();
e.stopPropagation();
...continue by doing ajax and DOM replacement instead

Now the application is being upgraded to Angular 8, but the Event class does not have ctrlKey or metaKey. Is there an alternate way to detect these two modifiers in Angular 8?
Comment: it not `Event` class but `KeyboardEvent`, then you should have access to your information
Comment: @Yanis-git you're absolutely right. All I needed to do was swap out Event for KeyboardEvent and then I had the attributes and it works as desired. You should put that as an answer so I can accept it.
Answer: We have ctrlKey and metaKey in MouseEvent. If you receive click event, it is a MouseEvent, so you will have access to hem. Both of them as Boolean.
see this simple example:
https://stackblitz.com/edit/angular-cpqrjr


Qual a diferença entre top e margin-top no css?

Question: Este é um assunto que sempre me confunde bastante. Qual a real diferença de ambos? Quando utilizar um e outro? Geralmente vou pela tentativa e erro, mas preciso entender como isso realmente funciona.
Comment: Ainda sobre o tema (ao menos funcionou para mim). Com a position: absolute, as coordenadas (top, left, right, bottom) funcionam bem.
Answer: Cada elemento no HTML sempre é uma caixa.
Essa caixa tem 4 valores de área:

A primeira, mais interna, é a do próprio elemento em si. No caso de uma imagem, é a própria imagem.
A segunda, é a chamada padding, em geral, ela é transparente e pouco usada. No caso de imagens, é algo como a parte interna da moldura.
A terceira, é a chamada margin. É a moldura em si do quadro da imagem.
E por ultimo, mas não menos importante, temos a border. É a parte mais externa da caixa.

Em css, você tem como manusear as propriedades de cada uma das partes da caixa com as propriedades:

padding;
margin;
border;

Agora, quando se trata de propriedades como top, bottom, left e right, você está alterando a posição do elemento, e assim a posição base da caixa do elemento.
Se você usa o Chrome, você pode clicar com o botão direito numa imagem, e clicar em Inspecionar elemento. No canto direito, você tem uma imagem da caixa do elemento que você está inspecionando.
Comment: Mas por que top, bottom, left e right nem sempre funcionam? Estão diretamente ligados ao position?
Comment: `Position` é uma outra forma de determinar a posição.

Explicando:
 - Position determina o `tipo` de posicionamento de um elemento. Se o elemento é um bloco, se é um elemento inline, é nesse atributo que você determina isso.
 - `Top`, `bottom`, `left` e `right` são atributos ligados à margin.

Você pode ler mais sobre posicionamento [neste link](http://www.w3schools.com/css/css_positioning.asp).
Comment: Valeu! Entendi aqui:D
Answer: O "top" posiciona o elemento em um coordenada, o margin-top usa como referencia os "irmãos" do objeto em questão, apenas dando um espaço.


Patching executable to avoid crashing

Question: I have got a minigame.exe which crashes at some point inside the game. It does not show any error message and it just says Not Responding. I am using Win 7. I want to identify the crashing point and try to fix the games problem. I think the problem might be caused due to a specific DLL imported by the executable. However, I have no clue about how to find out that specific assembly line and try to patch the executable with OllyDBG.
Answer: With the information given, this answer would need a full tutorial style, which is considered as too broad for this site. But the first step, finding out what type of crash it is and where it occurs can be explained.
I'll use WinDbg as the debugger, since I'm not familiar with OllyDbg. It is is part of the Debugging Tools for Windows and it's freely available. Install the versions, x64 or x86, that matches minigame.exe.

Start WinDbg, use the correct bitness
Run minigame.exe under WinDbg (File/Open executable). It will stop at the initial breakpoint.
Set up the symbols, at least .symfix c:\debug\symbols and .reload. This will download information needed to construct the callstack.
Continue running the application with g
Reproduce the issue / wait until it crashes
When WinDbg stops,

create a crash dump with .dump /ma c:\debug\minigame.dmp so you can analyze it later, e.g. for asking questions here, so that you needn't reproduce the bug again.
get information about the exception with .exr -1
switch to the thread that caused the exception with ~#s
look at the callstack with k

Now you should have a better understanding of the crash, perhaps enough to apply a patch, maybe not. At least it's a better starting point for further exploration.
Comment: Is not there any way to do so in the x64_DBG? When I run the WinDBG64 it says debugee is busy and it also does not show the windows for registers, memory, and ... Even opening registers window will not show the registers. It is not really a user friendly or even comfortable debugger to work with.
Comment: Yes, WinDbg is quite command oriented. Its GUI is not really intuitive, neither are the commands. But it is the most powerful debugger available. You can potentially do the same in OllyDbg, but as I said, I don't know how to use it.
Comment: Is minigame.exe available for free? Perhaps it applies anti-debugging techniques
Comment: No, it is not a free game. I see GetThreadContext stuff in it.

Patching executable to avoid crashing


Definition of ordinary differential equation

Question: Is a differential equation ordinary if it only contains derivatives with respect to one variable, even if the function has multiple variables?
For example the function y=f(x,t) and the differential equation
$\frac{d^2y}{dx^2}+2\frac{dy}{dx}=4$ would that be ordinary are partial?
Does the question not make sense because if you already know how many (independent) variables the function (in this case $y$) depends on, then it wouldn't be a differential equation because the function isn't unknown?
Answer: An ordinary differential equation is an equation which involves derivatives of one or more dependent variables with respect to a single independent variable.
Ex: $\frac{d^2y}{dx^2}+\frac{dy}{dx}+2=0$
A partial differential equation is an equation which involves partial derivatives of one or more dependent variables with respect to more than one independent variables.
Ex : $u_{xx}+u_{yy}=0$
Answer: In mathematics, an ordinary differential equation or ODE is an equation containing a function of one independent variable and its derivatives. The term "ordinary" is used in contrast with the term partial differential equation which may be with respect to more than one independent variable.


Is there a way to guesstimate how long it will take me to learn a specific piece?

Question: I was wondering if there was somewhere a list of classical pieces along with the amount of "unit of time" usually needed to master it.
The "unit of time" being adjusted using where you are now and how long it took you to arrive there...
Does such a directory exists somewhere? and if not, do you think it would make some sense to build one?

Eg, in my case, I've started the piano 3 month ago, and I'm now able to play in a quite satisfactory manner Bach's Invention n°4 (BWV 775). I don't know whether I'm slow or fast, but it certainly says something about my general abilities, my dedication, etc.
I'd be curious to know how many year it would take me to play a specific piece, say Bach's concerto n°1 in D minor (BWV 1052)
(I don't expect someone to be able to say "you'll be there in December 2015", but right now, honestly, I've absolutely no idea ... will it be next year? in 10 years? never ?)
Answer: I am sorry for what I'm sure you'll deem to be a very unhelpful answer, but the only way you can come up even with a wild guess is by doing the following:

Learn the most difficult page of the piece to your satisfaction.
Multiply the time taken to perfect that page by the number of pages

I will say that, for a given piece, you are likely to learn it more quickly if you're more experienced.  How much more quickly?  Well, here are a few things that will probably vary with it:

Familiarity with the composer's other pieces
Familiarity with other artists in the time period
Sight-reading ability
Memorization capacity
Exactly where you'll have gone once you've "gotten there" (are you performing it for your family? A panel of professional pianists? critics? Simon Cowell? a room of tone-deaf mimes?)
Practice schedule

In summary, I don't know of the existence of any such database.  I'm sure that if it existed, you'd be able to draw some very interesting correlations and even come up with a fairly accurate model to answer your question. But over the internet, and especially with the information given, we can take a guess, and we might even get it right (I'm betting on 1 year if you're really really dedicated), but that guess will be nearly entirely baseless.
EDIT
In response to your comment:
You are, broadly speaking, correct in your assertion that your technical skill will improve as you learn the piece.  After all, you must have some minimum amount of skill to play a passage, and that skill wasn't there before.  But technical skill isn't usually the limiting factor. A large part of learning music isn't building skill, but memorizing the music (I call this phase of learning the "what the hell note is that?" phase).  After all, pressing keys is easy.  Remembering which keys to press for the next 5 minutes of playing is hard.  That's why I've been playing the piano for over 15 years, but it still takes me a good month of solid practice before I learn the notes to a new piece.
Of course, the notes alone don't make music; if it did, we'd listen to MIDI tracks instead of musicians.  We need to polish it to sound musical.  This phase, which I call the "this sounds like crap!" phase, is limited by your ears.  You will always, always find something to improve on.  No exceptions.  How long you polish the piece depends on how good you want it to sound.  If it's good enough, then you can just quit and move on to the next piece.  For me, before I play a solo piece for any serious musician, I take almost a year to work on it.  But that's me, with my practice schedule.  Some professionals know exactly what they're doing; they'll learn the piece in half a week, and spend the other half getting it ready for their peers.
The reason professionals can do this faster isn't because they've played really really hard pieces.  They can learn faster because they've played more pieces.  Over their schooling alone, they'll have played hundreds of pieces of music, and over their lifetime, easily thousands.  The quantity of music that you play will contribute to your composite skill far more than the difficulty of the pieces.
Which brings me back to my point.  Learning a difficult piece isn't a trivial task.  Memorizing the notes is.  So if you're just memorizing the notes to bang out, then you're limited by how fast you can memorize.  If you're going to polish it afterwards, then you're done whenever you're done polishing.  Either way, it's not a question that we can answer.
Comment: @Brann: If you're a total beginner, you shouldn't start with a very difficult piece.
Comment: @Brann: Absolutely! The issue with this is that in order for that population average to be applicable to anybody in particular, you'd need to control pretty heavily for covariances (age when you started learning, time spent practicing every day, skill of your piano teacher, etc.).
Comment: @Babu: Because if you start out with a difficult piece, it is a high risk that your motivation drops because it takes too long before you master it. A simple piece does not necessarily have to mean a boring piece...
Comment: I don't understand your answer. Right now I'm a total beginner. If I was to start learning a very difficult piece, I guess the "hardest" page would take me years to learn, and then the following ones would take only days (because I've built up a lot of skill learning that hard page that I can use on the other ones)
Comment: well, I didn't want to start a lengthy discussion on the verb "play" in "When will I be able to play this piece". One might argue you never play anything properly, and another one that even hitting the keys in a random fashion is playing. Thousands of people are learning the piano every year. I guess there should be some "norm", and that every specific piece will usually (in a Gaussian sense) be "achievable" after x years of practice.
Comment: @awe: Why not start with a difficult piece?  If that's what you want to learn, what would the harm be?
Comment: @Babu : agreed. that why I'm asking if there's somewhere a database condensing all this. certainly they have been hundreds of people in my exact situation before (same age, same dexterity, same motivation, etc), and with enough data, one could certainly make statistically valid assumptions !
Comment: @Brann re: `Why not start with a difficult piece?` I learned piano on my own (after playing other instruments) as well. Starting with simpler (intermediate) pieces that I actually enjoyed allowed me to develop technique, muscle memory, and common fingering patterns, and get to where I could play and emote accurately at speed. Then moving to increasingly difficult pieces allowed me to build on this foundation. I'm confident that starting slow and developing proper technique helped me learn faster in the long run, and to reach a higher level of proficiency sooner.
Answer: Yes, but not until you've gotten a little more experience. For instance, I know that it will take me approximately 15-20 hours to learn a Chopin etude of medium difficulty (as Chopin etudes go.) I also know that it takes me about 100 hours to learn a concerto of non-obscene difficulty (Grieg, Schumann etc...)
I recommend keeping a practice journal for a while. Be specific about what you spend the most time on. It'll help you a lot when you try to "guesstimate" how long something's going to take you.
Also, the amount of time it takes you to learn pieces of a given difficulty will obviously change as you get better. Keep that in mind too.
Edit
Willard Palmer wrote a book containing a comprehensive list of piano pieces and their corresponding difficulty. I sometimes use that to figure out how long a piece will take to learn, by comparing it to pieces, of comparable difficulty, I have learned.
Answer: What does it mean to "master" a piece?  Take one of the first pieces you ever played.  Presumably you consider to have mastered it.  Is your rendition indistinguishable from that of your teacher when recorded and played side by side?
You say that you are able to play in a "quite satisfactory manner" Bach invention number 4.  Well, I assume you mean the two-part inventions which I cannot find at the moment, so I have to deal in generalities.
Does that mean that you can record this invention and, when listening, can follow each of the voices easily, and each voice is consistently played and articulated as if it were played by a separate player?  Is your choice of articulation and attack consistent enough that the listener will not confuse the voices when they are actually crossing?  Is the bass part executed with a dependable and consistent articulation (usually a nice portato with distinct notes that don't sound hacked off), carrying the piece reliably?  Where the voices happen to run in or across a unison, have you figured out strategies for how to make it audible that there are still two voices?  (Sounds contrived but I am actually doing the Air from the Bach orchestra suite 3 on free bass accordion right now, and when a voice played leggiero runs through a long note from the other voice I cannot interrupt the tone but cannot do nothing, so there is a subtle but audible short bellows impulse marking the pass-through voice, obviously something that calls for a different strategy on a percussive instrument like a piano).
Pieces like that have a tendency to come back and haunt you, making you feel less and less satisfied the longer you work on them.  But then as your skills grow, so does your hearing and work ability, so it often makes sense to leave them behind and come back at a time where you have more focus for the details available.
How much time should you invest in any piece?  I recommend recording it and seeing where you can figure out things to improve.  When you are not satisfied but cannot figure out what you could be doing better, you might either ask your teacher or move on.  That's when your time is less likely to be spent well on a piece than on new ones.
That's not only a function of how much you are improving on your rendition, but also of how much you are improving your hearing.  So it is hard to say just how long it will take you for any given piece until it makes sense to move on, and how much progress that entails.


Using UE4 with Visual Studio 2017

Question: I recently did some cleaning of my drives. I decided to install visual studio 2017 after cleaning the drives up. I have been trying to continue work on my old UE4 project using the engine pulled from GitHub. I tried rebuilding the project with VS2017 which I know is not fully supported yet. I did run into quite a few problems, including the missing corecrt.h files. I reinstalled the Windows SDK to fix this.
The current problem is a new missing file called windows.h, and I believe it is missing due to the build tools looking for the wrong version of the SDK. I was wondering, has anyone else successfully integrated Visual Studio 2017 with their UE4 project after running into similar problems?
-- Edited due to poor grammar.
Comment: One other detail. The errors seem to be centered around the ShaderCompileWorker project within the solution. It won't allow me to build the editor from the source code collected from github. I ran setup.bat and generateprojectfiles.bat -2017, but it does not affect the issue. I will continue looking into this.
Comment: Here is a link to a person with a similar problem in which he was forced to use temporary fixes for these issues.https://answers.unrealengine.com/questions/547647/packaging-with-visual-studio-2017-rc.html
Answer: As I know Version 4.15 supports both Visual Studio 2015 (default) and Visual Studio 2017.  If you are building the Engine from source code, you would want to open a command prompt after running Setup.bat and run the command GenerateProjectFiles.bat -2017. This will give you a Visual Studio 2017 solution for the Engine.
To use Visual Studio 2017 for projects, you can set your preference for which version projects use by going to Edit -> Editor Preferences -> General -> Source Code  and choosing Visual Studio 2017 in the Source Code Editor setting.
Answer: If regenerating the Engine's VS project files doesn't help. Try regenerating your own UE4 project's VS project files.
With Visual Studio and UE4 closed, find the .uproject file, right click and select Generate Visual Studio project files.
Open the solution, make sure your UE4 game (e.g. MyProject) under the Games folder is set as the StartUp project (right click, Set as StartUp project), then try a compile.

Using UE4 with Visual Studio 2017


Remove certain character of string PHP

Question: I need to remove the third character of a string. Here's what I tried.
<code>$my_string['2'] = "";
</code>
This worked find, but when I tried to put this variable in a MySQL query, it returned errors.

What is the best way to remove a certain character (character 3 in my case) from a string?
Comment: what query? what errors ? - crystal ball in the shop
Answer: Try out substr_replace.
For example:
<code>$new_string = substr_replace($my_string, '', 2, 1);
</code>
Answer: Use an integer as index, not a string:
<code>$my_string[2] = '';
</code>
Comment: This will thrown a warning: Cannot assign an empty string to a string offset

Remove certain character of string PHP


Interpreting logistic regression output

Question: Suppose I have a logistic regression output as follows.
Coefficients:
                 Estimate   Std. Error z value  Pr(>|z|)
(Intercept)     -5.8700887  0.0506436 -115.91   <2e-16 ***
f1               0.0511820  0.0005718   89.51   <2e-16 ***
f2              10.8470102  0.0992892  109.25   <2e-16 ***
f3               0.3762872  0.0108390   34.72   <2e-16 ***

In this case, which variable play the most important role in the model? Is it f1 (the lowest coefficient) or f2 (the highest one)?
Comment: Related: [Interpretation of R's output for binomial regression](https://stats.stackexchange.com/q/86351/).
Answer: There is no simple answer to that, as long as you don't have normalized predictors. If one of the predictors is a length, then the estimated coefficient will change dramatically, depending on whether you entered the length's in centimeters, inches, meters, kilometers or astronomical units. At the same time, the "importance" of the predictor does not chance depending on units.
So you might check if you want to normalize your predictors so that they become more comparable. After that, the size of the coefficient is the number of standard deviations that go into the model and that can be regarded as one possible definition of "important role".
Comment: Suppose I normalized the input (f1,f2,f3) to unit vectors already. In this case, does it mean that "f2" is the most important one, i.e. if changing each variable just 1 unit, the change on f2 will have the highest impact to the predicting value?
Comment: Yes, a one standard deviation change in `f2` will have an impact of 10 points on the logistic scale while `f1`and `f3` will have less then 1 point in the logistic scale. Do not expect coefficients in the neighborhood of 10 in standardized predictors in real life usage, though.
Answer: You might also consider dominance analysis or relative weights based approaches.
These approaches do not require a manual rescale but also do not offer quite the same information as the approach above.  They comment on the percentage of the McFadden (or Estrella) pseudo-R2 is explained by each predictor.
This can make the results easier to compare across predictors but, again, provides different information (no longer comments on changes in log-odds over the predictor; now refers to amount of information in the binary dependent variable is attributed to each predictor).
Also a handy online calculator for the relative weights method is available.

Interpreting logistic regression output


How do I get the Vendor and Product strings in case of a HID device on Windows?

Question: I need to get information about the idProduct and idVendor of a plugged in HID device on my Windows machine. How do I get the USB_DEVICE_DESCRIPTOR for a given HID device?
I searched the internet, but I only found examples of devices being queried using the WinUSB library and getting the USB_DEVICE_DESCRIPTOR. My understanding that I cannot use WinUSB for plugged in HID device.
What do I need to use for a HID device then?
Comment: Look at the [HID Support Routines](http://msdn.microsoft.com/en-us/library/windows/hardware/ff538865%28v=vs.85%29.aspx), while there is not a specific device descriptor routine there should be enough to get information that you need, for example [HidD_GetAttributes](http://msdn.microsoft.com/en-us/library/windows/hardware/ff538900(v=vs.85).aspx) or one of the other functions to get product or serial strings.
Answer: If you're using HidLibrary, you can get a device like this:
<code>_device = HidDevices.Enumerate(VendorId, ProductId, UsagePage).FirstOrDefault();

if (_device != null) {
    _device.OpenDevice();
    string product = GetProductString(_device);
    string mfg = GetManufacturerString(_device);
}
</code>
With the latter two functions defined like this:
<code>    private string GetProductString(HidDevice d) {
        byte[] bs;
        _device.ReadProduct(out bs);
        string ps = "";
        foreach (byte b in bs) {
            if (b > 0)
                ps += ((char)b).ToString();
        }
        return ps;
    }

    private string GetManufacturerString(HidDevice d) {
        byte[] bs;
        _device.ReadManufacturer(out bs);
        string ps = "";
        foreach (byte b in bs) {
            if (b > 0)
                ps += ((char)b).ToString();
        }
        return ps;
    }
</code>