Is there an analogue to the "Delta" symbol for ratios?

Question: A capital delta ($\Delta$) is commonly used to indicate a difference (especially an incremental difference). For example, $\Delta x = x_1 - x_0$
My question is: is there an analogue of this notation for ratios?
In other words, what's the best symbol to use for $[?]$ in $[?]x = \dfrac{x_1}{x_0}$?
Comment: @Henry if you'd like some context, I'm using this to express changes in a product in terms of changes of its individual terms. The reason I'm using ratios is that the product of ratios is the ratio of the products.
Comment: What you have there is $1+\dfrac{\Delta x}{x_0}$, i.e. one more than the proportionate change, which tends to $1$ as the change gets smaller.  I suspect that in most cases you may actually want the proportionate change itself.
Answer: The best symbol to use is $\exp\Delta\log$:
$$\exp\Delta\log x = \exp(\log x_1-\log x_0) = \frac{x_1}{x_0}.$$
The point is that this operation isn't "qualitatively different" from $\Delta$, so it may be reduced to $\Delta$. So far, I haven't used any new symbols but if you want some multiplicative new creative symbols, see e-percentages and units of evidence:

http://motls.blogspot.com/2010/01/exponential-percentages-useful-proposed.html
http://motls.blogspot.com/2010/08/units-of-evidence.html

There is no compact symbol for $\exp\Delta\log$. If you want an ally who would endorse the idea to introduce such a symbol, you may count on me. What about $\Delta^\times$?
Comment: Dear Theo, $\log(-1)=\pi i$ and $\exp(\pi i)=-1$: is there any problem with that? Something's changing multiplicatively but changing sign would be a discontinuous process in the real numbers, anyway, so it only makes good sense in the complex realm. Concerning the notation, not sure whether I understand which $D$ you mean.
Comment: What if $x_1$ and $x_0$ are negative? Also, $\Delta^{\times}$ doesn't seem particularly good, as it mixes the D in difference with multiplication.
Comment: Dear Luboš, 1) no, no problem with that, but it might be worth pointing out. The process is not really discontinuous, but simply undefined at $0$, as it should be. 2) The $\Delta$ is a Greek D(elta) for the D in difference.
Comment: Dear Theo, what I mean by "discontinuous" is that there is no continuous $f(x)$ such that $f(0)$ is positive and $f(1)$ is negative so that $f(k)/f(0)$ which is $\Delta^\times x$ at some moment would be well-defined for all $k$ between $0$ and $1$. That's a warning sign - if one uses $\Delta^\times$ for things that change sign, it could be an unnatural thing that can go awry at moment... I know that $\Delta$ is the Greek counterpart of $D$ but I think it's a good idea to distinguish them. Did your $D$ mean $\Delta$?
Comment: Thank you for the input, I was hoping there was something more compact than $\exp \Delta \log$ and while $\Delta^{\times}$ has some appeal it may confuse some readers because of the association of $\Delta$ with differences. I think I might just end up switching all the expressions to log-space or coming up with some other symbol (perhaps an unambiguous placement of $\div$?)
Comment: How about a Obelus-Delta... a delta with a dot inside and a dot below the base?  Or perhaps a Q-Delta... a delta with a q-like tail coming out of the bottom (which is a little easier to write).  (Can someone show how to form these symbols using the math markup?)
Answer: Not entirely standard, but in Peter Henrici's discussion of the (justly famous) quotient-difference (QD) algorithm in the books Elements of Numerical Analysis (see p. 163) and Essentials of Numerical Analysis (see p. 155), he defines the quotient operator as
$$Q\,x_n=\frac{x_{n+1}}{x_n}$$
in complete analogy with the (forward) difference operator $\Delta$.
Henrici's a pretty sharp mathematician, so I wouldn't mind borrowing notation from him if I were in your shoes...

Here's a screenshot of the relevant page of the first book (sorry, I don't have a digital copy of the other book):
Answer: The greek letter $\Delta$ stands for Difference
So the symbol for the multiplicative increase of variable should be related to letter $Q$ in greek which is the ancient Qoppa letter and stands for Quotient


Definition of Productive set

Question: I don't understand the definition of Productive Set in the Cutland's Computability book.

DEFINITION: A set $A$ is productive if there is a total computable function $g$ such that whenever $W_{x} \subseteq A$, then $g(x) \in A$  \ $W_{x}$. The function $g$ is called a productive function for A.

I don't understand what is the domain of the function $g$. Could $g$ be defined as $g:W_{x} \rightarrow A$ \ $W_{x}$?
Comment: What is $W_x$ ?
Comment: @Holo That's the standard notation for the $x$th recursively enumerable set in some fixed "reasonable" enumeration (the specific choice of enumeration - essentially, a choice of universal Turing machine - never really matters).
Comment: @NoahSchweber thanks
Answer: The domain of $g$ is all of $\mathbb{N}$ - that's the case for every total function. The point is that $g(x)$ is defined whether $W_x\subseteq A$ or not; and whenever $W_x$ is a subset of $A$, we have $g(x)\in A\setminus W_x$.
In particular, you should think of $g$ as taking as input an index for an r.e. set, not an element of some specific r.e. set $W_x$.

It might be easier to consider the "higher-type" picture: we're intuitively interested in a map $G$ from the set $\mathcal{W}$ of all r.e. sets to $\mathbb{N}$, such that $G(W)\in A\setminus W$ whenever $W$ is an r.e. subset of $A$. That is, $G$ sends an r.e. subset of $A$ to something in $A$ that that set "misses"  (and does wedon'tcarewhat on an r.e. set which isn't a subset of $A$).
Now this isn't actually what we get, since $(1)$ our $g$ is a map from $\mathbb{N}$ to $\mathbb{N}$ rather than $\mathcal{W}$ to $\mathbb{N}$ and $(2)$ more fundamentally, a $g$ witnessing productivity might not be "index-invariant" (just because $W_x=W_y$ doesn't mean $g(x)=g(y)$). But it may help convey a bit of the intuition.

Definition of Productive set


How can I fit these 3 columns into one?

Question: For a project, I have a database with some tables.
All of them are related between them. The table organization has a relationship with offer and user, etc.
However, I have some columns that only serve to link two tables together.
Take a look at the diagram. I use users_interests to link the user to his interests. Same thing for badges and group.
It doesn't really feel efficient. When I try to get the interests of a users, I must first go through requesting the user interests and from that, require the interest details.
Is there a way that I can request the interests of an user without having to go through a second table ?
https://dbdiagram.io/d/5da3f119ff5115114db53551
Answer: You can do it if you will make interests like this

id
user_id
name

but then you will lose uniqness of your interests, you will have many rows with the same name only because they connect to different users. Now db is perfectly ok according my understanding...It is as it should be
Answer: There's a couple things you should consider when looking at this question/functionality and what you're going to be doing with the data.

Do you have a unique set of interests that will remain the same or be added to,  without duplicates?
Do you need to have multiple interests for a single user?

If you answered "yes" to both of these questions, then you should leave things the way they are. You'll be able to reuse the same interests entry for multiple users as well as each user being able to have multiple interests.
If you only want one interest per user, but want to keep a "master list" (aka: lookup table) of interests, then you can move the interest_id to the users table.
If you don't care about duplicates, but you still want each user to have multiple interests, move the name column to the users_interests table.
Finally, if you don't care about duplicates and you want each user to have a single interest, move the name column to the users table.
FYI, how you currently have the tables structured will likely take up less disk space for a large amount of users.
It's unclear what you're trying to do, so I included all options. Each option has it's own set of pros and cons, and each will be required of some other project or another at some point. You might want to learn the difference and reasoning behind why you would use one option over another now, so you don't have to think too hard about it later.

How can I fit these 3 columns into one?


How to find N facorial using a For loop?

Question:
Possible Duplicate:
Function for Factorial in Python

I need to write a program in python that returns N!, without using the factorial function. I have a program written so far but I keep getting an error saying, local variable "fact" is assigned but never used. How do I use fact = 1, after it is assigned?
from pylab import *

def factorial(n):
    fact = 1

for i in range(n):
    print("i = ", i)
    fact = fact * i

print("The factorial of " + str(n) + " is: " + str(fact))

Comment: Is the indentation in your post the same as it is in your file? Try indenting the whole `for` block to be under the function definition.
Answer: In [37]: def fact(n):
    fac=1
    for i in range(2,n+1):
        fac *=i
    return fac
   ....:

In [43]: fact(5)
Out[43]: 120

In [44]: fact(6)
Out[44]: 720

Comment: Thanks alot!, this program ran the way I needed it to. Can you explain what the (2,n+1) does/mean in the the "for" loop?
Comment: @Bill lets say n is 5, then the range will return the values `2,3,4,5` one by one with each iteration, and we multiply them with `fac` in each iteration. `range(2,6)=[2, 3, 4, 5]`
Answer: I know very little of python, but you should use recursion in these example. It's very simple. Recursion is a function that calls itself
def factorial(n):
    if n== 0 or n == 1:
        return 1
    else:
        return n * factorial(n-1)

Comment: @jotape: each time you call a function, a stack frame is allocated to hold local variables, a pointer to the calling stack frame, etc.  So uncontrolled recursion could eat up all available memory.  That isn't quite what happens in Python though, since it imposes an artificial limit.  Some other languages include "tail call optimisation" though, which notes that if a function returns the result of another function call, then its stack frame won't be needed any more: the other function call can return directly to the grandparent stack frame instead.
Comment: You will run out the stack in Python pretty easily this way.
Comment: It wouldn't apply to your answer though, since you're modifying the result of the function call: the multiplication requires that the stack frame stick around the whole time.
Comment: Why? (Learning everyday)
Comment: Well, "pretty easily" is relative, but try running your code with `n = 1000` for instance. Each iteration through the function will call the function again, adding a level to the execution stack. If you put in a big number, this stack will get very high before it gets to the escape case (`if n==0 or n==1`). Python does not optimize this (called tail recursion) so it has a finite recursion depth.
Comment: Python will error out when you get a stack deeper than `sys.getrecursionlimit()` (set to 1000 on my system).  Your solution would also be problematic in languages that encourage recursion though, since you can't apply tail call optimisation.
Comment: This is a great learning example for recursion (and factorials), though!
Comment: Ok, tell me if I understood. When the function calls itself; like 1000 times; all that code (multiplied by 1000) is running at the stack at the same time?


Best way to store multiple ids in multiple columns

Question: I have a table for blogs in a production site I am developing. The users can post these blogs and filter viewership to targeted audiences based on locations, roles, and groupings of users premade by them. All of these columns will be holding multiple reference ids from other tables.
I found a lot of posts about putting multiple ids in one column in the form of a separate 1:* link table. But for my needs, I have 6+ columns that have this occurring. I understand that the logical solution is following the one above would be to make similar link tables for each of the columns, but is that the best course of action? How would this affect the performance or speed of the query to call all necessary data for this one row of data? Any insight is greatly appreciated, and I apologize if there was, in fact, a similar post that I had missed.
Edit:
"tile": "news",
"release_date": "--",
"scheduled_release_date": "2023-11-23",
"target_audience": "Only Staff",
"role_ids": "2",
"sub_role_ids": "4,5,7",
"region_ids": "16,2",
"district_ids": "6,207,55,94",
"campus_ids": "15,62,2699,483",
"plan_ids": "28,84,3",
"group_ids": "94,32",
"creator_ids": "Erika"

An example row of what might be found in the table.
Comment: Perhaps you could share an example?  *In general* one column does indeed contain one value for any given row.  If you have a many-to-many relationship between two tables then you would introduce a third table between them to maintain that relationship.  What have you tried and what isn't working?
Comment: Read some good articles on database normalisation.
Comment: Affecting performance: generate test data and test your query speed.
Comment: Having 6+ foreign keys is certainly not atypical. You would be shocked at how many tables in enterprise-grade applications far exceed that figure, often by one or two orders of magnitude. Achieving normalization will make it significantly easier and more computationally efficient for you in the future should you need your application to scale up.
Answer: In a normalized database, a multi-valued attribute should be stored as rows in a child table.
The fact that you have several multi-valued attributes in this table doesn't change that design principle. Every multi-valued attribute gets its own child table.
This does unfortunately create an issue if you need to fetch all the values from multiple child tables, because they tend to multiply together. For example, if you have four district_ids and four campus_ids, and you join to both tables, you get sixteen rows in the result. There's a Cartesian product between the two child tables. This gets even worse if you join to more child tables that each have multiple matching rows.
One solution is to avoid joining to multiple child tables in a single query where possible. It may be better to do multiple queries, one for each child table, just to avoid the Cartesian products.
Another solution is to GROUP BY the primary key of the parent table, and recombine the lists using GROUP_CONCAT(). This feels like returning to using comma-separated lists, but only for query results, not for storage. You still get the benefits of normalization — avoiding redundancy and data anomalies.
Another solution would be to find a way to relate the values from the child tables, so they aren't combined in a Cartesian product. This could be done by window functions like rank or row number if there's no other natural way to relate them.
Some people try to solve this by creating a single child table for all the multi-valued attributes. This breaks Fourth Normal Form. See my answer to https://stackoverflow.com/a/7084586/20860 for explanation of what can go wrong in that solution.
Answer:
link tables for each of the columns, but is that the best course of action?

Short answer:  Usually better to have the 'link tables'.
Tradeoffs:
With a commalist (like you have), it is messy and slow to look into such for a particular value.  See FIND_IN_SET() if you must.
If that is an "opaque" string that MySQL won't look into (for WHERE, etc), then fine.  Think of as a JPG.  You never need to pick a row based on some pixels in the image.  See GROUP_CONCAT() for constructing a commalist from multiple rows.


Tomcat session replication issue

Question: TL;DR - The node name in the sessionId is not being updated to the current node name in the backup when the primary goes down.
Tomcat version - apache-tomcat-7.0.50
I have two nodes (2 instances of my application in 2 seperate tomcats) set up, with the session replication config (also uses sticky session).Below is the cluster config from server.xml, which is inside the Engine tag. It is similar in both nodes, except the port numbers :
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster" channelSendOptions="8">
    <Manager className="org.apache.catalina.ha.session.DeltaManager"
    expireSessionsOnShutdown="false"
    notifyListenersOnReplication="true"/>

    <Channel className="org.apache.catalina.tribes.group.GroupChannel">
        <Membership     className="org.apache.catalina.tribes.membership.McastService"
        address="220.127.116.11"
        port="45564"
        frequency="500"
        dropTime="3000"/>
        <Receiver      className="org.apache.catalina.tribes.transport.nio.NioReceiver"
        address="auto"
        port="4050"
        autoBind="100"
        selectorTimeout="5000"
        maxThreads="6"/>

        <Sender className="org.apache.catalina.tribes.transport.ReplicationTransmitter">
            <Transport     className="org.apache.catalina.tribes.transport.nio.PooledParallelSender"/>
        </Sender>
        <Interceptor className="org.apache.catalina.tribes.group.interceptors.TcpFailureDetector"/>
        <Interceptor      className="org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor"/>
    <Interceptor className="org.apache.catalina.tribes.group.interceptors.ThroughputInterceptor"/>\
</Channel>

<Valve className="org.apache.catalina.ha.tcp.ReplicationValve"
filter=""/>
<Valve className="org.apache.catalina.ha.session.JvmRouteBinderValve"/>

<Deployer className="org.apache.catalina.ha.deploy.FarmWarDeployer"
tempDir="/tmp/war-temp/"
deployDir="/tmp/war-deploy/"
watchDir="/tmp/war-listen/"
watchEnabled="false"/>
<ClusterListener className="org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener"/>
<ClusterListener className="org.apache.catalina.ha.session.ClusterSessionListener"/>
</Cluster>

From the tomcat Manager, I can see that session (Ex: D042A0C5E380EB9E500224C87233119C.myNode1) is being created in the primary node on login, and replicated in the backup correctly.
But, as soon as the primary node goes down, I am expecting the sessionId in the backup node to be updated with the current node name i.e : D042A0C5E380EB9E500224C87233119C.myNode2
Example :
When user logs in :
Node 1 - Primary - jsessionIdSample.node1
Node 2 - Backup - jsessionIdSample.node1

When one node 1 goes down (Expected) :
Node 1 - - jsessionIdSample.node1 (NODE GOES DOWN)
Node 2 - Primary - jsessionIdSample.node2

But what is happening :
Node 1 - - jsessionIdSample.node1 (NODE DOWN)
Node 2 - Backup - jsessionIdSample.node1

I have two  questions :
1) Is my understanding that the sessionID should be updated in the backup soon after the primary node goes down correct? I read the tomcat docs, and it seems it should.
2) If it should, can you please help me with the config to make this work?
I have tried solutions from other questions on SO, but none of them seem to work.
Thanks in advance!
Comment: Hi Federico, yes, this has been added to apache-tomcat-7.0.50/conf/web.xml as well as the WEB-INF/web.xml file of my project
Comment: Check if `` tag exists in `web.xml` of the war deployed
Answer:
1) Is my understanding that the sessionID should be updated in the backup soon after the primary node goes down correct? I read the tomcat docs, and it seems it should.
Answer: No, when the primary goes down, it goes down. there is no time for it to post anything to the backup node "I'm gonna crush".  the Tomcat document said in here, it will replicate the session cross cluster of nodes. for the part that mentioned update, it mean to say, it will update across all nodes.(not the one already crushed).

2) If it should, can you please help me with the config to make this work?
Answer: N/A

Tomcat session replication issue


Can a center move his head forward before and during a snap?

Question: We had a bit of a debate about this one and looking for a source or discussion (by authority) around the practice of a center looking between his legs before the snap and then bringing his head forward in a continuous motion while snapping the ball.
So there isn't a rigid movement but the offensive player is clearly gaining momentum while snapping.
So is this a false start and are the any rule differences in high school, college, NFL?
Answer: To re-phrase the question, what constitutes a false start?
The NFL rules are discussed at NFL.com. In short the center must keep his head stationary for one second. This time restraint necessarily lends itself to a bit of ambiguity and judgement call from the referee. The rules also mention intent.
So in actual practice the center must have all parts of his body stationary for a brief moment before hiking and none of his movements should be "abrupt" with the intent to draw the defense off-sides.
The NCAAF official rulebook has the same language under Rule 7 Section 1: The Scrimmage - Shift and False Start (pg. FR-71).
The 2014 NFHS official rulebook also has the same language under Rule 7-2 Article 7 (pg. 58) with an emphasis on intent.
To your question:
Technically the center must halt his motion but the rule books leave plenty of leeway for the referee to decide. The intent to draw the defense off-sides is the most significant aspect of the ruling.


Status updates in organic groups disappear after a period of time

Question: After about 30 days or so, the activity streams under the Organic Group Home tab drop off or disappear. I have found a reference to this issue on Acquia Commons' community site.
I have checked the view activity_log_stream but do not see where we might adjust the length of time which content remains on the activity stream. Optimally, we'd like the content to disappear only after the Items per page attribute is met.
Answer: In /admin/settings/activity_log there is just the field to control this.
Note: Though each time we run a cron job, entries over 30 days still disappear. This is perhaps a bug? So our makeshift solution is to click the Regenerate Activity tag. This seems to behaves predictably.


Is This A Fraction?

Question: I was looking around to see some cool things you could do with a graphing calculator, and I came across this equation -
I'm using desmos, and I'm not sure how I would do this. Is the equation above the same as [dx/dy]=[1−4/1−2][x/y]? If not, how can I do this in Desmos?
Comment: No, it's not the same. They're matrices, not fractions
Comment: It is a bit odd that they have a matrix of differentials on the LHS, but not actual derivatives.
Comment: Do you know how to do matrices in desmos
Comment: Ask [Neo](http://en.wikipedia.org/wiki/Matrix_(mathematics)).
Comment: @Lucian how is wikipedia going to help
Answer: You are solving a system of differential equations
$$
x'(t) = x(t) - 4y(t) \\
y'(t) = x(t) - 2y(t)
$$
not one ODE.
This is exactly what allows you to make contour plots in 2D -- such graphs are in essence intersections of the 3D (t,x,y) solution with fixed-level planes...

Is This A Fraction?


Move status bar on watch face using more than setStatusBarGravity

Question: I have this kind of problem (also can be seen on picture below)
I am trying to create my own watch face, however, I am struggling with moving the status bar icons slightly so it does not collide with the background.
Current setup on initiating setWatchFaceStyle is as follows
<code>.setStatusBarGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL)
</code>
Any ideas how to move it a little below or do I have to adjust the watch background?
Here is the screenshot.
Answer: Instead of using the static variables of the Gravity-Class you can use your own settings. Just like:
<code>setStatusBarGravity(Gravity.CENTER | 10)
</code>
Answer: There is no possiblility to adjust the position more exactly than the Gravity.XXX directions.
Even in the design guidelines they are speaking about "several fixed locations" on the wearable.


Access .html file only if logged in

Question: How do you restrict a .html file/page with drupal so that only logged in users can access it?
Basically I have this .html file I need to put up, I don't care whether or not it's a content-page or just simply a file - but I need only those who are logged in to be able to access it.
I've tried simply pasting the html-code in content-creator (read; /?q=node/add/page), but that crashed my site and I had to manually remove the node from the database to get it working again - so that's not an option.
Answer: The Drupal way of doing this is to pull out the content from your HTML file; you don't need to paste the entire contents into the node body, that will break your site's theme.
Once you've created the node with the content you've pulled out of the HTML file, you can use the Content Access module to restrict viewing of the node to only authenticated users.
Answer: As Shawn Conn said Content Access module works here but the Working with files in Drupal 7 documentation is also useful. check it out.

Access .html file only if logged in


Complete separation and stepwise regression - possible in R?

Question: I've been using stepAIC to narrow down my logistic regression model.  However, I get the following warning when I run my model:
glm.fit: fitted probabilities numerically 0 or 1 occurred
I know this means I have complete or quasi-complete separation in my data.  On examination of my data, I see the quasi-complete separation and think that it's meaningful.  Reading online, I see recommendations to use a Firth penalized regression (logistf) or exact logistic regression (elrm); but neither of these will work with stepAIC.  I've also tried bayesglm but I still get the same warning.
How should I select a model when my data has complete separation?  How would I do this in R?  Is my mistake in my stats or in my understanding of using the packages in R?  Any help would be much appreciated!
Comment: You would do best not to do stepwise selection at all (cf., [Algorithms for automatic model selection](http://stats.stackexchange.com/a/20856/7290)).
Comment: The Hauck-Donner effect tag provides a number of very helpful answers on this topic.
Answer: See High p-values for logistic regression variable that perfectly separates? & How to deal with perfect separation in logistic regression? for some background. If stepwise selection were appropriate (take @gung's advice to read Algorithms for automatic model selection), a straightforward approach would be just to make the decisions based on likelihood-ratio tests (equivalently AIC), as the Wald tests will be badly wrong.
Perhaps you could take a similar approach with Firth regression: Heinze & Schemper (2002), "A solution to the problem of separation in logistic regression", Statist. Med., 21, pp 2409–19, form a penalized log likelihood ratio test statistic for the null hypothesis that a given coefficient is zero analogously to the unpenalized version, & imply that its asymptotic distribution is also chi-square with one degree of freedom. (By the way, "problem" is rather a loaded term.)


Layered scatterplot with spline for means

Question: I'm trying to plot animal behaviour over a series of days with individual animals colour coded in a scatter plot and a smooth line showing the mean over the dots. The closest I've come is using lattice like this, where "Standing" is the specific behaviour I'm looking at:
xyplot(data=data2,
       Standing ~ Day,
       type = c("p", "spline"))

This looks nice but doesn't differentiate the dots. If I try using group = Sheep it also divides the lines. I don't know how to group one but not the other.
I also tried using ggplot2, but geo_smooth() doesn't seem to give me the kind of line I want and the following code doesn't work.
means <- tapply(data3$Standing, data3$Day, mean)
ggplot(data3, aes(x = Day, y = Standing)) +
  geom_point(aes(colour = Sheep)) +
  geom_line(data = data.frame(spline(means)))

My dataset looks like this:
   Sheep Day Block Standing Lying Eating Ruminating Moving Fence Pawing Social Scratching
1      2  -4     0       49    12     36         16      0     0      1      0          0
12     4  -4     0       46    13     32         15      0     2      0      0          0
23     5  -4     0       48    13     32         22      0     0      0      0          0
34     6  -4     0       48    12     36         17      0     0      0      0          0
45     2  -3     0       45    19     39         20      2     0      1      0          0
56     4  -3     0       30    27     35         24      6     4      0      0          0

Answer: Within the ggplot check out stat_smooth, I think that is what you're after.
You don't need to calculate means beforehand since stat_smooth should do that for you. If you want to use splines, there is a spline example here.
In this example it isn't very helpful, but based on your dataset I can produce the following graphs:
ggplot(data2, aes(x=Day, y=Standing, color=Sheep)) +
  geom_point() +
  stat_smooth(method=lm)

library(splines)
ggplot(data2, aes(x=Day, y=Standing, color=Sheep)) +
  geom_point() +
  stat_smooth(method=lm, formula=y~ns(x,3))

Answer: Am I understanding correctly that you want to show values for individual animals as points only, and you want the line to summarize the trend across all of the animals?
If so, then you need to break the plotting into two steps: one to generate the scatter plot with coloring by group, and then another to compute the daily means and add a line connecting them to the original scatter plot.
For the first step, you can get colors by group (sheep) using plot() from base R if you specify the grouping variable as a factor in the call to color. So:
 with(data2, plot(Standing ~ Day, type = "p", pch=20, col=as.factor(Sheep)))

To add a line connecting the means across groups by day, use tapply() to calculate the means of Standing by Day, spline() or lowess() to connect the dots, and lines() to add that to the existing plot created in the first step. Here's a version using lowess():
 with(data2, lines(lowess(tapply(Standing, Day, mean)), lwd=2))

I used this line to generate play data to confirm that this worked:
data2 <- data.frame(Sheep = c(rep(1,7), rep(2,7), rep(3,7), rep(4,7)),
  Standing = rnorm(n = 4 * 7, mean = 45, sd = 5),
  Day = rep(seq(7),4))

Comment: Hi, thanks for the reply. You got what I meant, but I can't seem to make your code work. The scatter plot will show but the line isn't added on top. I get an error message saying "plot.new has not been called yet". I've never used the with() function before though so maybe I'm doing something wrong.
Comment: Ah, I see what you mean. That problem seems to be specific to `xyplot()`, and I don't know that function or 'lattice' well enough to know how to solve it. If you just do the `plot()` version, though, it should work fine. So, `with(data2, plot(Standing ~ Day, type = "p", col = as.factor(Sheep)))` followed by `with(data2, lines(spline(tapply(Standing, Day, mean))))`. I'm also seeing that my suggestion for `loess()` doesn't work as intended, so I will edit my original answer to leave only the version that works.
Comment: That does kind of work but for some reason the line starts at 0 rather than at -4 while the dots are correctly places. So they don't correspond. It's the same if I try to plot the means by themselves, even if the values that are generated definitely start with a mean for -4. I keep thinking there must be a way of doing this in ggplot2 that I haven't figured out.
Comment: In base R, you can customize the axes, including labels, by specifying `axes = FALSE` in the original call to `plot()` and then using `axis()` like you did '`lines()` here to add new versions with the desired labels and such. So if you want x-axis labels that start at -4, for example, you would do something like `axis(1, at=seq(7), labels=seq(-4,2,1))`.


filtering a data frame using a comparison between three columns of that data frame

Question: I am working with a  dataframe that contains 1 million rows.
I tried to replicate the dataframe as simple as possible.
Below is the simple data frame.
df = pd.DataFrame()
df['Match'] = ['A Vs B','A Vs B','A Vs B','A Vs B','A Vs B','C Vs D','C Vs D','C Vs D','C Vs D','C Vs D','C Vs D']
df ['Hwin'] = [1,1,1,0,0,0,0,1,0,0,0]
df ['Awin'] = [0,0,0,1,0,1,0,0,0,1,1]
df ['Draw'] = [0,0,0,0,1,0,1,0,1,0,0]

My actual data frame contains 30 over columns.
What I wanted to do as follow:
I want to keep only a row for each match where sum of one of the columns from HWin Draw Awin is greater than the rest two columns.
My expected output is as follow:

How can I do this?
Your advice is much appreciated.
Thanks,
Zep.
Comment: For the match C Vs D, Hwin is same as sum of Awin and Draw, not greater
Answer: IIUC need groupby + transform, then we do row max and idxmax
s=df.groupby(df.columns.tolist())[['Hwin','Awin','Draw']].transform('sum')
df.loc[s.max(1).groupby(df.Match).idxmax()]
    Match  Hwin  Awin  Draw
0  A Vs B     1     0     0
5  C Vs D     0     1     0

Comment: It is not drop duplicates. It will drop all duplicates without looking at the comparison
Comment: Thanks, I should be the one who has to thank to you.
Comment: I will apply it t my df. Thanks


Migrate date time field using migrate source csv

Question: I am trying to migrate a datetime field from csv file but only few are being migrating and other are being failed.I am using migrate
I have created two datetime fields called as Activation Date and Expiry Date in article content type. Attached field type images for reference.
I am writing a custom migration yml file to migrate data from csv file. But only the date values from id 6-10 are being imported but not the date values from 1-5 .
While import I am getting error stating article_csv_import Migration - 5 failed.
I have included sample data and yml file for reference.
Can anyone please let me know what causing the first 5 dates import failing ? Any pointers for a way to debug migration process is greatly appreciated.
migration_examples/migrations/article_csv_import.yml
id: article_csv_import
label: Import Articles
migration_group: default
migration_tags:
  - Article CSV Migration

source:
  plugin: 'csv'
  # Full path to the file.
  path: public://subscription-list-small-copy.csv
  # Column delimiter. Comma (,) by default.
  delimiter: ','
  enclosure: '"'
  header_offset: 0
  ids:
    - id
  fields:
    0:
      name: id
      label: 'Id'
    1:
      name: title
      label: 'Title'
    2:
      name: body
      label: 'Post body'
    3:
      name: field_activation_date
      label: 'Activation Date'
    4:
      name: field_expiry_date
      label: 'Expiry Date'
process:
  title: title
  body: body
  #activation date of the account.
  field_activation_date:
    -
      plugin: format_date
      from_format: Y-m-d H:i:s
      to_format: 'Y-m-d\TH:i:s'
      from_timezone: 'America/Managua'
      to_timezone: 'UTC'
      source: field_activation_date
  # expiry date of the account.
  field_expiry_date:
    -
      plugin: format_date
      from_format: Y-m-d H:i:s
      to_format: 'Y-m-d\TH:i:s'
      from_timezone: 'America/Managua'
      to_timezone: 'UTC'
      source: field_expiry_date
  type:
    plugin: default_value
    default_value: article

destination:
  plugin: entity:node

Sample CSV Data : subscription-list-small-copy.csv
id,title,body,field_activation_date,field_expiry_date
1,Title 1,Body 1,2012-12-22 2:36:03,2013-01-03 0:00:00
2,Title 2,Body 2,2013-08-16 0:00:00,2013-09-15 0:00:00
3,Title 3,Body 3,2013-09-14 0:00:00,2013-10-14 0:00:00
4,Title 4,Body 4,2014-04-08 0:00:00,2014-04-07 23:59:59
5,Title 5,Body 5,2014-09-30 0:00:00,2015-03-29 11:00:00
6,Title 6,Body 6,2014-12-09 12:29:00,2015-01-09 12:29:00
7,Title 7,Body 7,2014-12-31 11:08:00,2015-06-26 23:59:59
8,Title 8,Body 8,2015-02-25 19:12:00,2015-08-10 23:59:59
9,Title 9,Body 9,2015-03-01 11:19:00,2015-02-28 23:59:59
10,Title 10,Body 10,2015-03-02 18:01:00,2015-08-20 23:59:59

image-1 image-2
Answer: from_format: Y-m-d H:i:s means hours with leading zeroes, but there are no leading zeroes in your source. Use from_format: Y-m-d G:i:s (capital G)  for 24-hour-format without leading zeroes
see https://www.php.net/manual/function.date.php
Comment: Thank you it worked.


How can you do convolution graphically?

Question: I don't exactly remember whether I should get the common area under the curves of the functions being convolved or I should multiply them and get the area under the resulting curve.
Answer: The formula for convolution of $f$ and $g$ is $(f \star g)(x) = \int f(s) g(x-s)\ ds$.  So you take the area under the product of one function and a reflected and translated version of the other.
Answer: Here is a demo for doing convolution with respect a set of choices of filters. There is an animate button as well.
Comment: I can't find the "animate" button
Comment: Next to "1D filters" there are some choices. If you click on any of them the graph of the corresponding filter shows. Next to that graph is the button for "animate".

How can you do convolution graphically?


Calculate constant from PDF

Question: The PDF of a random variable X is given by:
$$f(x) = \left\{\begin{array}{ll}
2 & : -c \le x < 0\\
2e^{-4x} & : 0 \le x < \infty\\
\end{array}
\right.$$
In this example, how would I calculate the value of c?
In all of the previous examples I've encountered in the book, they are of the form of:
$$f(x) = \left\{\begin{array}{ll}
c(4x - 2x^2) & : 0 \le x < 2\\
0 & : otherwise\\
\end{array}
\right.$$
In the above example, I would just solve for the value of c through the following integration:
$$c\int_0^2{(4x - 2x^2)dx} = 1$$
Comment: We're supposed to give guidance and hints rather than complete solutions for these, so here's some guidance: you know the area under the whole pdf must be 1. Compute the area of the right hand part. Now you know what the area of the left hand part must be (since they add to 1). Now compute $c$ in a similar fashion to what you've done before.
Comment: I tried but it is difficult to get the idea across without some computation.
Comment: Thanks y'all! I've been trying to wrap my head around this problem for an hour, but now the answer is very clear! @Michael, I appreciate you giving me helpful hints, rather than the full solution!
Answer: In order to solve for the value $c$ in the PDF
$$f(x) = \left\{\begin{array}{ll}
2 & : -c \le x < 0\\
2e^{-4x} & : 0 \le x < \infty\\
\end{array}
\right.$$
It would seem proper to first find the stepwise CDF $F(X)$ by integrating each part separately. i.e.
$$F(x) = \left\{\begin{array}{ll}
\int{2} dx & : -c \le x < 0\\
\int2e^{-4x} dx & : 0 \le x < \infty\\
\end{array}
\right.$$
this results in the CDF being
$$F(x) = \left\{\begin{array}{ll}
\int{2} dx & : -c \le x < 0\\
\int2e^{-4x} dx & : 0 \le x < \infty\\
\end{array}
\right.$$
Which also means that:
$$\int_{-c}^0 2dx +\int_0^\infty 2e^{-4x} dx=1$$
After integration this is:
$$2c+{1\over{2}}=1$$
Solving for $c$ gives
$$c={1\over{4}}$$
Hope this is helpful!
Comment: This is even more explicit but doesn't try to give hints either.
Answer: In this case the first part is $2c$ (area of the rectangle). Then calculate the integral of $2 e^{-4x}$ from $c$ to infinity. That part will be in closed form ${2\over{4}} -0$.  So calculate $c$ as $2c+{1\over{2}} = 1$. Since the entire integral must equal $1$.

Calculate constant from PDF


Backing up Mac OS X Server & User Home Directories

Question: We're setting up Mac OS X Server on a Mac Mini Server for the first time an just getting to grips with it. Now I'm trying to sort out a good backup solution for both the server and the user's home directories.
I've setup Time Machine in the System Preferences to back up the server, however looking at the manual it says that service data isn't backed up, only the preferences & whether services are on/off. Would the best option to just be to clone the server HD and then use that should anything need recovering that isn't covered by Time Machine?
Another issue is backing up our user's home directories. Our user accounts are set up and their home directories are being stored on the server's internal HD via an auto-mounted sharepoint. The problem is that the server admin user doesn't have permission to read any of the files/folders in the user's homes, and therefore cannot read them to perform a backup. Why is this? And how would this be overcome so proper backups can be made of all the user's home directories?
Cheers!
Answer: For the server, I use to make the backups from a MacOS server with rsync. It did involve manual steps but at least I was sure I was backing up everything I needed to recover!
For the home directory:
If the users are all using Mac as well, I would setup Time Machine on their computer.
Since Time Machine can use a shared drive it pretty easy to setup (http://lowendmac.com/zisman/08az/time-machine-shared-backup.html)
Answer: rsync is definitely the way to go, there is also LBackup, which is worth mentioning. If you're interested in commercial packages as well, don't forget to check BRU by Tolisgroup, especially if you're thinking about backups to LTO.


I Need "Autolisting" function to Editable dropdown list

Question: I want to add Auto listing contents when we type text into the editable dropdown list. Is any js for that? I have used the following code:

$(document).ready(function(){

    $(".editableBox").change(function(){
        $(".timeTextBox").val($(".editableBox option:selected").html());
    });
});
.editableBox {
    width: 75px;
    height: 30px;
}

.timeTextBox {
    width: 54px;
    margin-left: -78px;
    height: 25px;
    border: none;
}

    <select class="editableBox">
        <option value="1">First Option</option>
        <option value="2">Second Option</option>
        <option value="3">Third Option</option>
        <option value="4">Fourth Option</option>
        <option value="5">Fifth Option</option>
        <option value="6">Sixth Option</option>
        <option value="7">Seventh Option</option>
    </select>
    <input class="timeTextBox" name="timebox" maxlength="5"/>

Answer: Try like this:
After edited value.The replace the value with same index with
$(".timeTextBox").change() function

$(document).ready(function(){

    $(".editableBox").change(function(){
        $(".timeTextBox").val($(".editableBox option:selected").html());
    });
   $(".timeTextBox").change(function () {
      $(".editableBox option:selected").html($(this).val());
     console.log('content will replaced with new one')
   })
});
.editableBox {
    width: 75px;
    height: 30px;
}

.timeTextBox {
    width: 54px;
    margin-left: -78px;
    height: 25px;
    border: none;
}

    <select class="editableBox">
        <option value="1">First Option</option>
        <option value="2">Second Option</option>
        <option value="3">Third Option</option>
        <option value="4">Fourth Option</option>
        <option value="5">Fifth Option</option>
        <option value="6">Sixth Option</option>
        <option value="7">Seventh Option</option>
    </select>
    <input class="timeTextBox" name="timebox" />

Comment: I thing its like search box .See the link http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist.  and http://stackoverflow.com/questions/40458669/jquery-search-using-real-time-input-like-filter-option-in-angular-js/40458846#40458846
Comment: Its only add typing contents as the first option. Actually i need automatically list content when we type in it. Eg: if we start typig "six", "Sixth Option" to be display in the list.
Comment: you need matching the string or match the index
Comment: Thanks @prasad its working.. http://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_datalist
Answer: you need a div.list or span.list label after .timeTextBox, and register a input or keydown on editableBox, when events happened, change the div.list's content to which can be matched by regular expression. code as follows:
HTML

<select class="editableBox">
    <option value="1">First Option</option>
    <option value="2">Second Option</option>
    <option value="3">Third Option</option>
    <option value="4">Fourth Option</option>
    <option value="5">Fifth Option</option>
    <option value="6">Sixth Option</option>
    <option value="7">Seventh Option</option>
</select>
<input class="timeTextBox" name="timebox" maxlength="5" />

CSS
.editableBox {
  width: 75px;
  height: 30px;
}

.timeTextBox {
  width: 54px;
  margin-left: -78px;
  height: 25px;
  border: none;
}

.list {   // NEW
  background: grey;
  display: none;
}

jQuery Code
$(function() {
  $('.timeTextBox').on('keypress keydown change input', function() {
    var typed = $('.timeTextBox').val();
    var re = new RegExp(typed);
    var matches = [];

    if (!typed) {
      $('.list').css('display', 'none');
      return;
    }

   $('.editableBox').children().each(function(__, option) {
      var content = $(option).text();

      if (re.test(content)) {
        matches.push(content);
      }
    });

    if (matches.length > 0) {
      $('.list').html(matches.join('
')).css('display', 'block');
    } else {
      $('.list').css('display', 'none');
    }
  });
});

My english is poor, I will be pleasant if you point out inproper grammar.


Problemas .htacess

Question: Fiz um site em Joomla e estamos implantando no servidor do cliente (UOL HOST)
porém deparei com um problema.
O site antigo estava dentro da pasta do ftp: dominio.com.br/web
Colocamos os arquivos em outra pasta e subimos o novo conteúdo para essa pasta. Ao acessar tudo estava ok, porém com um problema: Na URL do site começou a mostrar esses diretórios do ftp no link:
<code>www.dominio.com.br/var/www/dominio.com.br/web
</code>
No Joomla temos a opção de habilitar o mod_rewrite do servidor para que a url fique amigável. Portanto essa URL seria oculta.
Acontece que dentro do servidor isso não aconteceu.
Dentro da pasta do site, enviamos um arquivo .htaccess que utilizamos em outros clientes e apenas alteramos a url, porém nada aconteceu também.
Se no Joomla eu desabilito a opção de mod_rewrite, todo esse diretório de pastas some, porém fica aquele famoso "index.php" substituindo no lugar e as outras urls ficam "sujas", portanto não posso deixar assim.
Queríamos manter o esquema de URL amigável, porém com esse link do ftp oculto na URL.
Já tentei jogar o site na pasta raíz (fora desse dominio.com.br/web) e fica a mesma coisa, ele adiciona o tal do "var/www/" na URL.
Também tentei entrar no UOL Host para ver se havia como desabilitar ou mudar essa pasta raíz do FTP, porém sem sucesso.
Alguém tem ideia do que possa ser?
Não tenho muito conhecimento de configuração de servidores, porém segui o padrão de outros que fizemos e não tive esse problema. Por ser UOL Host e diferente dos outros que hospedamos, creio que seja algo na hospedagem.
Apenas para conhecimento, estou colocando abaixo como está meu .htaccess
<code>##
# @package    Joomla
# @copyright  Copyright (C) 2005 - 2015 Open Source Matters. All rights reserved.
# @license    GNU General Public License version 2 or later; see LICENSE.txt
##

##
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
#
# The line just below this section: 'Options +FollowSymLinks' may cause problems
# with some server configurations.  It is required for use of mod_rewrite, but may already
# be set by your server administrator in a way that disallows changing it in
# your .htaccess file.  If using it causes your server to error out, comment it out (add # to
# beginning of line), reload your site in your browser and test your sef url's.  If they work,
# it has been set by your server administrator and you do not need it set here.
##

## No directory listings
IndexIgnore *

## Can be commented out if causes errors, see notes above.
Options +FollowSymlinks
Options -Indexes

## Mod_rewrite in use.

RewriteEngine On

## Begin - Rewrite rules to block out some common exploits.
# If you experience problems on your site block out the operations listed below
# This attempts to block the most common type of exploit `attempts` to Joomla!
#
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.

## Begin - Custom redirects
#
# If you need to redirect some pages, or set a canonical non-www to
# www redirect (or vice versa), place that code here. Ensure those
# redirects use the correct RewriteRule syntax and the [R=301,L] flags.
#
## End - Custom redirects

##
# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root).
##

# RewriteBase /

## Begin - Joomla! core SEF Section.
#
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
# If the requested path and file is not /index.php and the request
# has not already been internally rewritten to the index.php script
RewriteCond %{REQUEST_URI} !^/index\.php
# and the requested path and file doesn't directly match a physical file
RewriteCond %{REQUEST_FILENAME} !-f
# and the requested path and file doesn't directly match a physical folder
RewriteCond %{REQUEST_FILENAME} !-d
# internally rewrite the request to the index.php script
RewriteRule .* index.php [L]
#
## End - Joomla! core SEF Section.
</code>
Answer: Consegui resolver o problema. Para pessoas que futuramente tiver esse problema com o UOL Host, basta pegar o arquivo .htaccess padrão do Joomla e tirar o "#" que comenta a linha "RewriteBase /".
Caso o site esteja instalado em uma subpasta, ficaria assim:
"RewriteBase /diretorio-do-site"
Abraço
Comment: Obrigado!
Resolveu aqui tambem!
Comment: Obrigado!!!! Resolveu aqui também!!!

Problemas .htacess


[System.Web.Security.Membership]::GeneratePassword() - Type Not found

Question: Why do I get Type Not Found when trying to use this class/method in PowerShell?
 [System.Web.Security.Membership]::GeneratePassword()

Do I need to install a module or something to make use of it?
Comment: Strange, i really had to do add-type -AssemblyName System.Web
Comment: Haha i should've known. Forgot about having to add it first. Long day! Thanks.
Comment: What version of .NET and PowerShell are using?  I see this on 5.1 in both Win7 and Win10.  Additionally, `GeneratePassword` requires two arguments.
Comment: 5.1.17134.228 , .net 4.7.03056 i think
Comment: Did you remove the Add-type comment answer? Please put it back since it can be useful.
Comment: It did not apply to this question and was misleading since that type should be loaded as a default on PowerShell v5.1 so I removed it.
Comment: Hm, maybe I have it imported on my profile somewhere..
Answer: For those landing here who are using PowerShell Core, as per this link:
https://github.com/PowerShell/PowerShell/issues/5352

.NET Core does not support System.Web.dll

As such [System.Web.Security.Membership]::GeneratePassword() will result in the same Type Not Found error in PowerShell Core even with the add-type fix above.
You'll have to roll your own password generator.
Comment: Sad that there is no inbuilt alternative. I'm using `$pass = ([char[]]([char]33..[char]95) + ([char[]]([char]97..[char]126)) + 0..9 | sort {Get-Random})[0..12] -join ''` per [this blog][1]

  [1]: https://www.undocumented-features.com/2016/09/20/powershell-random-password-generator/
Comment: This answer is not entirely accurate.  Using PowerShell 5.1 will work, but using 6+ will not.
Comment: @RashadRivera Well, yes, but this particular answer relates specifically to PowerShell __Core__ and is accurate for that version. Versions 1.0 through 5.1 of PowerShell are known as Windows PowerShell. Version 6.0 is known as PowerShell Core. Versions 7+ are known as PowerShell.
Comment: Here's a nice blog post on how to do it:
https://dev.to/onlyann/user-password-generation-in-powershell-core-1g91
Answer: Load the assembly first:
add-type -AssemblyName System.Web
[System.Web.Security.Membership]::GeneratePassword(10,0)

Answer: You do not need to roll your own.  You only need to understand how PowerShell is behaving in version 6+.
I'm running PowerShell 7 and when I try to use the techniques described here, I get the same Membership type is not found error.
When using PowerShell 5.1, I confirmed that before using the Add-Type -AssemblyName System.Web, the Membership type was not found.  After using it, it works.
Going forward, you will need to find a different solution for PowerShell versions 6+.  But so long as you have 5, you should be able to add the System.Web assembly to access Membership class.


Inspecting dependencies of static libs / executables

Question: I have a rather large project with a whole bunch of linked dependencies. The problem is that there's a dependency getting linked to which was compiled with VS 2005 and links with the vc80 debug crt, while I've migrated to VS 2008. The problem is that this also means that I must have the vc80 debug crt installed, something which I'd rather avoid since I have no use of having VS 2005 installed anymore. I'd love to be able to track down the culprit and avoid recompiling the entire project and all dependencies from scratch, so, is there perhaps a convinient way to find out which dependency is linking to the vc80 debug crt?
Answer: It seems dumpbin does the trick with the -directives switch, very handy. It displays various helpful information about the lib file, amongst other things all linked dependencies and their versions.
Answer: I'm not sure it will work for you, but give Dependency Walker a look.
Comment: @milan1612: Um... their answers weren't visible when I posted.
Comment: Why do you post the exact same answer like chills42 did 9 minutes before?


copy certain columns from table a and insert into table b?

Question: please can someone help i have been working on this query for hours. i am trying to copy certain columns from my table ptb_registrations and insert them as a new row into ptb_users.
my ptb_registrations table looks like this:
id  |   username  |  password   | firstname   |  lastname   |   email

1        dave        password       james          tanner       firstname.lastname@example.com
2        jonx10      gundam00       eric           davies       email@example.com
3        33csgge     henry10        daniel         gilmart      firstname.lastname@example.com

from these columns i only want to insert id, firstname, lastname, email and password NOT username.
So my ptb_user table looks like this:
   id   | user_id  |  password   | firstname   |  lastname   |   email

    1        1        password       james          tanner       firstname.lastname@example.com
    2        2        gundam00       eric           davies       firstname.lastname@example.com
    3        3        henry10        daniel         gilmart      firstname.lastname@example.com

id is an auto increment value, and i want user_id to have the same value as the auto_incremented id column when the data is inserted too (if this is possible so where id is 1 - user_id will be 1 also)
so far i have tried loads of different ways to get the columns inserted from ptb_registrations and into ptb_users but nothing is working for me.
cans someone please show me where i am going wrong, thank you.
 // Make a safe query
    $query ="insert into ptb_users(id, first_name)
    select ptb_registrations.id, ptb_registrations.firstname
    from ptb_registrations, temp
    where ptb_users.id=temp.id;
    ";

    mysql_query($query)or die('Could not update members: ' . mysql_error());

Comment: [**Please, don't use `mysql_*` functions in new code**](http://bit.ly/phpmsql). They are no longer maintained [and are officially deprecated](http://j.mp/XqV7Lp). See the [**red box**](http://j.mp/Te9zIL)? Learn about [*prepared statements*](http://j.mp/T9hLWi) instead, and use [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli) - [this article](http://j.mp/QEx8IB) will help you decide which.
Answer: There's no way to guarantee that your new AUTO_INCREMENT will match your previous user ID's... What happens if there is a break in the sequence? Your best bet is to re-assign the new table's id after you've inserted the records.
Your query should something like this:
INSERT INTO ptb_user (user_id, password, firstname, lastname, email)
SELECT id, password, firstname, lastname, email
FROM ptb_registrations
ORDER BY id

P.S. I hope you're not saving the passwords in plain-text.


How to duplicate a LinkedBinaryTree java?

Question: Im trying to implement a method called mirror() which reverses the tree but does not change the original tree. I have made a method which flips and changes the original tree, and i plan to duplicate the original tree, and flip the new tree. I am stuck on implementing the duplication of the original tree.
<code>/** Returns a mirrored copy of the tree */
public LinkedBinaryTree<E> mirror() {
    LinkedBinaryTree<E> reversed = new LinkedBinaryTree<E>();

}

public void duplicate(Position<E> p) {

}

/** Reverses the tree */
public void reverseMe() {
    if (this.root != null) {
        reverseHelper(this.root);
    }
}

private void reverseHelper(Position<E> p) {
    Node<E> node = (Node<E>)p;

    if (node.getLeft() != null) {
        Node<E> temp = node.getLeft();
        node.setLeft(node.getRight());
        node.setRight(temp);

    } else if (node.getRight() != null) {
        Node<E> temp = node.getLeft();
        node.setLeft(node.getRight());
        node.setRight(temp);
    }

    if (node.getLeft() != null) {
        reverseHelper(node.getLeft());
    }

    if (node.getRight() != null) {
        reverseHelper(node.getRight());
    }
}
</code>
Comment: What did you try so far in terms of duplicating the tree?
Comment: @Assafs
I've tried to use addRoot(), something like this:

reversed.addRoot(this.root.getElement());
reversed.reverseMe();

return reversed;
Comment: I wrote you an answer below. If it helps you solve the problem and duplicate your tree, may I ask you accept the answer (just click on the grey check mark next to the answer, making it green)
Comment: Any chance I could convince you to accept the answer below? It's just a click on the gray check mark next to it, making it green. I would really appreciate it. It's the only non-accepted answer I have in the past few months. Trying to complete a set :-)
Answer: Perhaps something like this will help:
<code>private Position<E> duplicate (Position<E> p) {
    Node<E> node = (Node<E>)p;
    Node<E> newNode = new Node<E>();

    //Set the contents of the node as needed.

    if (node.getLeft() != null) {
        newNode.setLeft(duplicate(node.getLeft());
    }
    if (node.getRight() != null) {
        newNode.setRight(duplicate(node.getRight());
    }
    return newNode;
}
</code>
Please take into account that the content of any node needs to be copied where the comment suggests, and that I created a new instance of the Node in the most basic way - if there's a special constructor, please use it.


Sort nodes based on parent taxonomy term name in views

Question: I have a taxonomy term "Store Locations". I have added terms as State & City by parent child concept.  Like this:

I have created Store Locations as node and assign them in the taxonomy term like this:

Now I want to sort the nodes as per parent taxonomy term name.
For e.g: I have created the parent term "Bihar" first, then added "Andaman". So the term ID for Bihar is 6 and 7 for Andaman.
So the sorting is showing Bihar at first and then Andaman.
I want to display them as alphabetical order of the parent term.
Currently the view is showing as per parent term id, not by name.
Answer: I have added another relationship "Taxonomy Term" as Parent and in Sort Criteria added a filter "Taxonomy Term Name" in ascending order.
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


How to apply Simple Factory Pattern Java

Question: I am trying ot understand how to apply a the simple factory pattern to an assigment I have but I do not understand how to do it.
This is the request: Apply the Simple Factory pattern that creates the appropriate Strategy object.
Remember, this is a Simple Factory pattern. Draw the UML diagram of the new
design.
We already implemented the strategy pattern but I do not understand how to apply the simple factory pattern to the code. I understand that the simple factory pattern is supposed to provide encapsulation for the creation of the object but I do not see how the examples I have found show how to apply to this. Any help would be appreciated.
EDIT: Updated code
EDIT: Changed code to make use of polymorphism
package Client;

import domain.Loan;
import factory.StrategyFactory;
import strategy.ComplexLoan;
import strategy.ICapitalStrategy;

public class Client {
    public static void main(String[] args){
        Loan complexLoan = new Loan(2.2, 2, 3.3, 4.4, 5, 6, 7, StrategyFactory.getComplexStrategy());
        System.out.print("hello");

    }

}

package factory;

import strategy.ComplexLoan;
import strategy.ICapitalStrategy;
import strategy.RevolvingLoan;
import strategy.TermLoan;

public class StrategyFactory {
    /*
    public static ICapitalStrategy getStrategy(String type) {
        if (type.equals("Complex")){
            return new ComplexLoan();
        }
        else if (type.equals("Revolving")){
            return new RevolvingLoan();
        }
        else if (type.equals("Term")){
            return new TermLoan();
        }
        return null;
    }
    */

    public static ICapitalStrategy getComplexStrategy() {
        return new ComplexLoan();
    }
    public static ICapitalStrategy getRevolvingStrategy() {
        return new RevolvingLoan();
    }
    public static ICapitalStrategy getTermStrategy() {
        return new TermLoan();
    }
}

    package domain;
    import strategy.ICapitalStrategy;

    public class Loan {
        private ICapitalStrategy strategy;

        double commitment;
        int duration;
        double riskFactor;
        double unusedPercentage;
        int outstandingRiskAmount;
        int unusedRiskAmount;
        double unusedRiskFactor;
        double capital;

        public Loan(double commit, int dura, double rskFact, double unusedPer,
                    int outStandRskAmt, int unusedRskAmt, double unusedRskFac,
                    ICapitalStrategy strat) {
            this.commitment = commit;
            this.duration = dura;
            this.riskFactor = rskFact;
            this.outstandingRiskAmount = outStandRskAmt;
            this.unusedRiskAmount = unusedRskAmt;
            this.unusedRiskFactor = unusedRskFac;
            this.strategy = strat;

        }

        public double CalculateCapital() {
            return strategy.CapitalLoan(this);
        }

        public double getCommitment() {
            return commitment;
        }

        public void setCommitment(double c) {
            commitment = c;
        }

        public int getDuration() {
            return duration;
        }

        public void setDuration(int dur) {
            duration = dur;
        }

        public double getRiskFactor() {
            return riskFactor;
        }

        public void setRiskFactor(double rskFac) {
            riskFactor = rskFac;
        }

        public double getUnusedPercentage() {
            return unusedPercentage;
        }

        public void setUnusedPercentage(double unusedPercent) {
            unusedPercentage = unusedPercent;
        }

        public double getOutstandingRiskAmount() {
            return outstandingRiskAmount;
        }

        public void setOutstandingRiskAmount(int outStandingRskAmt) {
            outstandingRiskAmount = outStandingRskAmt;
        }

        public double getUnusedRiskAmount() {
            return unusedRiskAmount;
        }

        public void setUnusedRiskAmount(int UnusedRskAmt) {
            unusedRiskAmount = UnusedRskAmt;
        }

        public double getUnusedRiskFactor() {
            return unusedRiskFactor;
        }

        public void setUnusedRiskFactor(double unusedRskFac) {
            unusedRiskFactor = unusedRskFac;
        }

        public Loan(ICapitalStrategy strategy) {
            this.strategy = strategy;
        }

        /*public double executeStrategy() {
            return this.strategy.CapitalLoan(this);
        }
        */
    }

    package strategy;

    import domain.Loan;

    public class ComplexLoan implements ICapitalStrategy {

        @Override
        public double CapitalLoan(Loan l) {
            return ((l.getOutstandingRiskAmount() * l.getDuration() * l.getRiskFactor()) + (l.getUnusedRiskAmount()
                    * l.getDuration() * l.getUnusedRiskFactor() ));
        }

    }

    package strategy;

    import domain.Loan;

    public interface ICapitalStrategy {
        public double CapitalLoan(Loan l);
    }

    package strategy;

    import domain.Loan;

    public class RevolvingLoan implements ICapitalStrategy {

        @Override
        public double CapitalLoan(Loan l) {
            return (l.getCommitment() * l.getUnusedPercentage() * l.getDuration() *l.getRiskFactor());
        }

    }

    package strategy;

    import domain.Loan;

    public class TermLoan implements ICapitalStrategy {
        public TermLoan() {

        }
        public double CapitalLoan(Loan l) {
            return (l.getCommitment() * l.getDuration() * l.getRiskFactor());
        }

    }

Comment: *"I do not see how the examples I have found show how to apply to this."* We would be guessing too. It should be in your assignment specification. If it's not, you should ask the instructor.
Comment: @Radiodef It was more of a heads up that I ahve looked at resources online but it still isn't clear so I could get a more guided explanation.
Answer: Here's a likely helpful bit about Simple Factory Pattern[1]:
The simple factory isn't actually a pattern; it's more of a design principle. The simple factory encapsulates the object creation code, but keeps control over how the object is created. Simple factories are often designed as a class with a static method (aka static factory) that returns the object requested.
Here's an example, not suited directly to your example in order to make you think a bit hard for your homework :)
interface Foo{
  double calculateStuff();
}

class MyClass implements Foo{
  @Override
  public double calculateStuff(){
    //logic goes here
  }
}

class MyFactory {
  public static double getCalculatedStuff(){
    return new MyClass().calculateStuff();
  }
}

class RunCode {
  public static void main(String[] args){
     double stuff = MyFactory.getCalculatedStuff();
  }
}

[1] - Learning Design Patterns - Factory Pattern

EDIT:
class LoanFactory{

    public static double getComplexLoan(Loan l){
        return new ComplexLoan().CapitalLoan(l);
    }
}

another way (which has its uses, but in this case I prefer the method above):
class ComplexLoan implements ICapitalStrategy{
    private ComplexLoan(){
    }

    public static double getLoan(Loan l){
        return new ComplexLoan().CapitalLoan(l);
    }
}

or this option that explicitly displays polymorphism:
class LoanFactory{

    public static ICapitalStrategy getComplexLoan(){
        return new ComplexLoan();
    }
}

One other thing that is important to note: convention says method names should start with a lowercase letter, so your CapitalLoan() would be capitalLoan().
Also, there's no need to prefix your interfaces with an I, so your ICapitalStrategy would become CapitalStrategy.
Comment: The OP said they have already looked at examples. Also, your example is not entirely correct. Factory Pattern is generally an object one uses to create other objects, not a static utility class for performing a computation.
Comment: Yes, my example regarding computations isn't the best choice for exemplifying factory pattern, but I believe it is simple enough for OP to understand. Also, OP said they didn't understand the examples they found.
Comment: @victorantunes So I would basically need to create a factor for each subclass of my interface?
Comment: Not really. The point is to have only one Factory class, and have one method for each class that implements your `Strategy` interface, and have that method return an instance of said class. Are you getting somewhere now? I'm trying to point you in the right direction without giving you the exact answer to your homework. You're supposed to think :p
Comment: @victorantunes Well all of the examples I have found online seem a easier than this. I think I may be making progress. Just kind of fried at the moment.
Comment: @victorantunes I get that a factory could have a chain of If/else statements that determins which on is created but in the case of my code it is done already by what is passed when the loan is created. I do not understand how I am supposed to etract that into a class.
Comment: @victorantunes I think I figured it out right as you posted your new edits. Let me know if it looks correct.
Comment: Yes, it is one correct way of doing it, but since you have polymorphism going on (classes which implement `ICapitalStrategy`), you could ditch the `String type` argument in this case, and go for several methods, one directed at each class that implements `ICapitalStrategy`. I've updated my answer to illustrate this.
Comment: @victorantunes Yeah i think it just all clicked. I changed it to actually use the polymorphism and I think I understand it now. Let me know if you see anything else.
Answer: In the following example. The "Document" is abstract class and "html" document. "MyDocument" and "pdf" are concrete class. As long as you provide parameter with valid string, you will get the corresponding concrete class. For example if you put "pdf" as a parameter, you will get pdf document. Document type is all you need to accept whatever type of documents you want to create.
public Document CreateDocument(String type){
if (type.isEqual("html"))
    return new HtmlDocument();
if (type.isEqual("proprietary"))
    return new MyDocument();
if (type.isEqual("pdf"))
    return new PdfDocument ();
}

There is a better documented article thread in
Examples of GoF Design Patterns in Java's core libraries
Comment: I think I figured it out let me know if it looks correct.
Comment: You can use generics too. Writing three different methods for three type of concrete class can effect the scalibility in my opinion. http://stackoverflow.com/questions/6191710/am-i-implementing-a-generics-based-java-factory-correctly
Answer: public interface PaymentMethod {
    public void makePayment();
}

class CreditCard implements PaymentMethod {
    public void makePayment() {
        System.out.println("Payment through credit card...");
    }
}

class NetBanking implements PaymentMethod {
    public void makePayment() {
        System.out.println("Payment through net banking...");
    }
}

public class PaymentMethodFactory {
    public static PaymentMethod getPaymentMethod(String method) {
        if ("creditcard".equalsIgnoreCase(method)) {
            return new CreditCard();
        } else if ("netbanking".equalsIgnoreCase(method)) {
            return new NetBanking();
        } else {
            throw new IllegalArgumentException("Payment method not supported!");
        }
    }
}

public class SimpleFactoryTest {

    public static void main(String[] args) {
        PaymentMethodFactory factory = new PaymentMethodFactory();
        PaymentMethod paymentMethod = factory.getPaymentMethod("creditcard");
        paymentMethod.makePayment();
    }

}


Como pegar uma string retornada da execução interna de uma URL para transformá-la em um objeto JSON?

Question: Preciso executar esta URL internamente no servidor.
O resultado da execução gera uma string no formato JSON:
{"success":false,"errorMessage":"Token inválido"}

Como pegar a string retornada da execução da URL para transformá-la em um objeto JSON?
Answer: Essa string já vem no formato JSON, para transformar num objeto usa o metodo json_decode();
Usando PHP tem pelos menos duas maneiras:
Usando curl:
$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken=1234';
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, True);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl,CURLOPT_USERAGENT,'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1');
$rawData = curl_exec($curl);
curl_close($curl);
$data = json_decode($rawData);
print_r($data); // stdClass Object ( [success] => [errorMessage] => Token inválido )

Usando file_get_contents:
$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken=1234';
$opts = array(
    'http' => array(
        'method'=>"GET",
        'ignore_errors' => true, // para este caso, isto é necessário senão seria ".. 400 Bad Request .."
        'header' => array(
            'User-Agent' => "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:7.0.1) Gecko/20100101 Firefox/7.0.1",
        )
    ),
);
$context = stream_context_create($opts);
$rawData = file_get_contents($url, false, $context);
$data = json_decode($rawData);
print_r($data); // stdClass Object ( [success] => [errorMessage] => Token inválido )

Em para aceder às keys deste novo objeto ($data) faz:
$data->errorMessage; // Token inválido

Nota que nem sempre é preciso definir nos headers um User-Agent, mas para muitos casos o servidor a que vamos fazer o pedido "obriga" a que haja um  User-Agent definido, caso contrário a resposta vem vazia ou responde algum tipo de mensagem de erro
Comment: Muito bom Miguel. Eu tinha conseguido fazer aqui usando cURL. Ficou um pouco diferente mais funcionou também. Achei o segundo método interessante também. Valeu.
Answer: Solução final galera! Utilizando cURL
$url = 'https://sandbox.boletobancario.com/boletofacil/integration/api/v1/fetch-payment-details?paymentToken='.$paymentToken;

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url);
// define que o conteúdo obtido deve ser retornado em vez de exibido
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false);
$order = curl_exec($ch); //Pega a string JSON obtida.
curl_close($ch);
$array = json_decode($order, true); //transforma a string em um array associativo.


How much baroque music was derived from improvisation?

Question: I've heard that much music we think of as "baroque" was actually improvised, and only later set in stone. Is this true?
I'm currently playing baroque-style continuo/bass lines in a duo that riffs off of baroque and folk music, and the answer to this might help me interpret these pieces.
Comment: I do not claim to be really knowledgeable on this matter, but I wonder if you are mixing two facts together. The first is that Baroque music (especially solo performance forms) are big on ornamentation, which are typically supplied/improvised by the performer, though the basic score is written down. Second is [the story behind _The Musical Offering_](http://en.wikipedia.org/wiki/The_Musical_Offering) of Bach.
Comment: Certainly everything I've written, music *and* lyrics. Perhaps a better way to ask this would have been "how much of what we consider 'baroque music' is an improvisation that jelled, and how much of it was written in a fixed form from the beginning?" But I think (hope) that my point came across.
Answer: Some of the music was written quickly in a kind of shorthand.  If you as a harpsichordist were expected to write a new piece for flute and harpsichord to be performed tonight, you would probably just write a lead sheet for the harpsichord part and wing it from that.  The Baroque equivalent is "figured bass":  just the bass notes with numbers indicating the chords.
You would write the melody for the flute, but the style of playing at the time was to have lots of grace notes, mordents, flourishes and scales and so on.  Most likely you wouldn't take the time to write them into the score; you'd let the flute player go wild.
It wasn't exactly like modern jazz improvisation; the soloist would still play all the written notes, and just lots of little ones besides.
J.S. Bach generally took the time to write down full accompaniments and to write in the mordents and other stuff.  Maybe he didn't like what he heard when other players improvised and he knew he could write better than they could improvise.  Or maybe he was just showing you one sample way of interpreting it.  Very few of the other composers took that much care with their notation.
Rule of thumb:  if the keyboard part is just single bass notes, play chords and stuff.  If it looks like it's all worked out for you, play it as written.  Play the keyboard parts from some Bach solo sonatas and trio sonatas to get a feel for what a good accompaniment sounds like.
Comment: I think Bach probably also believed that he can improvise better than other people can write. `:-)`
Comment: @Willie I bet he was right most of the time too.


Is it possible to develop a web site for a touch based browser without using HTML5 or CSS3?

Question: I'm developing the CSS file for the mobile version of the website my group are working on for our web design coursework, and I was wondering if it was possible to design a site for touch based browsers using the currently ratified specification of HTML and CSS, as the other member are doing for the desktop variant, or am I going to have to use the draft specification of the new language. I'm not intending to use anything too elaborate, I'm only attempting to allow the user to navigate the site with their finger, and the current implementation allows me to activate a dropdown menu on the desktop, but when I try to navigate on my Android handset, nothing happens.
The menu button gets illuminated in the way that all links in my browser do when they get pressed, but nothing happens. The research I've done since this revelation has led me to the conclusion that I'm going to have to experiment with the new spec, though since this is coursework, I'd rather stick with current standards than experimental drafts of new ones.
P.S. I'm only developing an informative site, not an application.
Answer: Yes, you can use older versions of HTML. iPhone, Palm OS, Android, and recent versions of the Blackberry OS all use Webkit, which is the same rendering engine that Chrome and Safari use.
In fact, the very first page on the World Wide Web will work just fine.
We'd need to see your code for your navigation bar to troubleshoot, but it's probably something along the lines of using a hover event to display the navigation (touchscreens can't have a hover event).
Comment: Thanks a lot for the feedback. It turns out there isn't really an problem here. I was using Dropbox to get the files over to my phone, and I was downloading the HTML and CSS files manually, but I was forgetting to download the Javascript file I was using to animate the dropdown :P
Answer: I can browse to any site on my iphone using the touchscreen. The language is not the problem. Most mobile browsers on smartphones can handle html(4)/css(2) fine. You should be more worried how to show the content so it will be easy to navigate on the site using a (small) touchscreen. Usability testing is your friend here. Browsing a website made for desktop can be very frustrating (not impossible) on a small touch screen.
Also the size of images and stuff shouldn't be to big. Since loading those can be a pain. At least the t-mobile(Netherlands) g3 network is slow, if available at all.
Answer: For sure do it! just ensure links are larger for fingers. Also allow the site to resize.
Most mobile sites are HTML1.0.
You would be silly using html5 + css3 unless you knew that it was only going to be used on an iphone eg. webapps.
And don't forget you can still use JavaScript!
Go For It!
Answer: Note that the 'currently ratified' version of CSS is CSS1 (from 1996), CSS2.1 isn't yet a W3C Recommendation.  So from that point of view the standards your other members are using for the desktop variants are not much more ratified than HTML5 and CSS3.


OpenVPN - ERROR: Cannot open TUN/TAP dev /dev/net/tun: No such file or directory (errno=2)

Question: There are lots of questions pertaining this error, and there is a suggested manual fix which works well, but there's no permanent solution. How can i permanently solve this? Im having this issue on a debian wheezy server, using OpenVPN client to connect to an OpenVPN server.
The suggested fix is the one below. Seems like, /dev/net is not automatically created and of course disappears on each reboot.
mkdir -p /dev/net
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun

Comment: it's work like a charm on synology nas, i was try to use zerotier and was unable until i see this answer !!!
Answer: It happens in Arch/Manjaro as well.
I managed to figure out the problem, apparently a kernel upgrade is simply moving the modules directory, so trying to reach the modules from their known location is unavailable, the current running kernel is still running but I can't seem to modprobe (load) any modules which are not already loaded (such as tun required for OpenVPN connections).
So for example, the /lib/modules/ directory had the following directories before the upgrade (I have multiple kernels, notice the 5.16 series):
5.15.32-1-MANJARO  *5.16.14-1-MANJARO*  extramodules-5.15-MANJARO  extramodules-5.16-MANJARO

And this is the status after the upgrade:
5.15.32-1-MANJARO  *5.16.18-1-MANJARO*  extramodules-5.15-MANJARO  extramodules-5.16-MANJARO

Trying to load the tun modules shows the following message:
modprobe: FATAL: Module tun not found in directory /lib/modules/5.16.14-1-MANJARO

Which perfectly makes sense as this directory doesn't exist.
So, what is my proposed solution in this case? A restart.
Answer: debian wheezy has been out of support since may 2018 (https://www.debian.org/releases/wheezy/), you should not be using it in 2020 any more for production.
Now, with that out of the way, you could add the commands that temporarily fix your issue adding those commands a bash script that you add to your root crontab with the @reboot nickname (man 5 crontab).
So create a bash script somewhere in your file system with something like this:
#!/bin/bash

mkdir -p /dev/net
mknod /dev/net/tun c 10 200
chmod 600 /dev/net/tun

/etc/init.d/openvpn restart

Save it with 755 permissions and modify the root crontab:
# crontab -e

with this content at least
@reboot /path/to/where/you/saved/the/script

And after rebooting it should have started openvpn successfully.
Comment: As an alternative, the code snippet can be be written into `/etc/default/openvpn` file, which is sourced by `/etc/init.d/openvpn` script.
Comment: nice, I do not have a debian wheezy handy to test, but this should be the preferred option if it works
Answer: I think that a possible solution is to configure the system to load the tun kernel module during startup. In order to do so, list the tun module name in /etc/modules file:
# echo tun >> /etc/modules

udev is the system component that creates and maintains device nodes in /dev folder according to loaded kernel modules and connected hardware devices. I believe that by loading tun kernel module at boot time, the system will create the /dev/net/tun device node on every startup.
I hope it helps.

EDIT: I am a bit outdated. After launching a Debian Wheezy image published in Vagrant Cloud website, I figured out that udev in fact handles permissions, ownerships and symlinks regarding already existing device nodes. Device nodes are actually created by the kernel itself and are exposed to userspace through the devtmpfs pseudo-filesystem.
devtmpfs filesystem is mounted at initramfs time. The file /usr/share/initramfs-tools/init, which gets executed once grub extracts initramfs to memory, presents code that mounts a devtmpfs filesystem into /dev, falling back to a standard tmpfs filesystem if unsuccessful.
In addition, to have devtmpfs filesystem available, Debian Wheezy kernel is shipped with CONFIG_DEVTMPFS=y enabled.
Comment: On Busybox systems I have experienced that `tun.o` or `tun.ko` does exist in the default modules directory. In that case `insmod /path/to/tun.o` will be the way to go?
Comment: Anderson, i tried the suggested solution, but it doesn't work
Comment: @LasseMichaelMølgaard It depends on how the Busybox system is implemented. I am not sure on how device nodes are maintained in such systems. Anyway, `modprobe` and `insmod` are to kernel modules as `apt-get` and `dpkg` are to software packages, so `insmod` may work.
Comment: @Joe Interesting. So I think that the only option is to automate the manual fix at boot time, as [@natxo asenjo's answer](https://serverfault.com/a/1003129/293407).


Cors XmlHttpRequest and Response

Question: Description of Task
I'm creating a program with a client/server architecture. The server is a javascript script running in the users's browser, the client is a application running on the user's local machine. The script posts a GET request to a port on 127.0.0.1; 2000 for example. The client reads the message, does some action, and posts a reply back to the server.
Description of Problem
This type of interaction is considered to be cross-origin resource sharing. I've read the material here and written my program to respond to the request using with appropriate cors header messages. Unfortunately I seem to be getting the error message:
XMLHttpRequest cannot load http://127.0.0.1:2000/?Command=test&Parameters=1234. Origin http://127.0.0.1 is not allowed by Access-Control-Allow-Origin.
Full Http Exchange
GET /?Command=test&Parameters=1234 HTTP/1.1
Host: 127.0.0.1:2000
Connection: keep-alive
Origin: http://127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Geco) Chrome/17.0.963.79 Safari/535.11
Accept: */*
Referer: http://127.0.0.1/test/main.php
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

HTTP/1.1 200 OK
Server: Custom-Gnat-Client-v1.0
Access-Control-Allow-Origin: *
Origin: http://127.0.0.1
Content-Length: 12
Keep-Alive: timeout=2, max=100
Connection: Keep-Alive
Content-Type: text/plain

Success

Relevant Code
In main.js:
var Is_IE                = window.XDomainRequest ? true : false;
var Cross_Domain_xmlhttp = Create_Cross_Domain_Request();

function Create_Cross_Domain_Request(){
  var request;
  if(Is_IE)
    request = new window.XDomainRequest();
  else{
    if(window.XMLHttpRequest){
      request=new XMLHttpRequest();
    } else {
      request=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  return request;
}

...

var URL = "http://127.0.0.1:2000/"+"?Command="+Command_String+"&Parameters=" +Parameters;
if (Cross_Domain_xmlhttp){
  if(Is_IE){
    Cross_Domain_xmlhttp.onload=function(){
      console.log(Cross_Domain_xmlhttp.responseText);
    }
    Cross_Domain_xmlhttp.open("GET", URL, true);
    Cross_Domain_xmlhttp.send();
  } else {
    Cross_Domain_xmlhttp.open('GET', URL, true);
    Cross_Domain_xmlhttp.onreadystatechange=function(){
      if (Cross_Domain_xmlhttp.readyState==4 && Cross_Domain_xmlhttp.status==200){
        console.log(Cross_Domain_xmlhttp.responseText);
      }
    }
    Cross_Domain_xmlhttp.send();
  }
} else {
  alert("The browser does not support XDomainRequest or XmlHttpRequest");
}

The client code isn't relevant currently but I will post if requested.
Answer: There should not be any Origin: http://127.0.0.1 in server response since it's a request header.
And why not to return Access-Control-Allow-Origin: http://127.0.0.1 instead of *?
Comment: Well, removing the Origin didn't help. Also it would be ideal for it to be http://127.0.0.1 as Access-Control-Allow-Origin, but I have * there now because I want it to be as permissive as possible until I get it working. Then I'll narrow it down.
Comment: It didn't work either, I bet it has something to do with the encoding of the response. The client, written in Ada, has default Latin-1 string encoding. After some reading, it seems they expect utf-8 encoding.
Comment: It wouldn't make any difference with encoding if you use only latin characters.
Comment: so I went into the network developer tools in chrome and IE 9 and looked at the header/response stuff. IE 9 received the response, though it couldn't render "Success". Chrome didn't receive any response headers at all... wtf?
Comment: which means it's something to do with xmlhttprequest vs. xdomainrequest

Cors XmlHttpRequest and Response


Kotlinc command line error

Question: I follow this (https://kotlinlang.org/docs/tutorials/command-line.html) instruction. I set the environment variable (windows 7) to bin directory run "kotlinc" at the command line i get the following error (I even navigate to the bin directory from the command prompt)

Error: Could not find or load main class org.jetbrains.kotlin.preloading.Preloader
Comment: [This might be related](https://discuss.kotlinlang.org/t/how-to-run-kotlin-1-1-4-eap-repl/3808/2), I'm not sure
Comment: Thanks for the response, but the compiler version is 1.2.10.(your link version is 1.1.4) downloaded from the link provided by the above doc page
Comment: why do you kotlinc? why not just gradle or maven?
Comment: @knock I wanted to compile the basic code from the doc page, do I need gradle or maven to do that (and will gradle or maven work without the kotlinc command working)
Answer: its because spaces in path to kotlinc. Need to convert path from D:/Program Files to D:/.
Answer: The manifest file for hello.jar does not point to main() anymore. I've been asking about this for awhile -- it may have been broken since Kotlin 1.1.

Kotlinc command line error