2-Sat to Implication Graph

Question: I have a set of clauses
$$(x,y),(x,z),(y,z),(\neg x, \neg y), (\neg x , \neg z), ( \neg y, \neg z)$$
I drew the implication graph and have no bad loop but the answer says there is a bad loop.
My graph I'm pretty sure is wrong.
I drew
x->y->y with a line from x->y
and the same for the negation but this doesn't contain a bad loop so my graph must be wrong.
Answer: If $p \lor q$ is a clause in your 2-Sat instance, then in the implication graph this gives two arrows, namely $\neg p \to q$ and $\neg q \to p$. (Namely, the clause says that if $p$ is false then $q$ must be true, and if $q$ is false then $p$ must be true in order to make the clause true.)
For instance, from $(x,y)$ you get arrows $\neg x \to y$ and $\neg y \to x$. From $(\neg y,\neg z)$ you get arrows $y \to \neg z$ and $z \to \neg y$.
Can you find the correct graph now? And the bad loop in your graph? Hint for checking your answer: it goes past all 6 vertices of the graph.
Comment: Yeah got the right graph now, thanks

2-Sat to Implication Graph


Is there a generalization of Brahmagupta–Fibonacci identity for cubic?

Question: I was wondering if there was a cubic version of Brahmagupta–Fibonacci identity .
I looked everywhere but I didn't find anything ,except the splendid website of Tito Piezas (see here)
Furthermore I know the Gauss identity wich is :
$$a^3+b^3+c^3-3abc=(a+b+c)(a^2+b^2+c^2-ab-bc-ca)$$
So my question is :
Is there a generalization of Brahmagupta–Fibonacci identity or Gauss identity ?
Thanks a lot .
Comment: As you say, Tito's page is so splendid, that every such generalisation would already be there. So have a look again. I did not find a cubic Bramagupta yet.
Comment: Do you mean something like $(a^3+b^3)(c^3+d^3)=f(a,b,c,d)^3+ g(a,b,c,d)^3$ where  $f$ and $g$ are some integer polynomial? Or something else?
Comment: @Robert Z Yes I mean something like that , furthermore I just find [this](http://jrms.ramanujanmathsociety.org/in-publication/in-publication-list/a-cubic-generalization-of-brahmagupta-s-identity) but there is nothing...
Comment: In order to have a cubic version of the Brahmagupta-Fibonacci identity, you need to have a "cubic semigroup" like $\mathbb{Z}[\omega]$ or something analogous, don't you?
Comment: @JackD'Aurizio: [This post](https://math.stackexchange.com/questions/2653086/on-the-cubic-generalization-a3b3c3d3e3f3g3h3-v-13v-23v) may be of interest.
Answer: There is not one.
If there were one, that would mean that the set of the sums of two integer cubes is closed under multiplication. However,
$$(1^3+1^3)(1^3+1^3)=4,$$
which is not the sum of two integer cubes (positive, negative, or zero).
Comment: +1 Simple but powerful (generalises to all higher powers).
Comment: @AdamBailey Thank you, and that's a good point!
Answer: There is, provided your are prepared to have 3 letters in the identity. It requires consideration of multiplication in a cubic field. See http://www.mathjournals.org/jrms/2017-032-004/2017-032-004-001.html
Let $$N_j = \left ( \begin {array} {ccc} u_j & -a d y_j & -a d x_j - b d y_j \\ x_j & u_j - b x_j -c y_j & - c x_j - d y_j \\ y_j & a x_j & u_j - c y_j  \\\end {array} \right) .$$ Then define $$N_1 N_2 = N_3. $$ Taking determinants gives such an identity.


Induced homomorphism is injective

Question: Let $\pi:M\longrightarrow N$ be a surjective submersion or fiber bundle(local trivialization) or fibration. Here $M$ and $N$ are manifolds.
Why the induced homomorphism of first cohomology group $\pi^{*}:H^{1}(N)\longrightarrow H^{1}(M)$ is injective?
Is proposition correct for all case?
Comment: I have a suggestion. Don't change or strengthen the hypotheses on this question, as you did when you edited it after the answer of @TesmoAristide was posted. Instead, simply add a link to [your later question](https://math.stackexchange.com/questions/3272651/fibration-with-t2?noredirect=1#comment6730205_3272651) where you asked it with stronger hypotheses.
Comment: @LeeMosher You are right.Sorry
Answer: Let $L$ be a $p$-lens space i.e the quotient of $S^{2n-1}, n>1$ by the action of $\mathbb{Z}/p$, $H_1(L,\mathbb{Z})$ is not trivial implies that $H^1(L,\mathbb{Z}/p)$ is trivial, but $H^1(S^3,\mathbb{Z}/p)$ is trivial.
Integral homology of lens space.
Comment: Yes, because it is a product, apply Kunneth.
Comment: If M and N both compact and connected, What about this case?
Comment: The lens space and the sphere are compact and connected.
Comment: You mean for all case that is incorrect?
Comment: if $N$ is torus ie, there is a fibration M to $T^{2}$, is induced homomorphism is injective?
Comment: Which is product? Total space or $T^{2}$?

Induced homomorphism is injective


Save as new name each time

Question: I can save a screenshot on a timer, but how could I have it save as a new name and not overwrite every time?
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
                           Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(bitmap as Image);

graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

bitmap.Save(@"c:tempscreenshot.bmp", ImageFormat.Bmp);

Comment: may be you can try with append current datetime in name.
Comment: You don't need to do `bitmap as Image`. Just use `bitmap`.
Answer: You can use the handy method: Path.GetRandomFileName()
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
              Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(bitmap as Image);

  graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

bitmap.Save("c://" + Path.GetRandomFileName() + ".bmp", ImageFormat.Bmp);

Answer: You just need to generate a unique name every time. There are several possibilities. One would be to add a datetime-string at the end:
Bitmap bitmap = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
              Screen.PrimaryScreen.Bounds.Height);

Graphics graphics = Graphics.FromImage(bitmap as Image);

  graphics.CopyFromScreen(0, 0, 0, 0, bitmap.Size);

bitmap.Save(@"c:tempscreenshot" + DateTime.Now.Ticks + ".bmp", ImageFormat.Bmp);

Comment: Thank you so so much I really appreciate it. You made my day. If I can do anything to repay you , just name it. Follow on twitter? itunes review? Thanks again
Comment: No problem, happy to help. If you're interested, this is my twitter handle : @Kennethtruyers
Answer: Use an integer (or some other numeric type) and increment it within your timer.  Then call your save method with something like:
bitmap.Save(string.Format("c:tempscreenshot.{0}.bmp", counter), ImageFormat.Bmp);

or use a GUID:
bitmap.Save(string.Format("c:tempscreenshot.{0}.bmp", Guid.NewGuid().ToString("N")), ImageFormat.Bmp);

Answer: You can generate a new filename everytime based on the current time. Something like this:
string GenerateFilename() {
    string file = DateTime.Now.ToString("yy.MM.dd HH.mm.ss") + ".bmp";
    return @"C:\" + file;
}

The good thing about using this approach is that when you browse the folder where you're saving the files, they will be sorted.
and then use it in your existing code:
bitmap.Save(GenerateFilename(), ImageFormat.Bmp);

You can also prepend any text (like image- or something) to the filename.
Another option would be append an integer to the end of the filename, like some copy handling programs do.
Answer: There is already something for that:  Path.GetTempFileName()

Save as new name each time


How To setup a Mass Mail server using php / Linux?

Question: What is required to set an mass mail sever using Linux and php  , and where can i find some steps for that , what do you recommend .
Best Regards
Comment: Find steps on Google........
Comment: StackOverflow is for questions about _specific_ problems, not general how-to stuff like this.
Comment: [What have you tried?](http://www.whathaveyoutried.com)
Answer: Check out those links,

Sending mass email using PHP
Mass mail using PHP from my web application
How to build a bulk email sending application in php
How to setup a bulk email sender program

May this help you.
Comment: Thank you the links are great


I need a set which uncountable has one property.

Question: I am looking for a subset $A$ of a topological space $X$ such that $A$ is uncountable but when you remove one point then become a countable, (i.e. $A-\{x\}$ become countable).
I suspect that $\omega_1$ could serve us but I cannot show how ? and in what topology?
Comment: The corresponding thing with countable sets would be a countably infinite set that became finite with the removal of one element, which is also impossible.  In fact, removing any subset of smaller cardinality cannot reduce the cardinality of any infinite set.
Answer: This is impossible. If $A$ is an uncountable set, and $x\in A$, then $A\setminus\{x\}$ is always uncountable. Topology has nothing to do with this.
Comment: @Dayana: No, it doesn't. It means that if $A$ is any uncountable set, then $|\omega_1|\le|A|$, i.e., there is an injection $f:\omega_1\to A$. There is no uncountable set that is strictly smaller in cardinality than $\omega_1$.
Comment: what does it mean a smallest uncountable set which is $\omega_1$, it is not mean, when you remove something then it will not stay uncountable !
Comment: Thanks for explanation. I understood.
Comment: More generally, for any set $A$ of  *infinite* cardinality, $A\setminus\{x\}$ has the same cardinality as $A$.
Comment: @Dayana: You're welcome.


Using Banach's Fixed Point Theorem to show existence and uniqueness of global critical points of perturbations of quadratic functions

Question: I have a question regarding the existence of a global critical point for perturbations of quadratic functions, which is motivated by the study of Quantum Field Theories in dimension $d=0$. Consider the following function in one variable
$$
S(x) = \frac{\alpha}{2} x^2 - \sum_{k=1}^{\infty} \frac{\lambda_k}{k!} x^k,
$$
where $\alpha > 0$ and $\lambda_k > 0$ for all $k \geq 1$. The goal is to show that for sufficiently small $\lambda_k$, this function has a unique critical point $x_0$ within a small box $B$ around $0$. So one can consider the equation $S'(x) = 0$, defining such critical point $x_0$. This equation can be written as $x = T(x)$, where
$$
T(x) = \sum_{k=1}^{\infty} \frac{\alpha^{-1} \lambda_k}{(k-1)!} x^{k-1}
$$
At first glance, one might be inclined to apply Banach's Fixed Point Theorem to establish the existence and uniqueness of a fixed point for the equation $x = T(x)$. This would imply that $x_0 = \lim_{N \rightarrow \infty} T^{N}(x)$. Page 14 of Etingof's "Mathematical ideas and notions of Quantum Field Theory" touches upon this idea (albeit in a more general setting) without providing a thorough explanation. Etingof claims that, in the sense of a "power series norm", $T$ is a contracting mapping. However, I have been struggling to make sense of this statement. The question is: What precisely does the term "power series norm" refer to? Alternatively, which specific Banach space norm should be considered to make this statement accurate?
Answer: I'm unfamiliar with Etingof's formalism, all I'm going to prove is that, for sufficiently small $\lambda_k$, you can indeed use Banach's fixed point theorem to get a unique fixed point. As such, my hypotheses may be less than optimal for the context this is from.
Since the points are just real numbers, we're going to use the usual $|\cdot|$ absolute value norm. To apply Banach's fixed point theorem, we need a closed and bounded subset $B\subset\mathbb{R}$ such that $T(B)\subset B$. Choosing $B:=[-1,1]$, we get for all $x\in B$:
$$
|T(x)|
\leq \sum_{k=1}^\infty \frac{\alpha^{-1} \lambda_k}{(k-1)!}|x|^{k-1}
\leq \sum_{k=1}^\infty \frac{\alpha^{-1} \lambda_k}{(k-1)!}.
$$
Therefore, if the $\lambda_k$ are small enough so that $\sum_{k=1}^\infty \frac{\alpha^{-1} \lambda_k}{(k-1)!}\leq 1$, we have $T(B)\subset B$.
Now we need $q\in(0,1)$ such that $|T(x)-T(y)|\leq q|x-y|$. Since $x\mapsto x^k$ is $k$-Lipschitz, we have :
$$
|T(x)-T(y)|
\leq \sum_{k=2}^\infty \frac{\alpha^{-1} \lambda_k}{(k-1)!}|x^{k-1}-y^{k-1}|
\leq \sum_{k=2}^\infty \frac{\alpha^{-1} \lambda_k}{(k-2)!}|x-y|,
$$
and we can apply the theorem and get a unique fixed point in $[-1,1]$ if the $\lambda_k$ are small enough to also have $\sum_{k=2}^\infty \frac{\alpha^{-1} \lambda_k}{(k-2)!} < 1$.
NB: I chose $B=[-1,1]$ almost arbitrarily, this works with $B=[-R,R]$ for any $R$. The only difference is that the bounds on $\lambda_k$ would get stronger for bigger $R$, and weaker for smaller $R$.
NB 2: I don't know if this useful, but this would also work for any arbitrary $\lambda_1>0$, the appropriate subset would just be centered around $T(0)=\alpha^{-1}\lambda_1$: $B=[\frac{\lambda_1}{\alpha}-R\, ,\ \frac{\lambda_1}{\alpha}+R]$.
Comment: I appreciate your response greatly. It certainly fulfills the purpose. However, I'm still puzzled about the meaning of "power series norm" as mentioned by Etingof.
Comment: Honestly I am too. It's possible I just haven't encountered what they're talking about, but to me "power series" would imply it's a norm of functions, yet the points are in Euclidian space.


Internal DNS delegate to external host

Question: We have been facing an issue with internal DNS delegation.
Here is a description of our architecture and the issue:
Architecture
Domain1

DHCPDNS1 and DHCPDNS2   (Windows Server 2012)

Domain2

extDNS1 and extDNS2   (Windows Server 2003) - external DNS
intDNS1  and intDNS2   (Windows Server 2003) - internal DNS for Domain2 servers
srv1 and srv2   (Windows Server 2003) - Web servers

Here is description of our architecture:
We have two Active Directory domains (forests) in our environment. The first is, "Domain1" (which we use for general purpose servers and users/client machines) and "Domain2" (which we use for web development servers).
Domain2 also includes our external DNSes "extDNS1" and "extDNS2".  We have quite a few websites that are hosted externally (outside both "Domain1" and "Domain2") but need to be referenced internally on our webservers ("srv1" and "srv2") in "Domain2" for integration with other websites and portals. These websites use "extDNS1" and "extDNS2" as their DNS. Inorder that "srv1" and "srv2" are able to reference these external servers, we have setup delegates for these domains in the internal DNS in Domain2 on servers "intDNS1" and "intDNS2". These delegates point to our servers "DHCPDNS1" and "DHCPDNS2" in "Domain1" in order to get the external DNS address. "DHCPDNS1" and "DHCPDNS2" are our DHCP servers.
This setup worked perfectly till we had "DHCPDNS1" and "DHCPDNS2" on Windows Server 2008. We recently migrated these two servers to Windows Server 2012, with the same DHCP and DNS settings they had earlier. After migration, on "srv1" or "srv2", we are not able to resolve the IP addresses of our domains whose delegates point to "DHCPDNS1" and "DHCPDNS2", on ping.
Here are some observations and some things we tried:

If we ping these subdomains on any client machine or server in Domain1 or on DHCPDNS1 or DHCPDNS2, it is able to retrieve the external IP address, and then stores this in its DNS resolver cache. As long as these records exist in DHCPDNS1's or DHCPDNS2's resolver cache, srv1 and srv2 (and all servers in Domain2) are able to ping those subdomains. When the resolver cache records on DHCPDNS1 and DHCPDNS2 expire, ping from the Domain2 servers fail to work. Remember, this is only for those domains who have a delegate pointing to DHCPDNS1 and DHCPDNS2. Again, our aim is that the servers in Domain2 are able to retrieve the external IP address, which is not possible as the external DNS is in the same domain.
When changed the Dynamic Updates from "None" to "Nonsecure and secure" on DHCPDNS1 and the Domain2 servers were immediately able to route their ping requests through DHCPDNS1 and DHCPDNS2 successfully. This worked for 7 days and ping requests fail to resolve on all Domain2 servers now. I'm not sure if it has anything to do with Aging on DHCPDNS1 which is set to 7 days, by default.

Hoping that someone can help throw some light here.
Once again, our aim is that all servers in Domain2 (which includes the external DNSes) must be able to ping the external addresses (which use extDNS1 and extDNS2 as its DNS). Thus, the internal DNS in domain Domain2 must point to the external IP address.
Answer: We setup forwarding on DHCPDNS1 and DHCPDNS2 to 188.8.131.52, and now all servers in Domain2 can resolve those addresses.

Internal DNS delegate to external host


Linux Raw Sockets: Block Packets?

Question: I've written my own packet sniffer in Linux.
I open a socket with socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL)) and then process the Ethernet packets - unpacking ARP packets, IP packets (and ICMP / TCP / UDP packets inside those).
This is all working fine so far.
Now I can read packets like this - and I can also inject packets by wrapping up a suitable Ethernet packet and sending it.
But what I'd like is a means to block packets - to consume them, as it were, so that they don't get further delivered into the system.
That is, if a TCP packet is being sent to port 80, then I can see the packet with my packet sniffer and it'll get delivered to the web server in the usual fashion.
But, basically, I'd like it that if I spot something wrong with the packet - not coming from the right MAC address, malformed in some way, or just breaking security policy - that I can just "consume" the packet, and it won't get further delivered onto the web server.
Because I can read packets and write packets - if I can also just block packets as well, then I'll have all I need.
Basically, I don't just want to monitor network traffic, but sometimes have control over it. E.g. "re-route" a packet by consuming the original incoming packet and then writing out a new slightly-altered packet to a different address. Or just plain block packets that shouldn't be being delivered at all.
My application is to be a general "network traffic management" program. Monitors and logs traffic. But also controls it too - blocking packets as a firewall, re-routing packets as a load balancer.
In other words, I've got a packet sniffer - but if it sniffs something that smells bad, then I'd like it to be able to stop that packet. Discard it early, so it's not further delivered anywhere.
(Being able to alter packets on the way through might be handy too - but if I can block, then there's always the possibility to just block the original packet completely, but then write out a new altered packet in its place.)
Answer: What you are looking for is libnetfilter_queue. The documentation is still incredibly bad, but the code in this example should get you started.
I used this library to develop a project that queued network packets and replayed them at a later time.
Comment: Thanks for that. I didn't know one could drop packets from userspace in Linux.
Answer: A bit of a tangent, but it was relevant when I was resolving my problem. Blocking raw packets is relatively complicated, so it might make sense to consider doing that at a different layer. In other words, does your cloud provider let you set up firewall rules to drop specific kind of traffic?
In my case it was easier to do, which is why I'm suggesting such a lateral solution.
Comment: At the time I was doing this, I was running my own cluster of servers and did have firewall rules set up, of course. Somewhat the idea here was that I was looking into creating a singular "network traffic management" daemon to do the whole job - firewall, packet router / load balancer, etc. (with potential for on-the-fly "learning" too, maybe) - dynamically in one place, rather than have a dozen static text files in "/etc". I changed jobs since, but  applying my coding to make the net admin job a whole lot easier was where I was going at the time.

Linux Raw Sockets: Block Packets?


Dynamic Fields at content type level

Question: I got a site where we got pages tagged with several taxonomy terms. We also got several Contactblocks (added as Content Type & displayed by Views) that are tagged with the same set of taxonomy terms.
The Content Type "Contactblock" has the fields E-Mail, Phone & Room. Those Fields may vary from page to page. The reason behind this is some employees have different positions and those have to be displayed on different pages with different information. May way to go atm was to add multiple Contactblocks but its not clean enough for me.
My idea was to display for each tagged term a specific field of E-Mail, Phone & Room. But idk how the system can associate it then..
Atm its like page<->taxonomy term<->contactblock but it should be like page<->taxonomy term, for each tax term<->create fields: mail, phone & room
Any idea how I can solve this? Any better idea is apreciated
Comment: `it should be like page<->taxonomy term<->contactblock<->for each tax term<->create fields: mail, phone & room` I think you mean **page<->taxonomy term, for each tax term<->create fields: mail, phone & room** cause no point in creating the mail, phone & room fields in the tax terms and also in the Contactblock.
Comment: You could do **page<->contactBlock** will that work for you? or do you really need those tax term tags?
Comment: how woud this improve my situation @NoSssweat ?
Comment: no need to fill the Database with tax terms, I guess.
Comment: I use the tax terms to associate contactblocks of employees to several fields that they work at..
Comment: @NoSssweat yes right!
Answer: Yes you can add fields: mail, phone & room to each of your tax terms, but the problem would be that all your employees would have the same mail, phone & room, because the fields belong to the tax term and not the employee. Unless you create a unique tax term for each of your employees this would work, but why do this when page<->contactBlock will do the same?
So either you stick with page<->taxonomy term<->contactblock
or go with page<->contactBlock using the Entity Reference module in D7 (for D8 Drupal Core already has this module's features). This option will save you save Database space since you don't create tax terms.
Comment: I'm I right that I have to still add multiple contactblocks for every page and every position the employee works at?
Comment: For each employee you need to create a contact block for them. I assume in the employee profile you have a field for his position. `some employees have different positions and have to be displayed on different pages` You can then use views to filter employees by position and show only employees with position "X".
Comment: right and the positions are my tax terms. How should I filter them if I remove the taxonomy from the relation?
Comment: Also that wouldn't solve the fact that I still have to add multiple Contactblocks that contain the different mail, phone etc...
Comment: `How should I filter them if I remove the taxonomy from the relation?` You can add a Contextual Filter with a default fixed value of the employee position.
Comment: @SaifDeen One thing that wasn't clear to me, where are you adding the employee name and last name? Are you creating drupal users for each employee? or did you create a content type where you add each employee? or does the ContactBlock also contain the employee name and lastname fields?
Comment: I have a content type that has all the necessary fields....

Dynamic Fields at content type level


How to create a conditional index column in R based on 2 variables in the dataset?

Question: I'm currently in the process of converting a SAS script to R. I'm quite familiar with R but not too much with SAS. I understand what the following code is trying to do but I haven't come across this type of indexing in R before and could really do with some guidance.
Below is the block of SAS code I am trying to convert to R:
data LA_5_c;
    do index = 1 by 1 until(last.Entity_name);
    do index = 1 by 1 until(last.Local_Authority);
set LA_5_B;
by business_reg_number Entity_name Local_Authority;
if index gt 3 then delete;
output; end; end;
run;

So I understand that we are creating a new index column based on the 2 variables Entity_name and Local_Authority. We don't want any index greater than 3 either which most likely corresponds to the fact there are 3 different years in the data.
I understand that if the Entity_name and Local_Authority repeat the same answers the rows will be indexed as 1, 2, 3, 1, 2, 3.... and so on. But also want to include cases where they don't repeat so periodically. Say if the Entity_name and Local_Authority changes after only 1 repetition so the index for this block would be 1, 2, 1....
So I understand what the code is trying to do I just don't know how to go about implementing this in R. I have looked into the setindexv() function and also using cbind along with nrow() to create an index column but I'm quite stumped as any combination I try isn't producing near what I want.
Any guidance would be much appreciated!
########
EDIT:
I have attached how I would like my data to look like below (result displayed in SAS but I would like in R. The original data is the same minus the Index column.
Answer: It would be helpfull if you could post some sample data and the desired result, as this is not entirely clear to me.
However, this might already help you:

group your dataset by Entity_name and Local_Authrority
create a column with a constant value of 1, that serves as an intermediate helper variable.
Calculate the index column using the cumsum() function to calculate the cumulative total of the constant variable for each combination of Entity_name and Local_authority. This basicly means that if the value for the Entity_name and Local_authority column are repeated across subsequent rows, the index column takes the value of 1, 2, 3, ... . Whenever a new combination of Entity_name and Local_authority occurs, the value for the index column start counting from 1 onwards again.
Filter rows on index <= 3.
Remove the constant column from the dataframe.

Below is an example with sample data:
First, create some sample data:
df <- data.frame("Entity_name" = c("A", "A", "A", "B", "B", "B", "B", "C", "D", "D"),
           "Local_Authority" = c("F", "F", "F", "F", "G", "G", "G", "H", "I", "I"))
#Output:
> df
   Entity_name Local_Authority
1            A               F
2            A               F
3            A               F
4            B               F
5            B               G
6            B               G
7            B               G
8            C               H
9            D               I
10           D               I

Next, create the index column using functions from the dplyr package.
library(dplyr)

df <- df %>%
  arrange(Entity_name, Local_Authority) %>%
  group_by(Entity_name, Local_Authority) %>%
  mutate(constant = 1,
         index = cumsum(constant)) %>%
  filter(index <= 3) %>%
  select(-constant)

The output looks like this:
   Entity_name Local_Authority index
   <chr>       <chr>           <dbl>
 1 A           F                   1
 2 A           F                   2
 3 A           F                   3
 4 B           F                   1
 5 B           G                   1
 6 B           G                   2
 7 B           G                   3
 8 C           H                   1
 9 D           I                   1
10 D           I                   2

Comment: Hi there, thanks for getting back to me. As per your request I edited the original question to show some of the data I'm working with and what I want to achieve. I tried your provided code but it didn't produce exactly what I wanted. It's definitely closer to what I want but still not getting my required output. From the output in SAS provided above it seems like each year should refer to the same index (even though the data is not arranged by that variable) , however when I run your code the year 2020 references both 2 and 3 in two different cases
Comment: Thanks, I edited your code a bit and played around with the arrange and group by variables and finally got my desired output. Thanks very much for your help!!


How to calculate the coordinates of point C in an isosceles triangle?

Question: I hope this is not a duplicate but maybe I don't know the right keywords.
In the following diagram, I know the coordinates of $A=(X_a, Y_a)$ and $B=(X_b, Y_b)$, as well as the distance $h$. What I'm looking for is the coordinates of point $C$. Point $O$ is the midpoint between $A$ and $B$.

I know that I can use the Pythagorean theorem in order to calculate $AC$ and $BC$, but how would I proceed?
If that helps, I need this for rotating a rectangle using python and openCV.
Comment: This may help: [How to find the third vertex of an isosceles triangle given 2 points](https://math.stackexchange.com/questions/865358/how-to-find-the-third-vertex-of-an-isosceles-triangle-given-2-points)
Answer: You have
$$\vec{A} = \left [ \begin{matrix} x_A \\ y_A \end{matrix} \right ], \quad
\vec{B} = \left [ \begin{matrix} x_B \\ y_B \end{matrix} \right ]$$
Because $\vec{O}$ is halfway between $\vec{A}$ and $\vec{B}$, it is
$$\vec{O} = \frac{\vec{A} + \vec{B}}{2} = \left [ \begin{matrix} \frac{x_A + x_B}{2} \\ \frac{y_A + y_B}{2} \end{matrix} \right ]$$
The unit direction vector from $\vec{A}$ to $\vec{B}$ is $\hat{U}$:
$$\hat{U} = \frac{\vec{B} - \vec{A}}{\left\lVert \vec{B} - \vec{A} \right\rVert} = \left [ \begin{matrix} \frac{x_B - x_A}{\sqrt{(x_B - x_A)^2 + (y_B - y_A)^2}} \\ \frac{y_B - y_A}{\sqrt{(x_B - x_A)^2 + (y_B - y_A)^2}} \end{matrix} \right ] = \left [ \begin{matrix} x_U \\ y_U \end{matrix} \right ]$$
The other unit direction vector $\hat{V}$ is $\hat{U}$ rotated 90° degrees clockwise:
$$\hat{V} = \left [ \begin{matrix} y_U \\ - x_U \end{matrix} \right ] $$
Thus, if $\vec{C}$ is at distance $h$ from $\vec{O}$ in the direction of $\hat{V}$, then
$$\vec{C} = \vec{O} + h \hat{V} = \left [ \begin{matrix} \frac{x_A + x_B}{2} + h y_U \\ \frac{y_A + y_B}{2} - h x_U \end{matrix} \right ]$$
Comment: Thank you for the quick answer! I tried to convert this in python but I don't seem to get the expected coordinates. Is it wrong to consider that vectors can be translated to point coordinates?
Comment: Oh, could it be that it's `xA+xB` instead of `xA+yA` at the very last formula?
Comment: @Phi: Yes, the $x$ component of $\vec{C}$ should be $(x_A + x_B)/2 + h\,y_U$. Fixed now.
Comment: Thanks again, I really appreciate the help!


Evaluating $ \sum\limits_{n = 1}^{\infty}{\binom{2n}{n} \frac{1}{5^n}} $

Question: Here is the question a little bigger:
$$ \sum_{n = 1}^{\infty}{\binom{2n}{n} \frac{1}{5^n}} $$
This is given as an example (not an exercise) in my textbook on how to solve sums involving binomial coefficients. I understand almost all of the example, but one part losses me.
First, we set:
$$ \binom{2n}{n} = \frac{1}{2 \pi i}\int_{C}{\frac{(1 + z)^{2n}}{(5z)^{n}}\frac{dz}{z}} $$
So far so good. Then we simply substitute this value to get:
$$ \sum_{n = 1}^{\infty}{\binom{2n}{n} \frac{1}{5^n}} = \frac{1}{2 \pi i} \sum_{n = 1}^{\infty}{\int_{C}{\frac{(1 + z)^{2n}}{(5z)^{n}}\frac{dz}{z}}} $$
The book then says that if we can show convergence is uniform on the closed curve chosen, then we can switch the order of summation and integration. The book then shows that convergence is uniform on the unit circle. This makes sense. What happens next though I don't understand at all. Once they show convergence on the unit circle this simply state this:
$$ \sum_{n = 1}^{\infty}{\binom{2n}{n} \frac{1}{5^n}} = \frac{5}{2 \pi i}\int_C{\frac{dz}{3z - 1 - z^2}} $$
Can anyone shed some light on how this equality was deduced?
Thanks.
Comment: they skipped the part where you compute the power series
Comment: Please avoid titles that are entirely in $\TeX$.
Comment: Related: http://math.stackexchange.com/q/69270/
Answer: Hint:  Let $x=\frac{(1+z)^2}{5z}$ and use
$$\sum_{n=0}^{\infty}x^n=\frac{1}{1-x}$$


IBM 3650M2 "battery status alert"

Question: I have just installed a new 7 server cluster for a client... five servers are 3850M2 and the lasst two are 3650M2. All the servers play well together (vmotion etc) but we constantly have a battery status alert on the two 3650M2 servers.
IBM sent us new batteries before xmas which we swapped out (the batteries on the raid controller)... but here we are a week later with the same alert still present. vSphere appears in constant warning status telling us that the batteries are not charged.
Is this a known issue with vSphere on this model, or is there something we can do to remove this?... the interesting thing is that when I rebooted one of the hosts this morning so I could look in the Raid Configurator screen, it reports the batteries as fully charged.
Cheers
Answer: I've seen the same problem with ESX4 on Dell R710's with PERC 6i Controllers - it's (somewhat) erratic but affects all the hosts regularly. Other's have reported the same issue on the VMware Communities site in a number of threads like this one. I thought it was a bug limited to the PERC6i but it may be that this is an issue with VMware's hardware monitoring code in ESX 4.

IBM 3650M2 "battery status alert"


How do I generate random numbers but not repeating and within a certain range based on user input?

Question: Currently, I am experimenting some codes regarding/about random numbers. The problem is, when I run the program, input any number (ex. 12), I, sometimes get the correct and sometimes wrong answer. The correct answer must be any non repeating random numbers based on user input. (ex. input 5, output must be 1. seats[12]=1, 2. seats[19]=1,..., 5. seats[47]=1). I do not know what to do and yeah help me coders!
Here's the code:
#include<stdio.h>
#include<conio.h>
#include<time.h>
main()
{
    int x,y,chc1A,seats[50]={};
    printf("Enter a number: ");
    scanf("%d",&chc1A);
    srand(NULL);
    for(x=0;x<chc1A;x++)
    {
        if(seats[rand()%50]==0)
            seats[rand()%50]=1;
        else
            x--;
    }
    for(x=0,y=1;x<50;x++)
        if(seats[x]==1)
        {
            printf("%d. seats[%d] = %d\n",y,x,seats[x]);
            y++;
        }
    getch();
}

I do not really know what's wrong please enlighten me.
I run and coded this on Dev C++
What I want to do is: generate random numbers between 0-49 and putting it in an array seats[50]. (ex 38 then put 1 in array seats[38]). Btw this code represents passengers sitting on a bus with 50 seats. So the "1" means that the seat is occupied.
Comment: Please edit your question to add details and crucial information, don't put them in comments.
Comment: The correct answer must be any non repeating random numbers based on user input. (ex. input 5, output must be 1. seats[12]=1, 2. seats[19]=1,..., 5. seats[47]=1)
Comment: Can you add a bit more context? Is zero a random number that you accept?
Comment: The random number I accept is 1 @J...S
Comment: @user3121023 uhm is it necessary to shuffle the array??
Comment: Can you tell us, step by step, how you are trying to solve the problem in the program that you posted?
Comment: @J...S uhh the code that I have posted was about uhh generating random numbers between 0-49 and putting it in an array seats[]. (ex 38 then put 1 in array seats[38]). Btw this code represents passengers sitting on a bus with 50 seats. So the "1" means that the seat is occupied.
Comment: @user3121023 ohh I get it what you are trying to say. Wait lemme try it
Comment: @user3121023 I tried it but it makes my code longer
Answer: This part may cause problem.
for(x=0;x<chc1A;x++)
{
    if(seats[rand()%50]==0)
        seats[rand()%50]=1;
    else
        x--;
}

I think by
    if(seats[rand()%50]==0)
        seats[rand()%50]=1;

you meant to generate a random number, use that as index to seats and if seats[random_no] is 0, set seats[random_no] to 1.
But the random number in the if statement and the one in its body are different numbers.
You could use
    int index = rand()%50;
    if(seats[index]==0)
        seats[index]=1;

Consider changing the signature of your main() function. See What are the valid signatures for C's main() function?

conio.h is not part of the standard, try to avoid its usage. Same goes for getch() as it's from conio.h.

srand() expects an unsigned int as argument and NULL is not of that type. See here.
Include stdlib.h to use srand().

And checking the return value of scanf() is a good idea. You can see if it failed or not.
Comment: Ohhh okk lemme try it! Also thanks for this detailed answer


How to send status information from a Web service while is being executed?

Question: I'm new to web development so I'm not sure what's the best option for the problem that I'm having.
Basically I have a web application that calls a web service for processing some data.
This process may take a long time (hours) and I would to know if there is an easy way to send some status information to the client from time to time.
Right now, the client makes the request from the browser and it just waits there until it finishes.
How can I send some information from the web service? I would like to send a percentage and some additional text specifying what is being done.
Thanks
Answer: Maybe you can poll another method for status?
Comment: How can I do that? The execution on the client is stopped waiting for the web service to finish.
Comment: You can spawn a new thread for polling just before call, and kill it after you get result...
Answer: WCF services can be marked as [OneWay] so that they don't return a response.
or, you could have the service kick off the process in an async manner and then just return to the client that the process has/or hasn't kicked off.
Then, the client can poll another method as the other user has suggested.
If you process takes hours you definitely can't use a sync service because you'll hit your execution timeout or rather the connection timeout for the client.
Comment: Thanks for the information. I didn't know about the [OneWay] option.
Comment: The gotcha about OneWay is that even if your service errors you won't know so it makes the polling subsequent step all the more important.

I'd say that if you're comfortable with dispatching  a "job" or async processing from within the syncronous service then you'll get both: feedback from the service during the initial kickoff and as well the ability to run a long running process in the wcf service.

You can see here that Steve Gilham notes that even a duplex service may do the trick: http://stackoverflow.com/questions/1142698/dealing-with-a-longer-running-process-in-wcf
Answer: If I were you, I would make the original request asynchronous, as in instead of waiting for the response, it just "starts" the task and returns immediately.  Then I would have a separate method on your web service that the app can poll periodically to get the status of the job.  once it completes, it can display the data like the original request was doing.
if you want to do it synchronously, you can turn off Response.Buffer and write directly to the response.


Proving that copulas are Lipschitz continuous

Question: A copula is a function $C:[0,1]^2\to[0,1]$ such that $C(x,0)=C(0,x)=0$ for all $x\in[0,1]$, $C(x,1)=C(1,x)=x$ for all $x\in[0,1]$, and
\begin{equation}\label{ineq}
 C(x_2,y_2)-C(x_1,y_2)-C(x_2,y_1)+C(x_1,y_1)\ge0\tag{*}
\end{equation}
for all $(x_1,y_1), (x_2,y_2)\in[0,1]^2$ with $x_1\le x_2$ and $y_1\le y_2$. I am trying to show that a copula is Lipschitz continuous in the following sense:
$$
 |C(x_2,y_2)-C(x_1,y_1)|
 \le|x_2-x_1|+|y_2-y_1|
$$
for all $(x_1,y_1),(x_2,y_2)\in[0,1]^2$.
Suppose that $x_2\ge x_1$ and $y_2\ge y_1$. Using the definition of a copula, we have that
$$
x_2-x_1-C(x_2,y_1)+C(x_1,y_1)\ge0
$$
and
$$
y_2-y_1-C(x_2,y_2)+C(x_2,y_1)\ge0.
$$
Adding these two inequalities, we obtain
$$
C(x_2,y_2)-C(x_1,y_1)
\le x_2-x_1+y_2-y_1.
$$
Since copulas are increasing in each argument, $
C(x_2,y_2)
\ge C(x_2,y_1)
\ge C(x_1,y_1)
$
so that
$
C(x_2,y_2)-C(x_1,y_1)\ge0
$
and hence
$$
|C(x_2,y_2)-C(x_1,y_1)|\le x_2-x_1+y_2-y_1,
$$
when $x_1\le x_2$ and $y_1\le y_2$.

We also need to consider the case when $x_1\le x_2$ but $y_1\ge y_2$. If I understand correctly, inequality \eqref{ineq} is not valid in this case and I am not sure how to proceed. How can we proceed with the proof when $x_1\le x_2$ but $y_1\ge y_2$?

Any help is much appreciated!
Comment: However, sligthly more complicated case is when $x_2\geq x_1, y_1\geq y_2$. Then, you need to divide the $[0,1]^2$ into two parts.
Comment: As you said, A copula is non-decreasing in each argument .Therefore, $C(x2, y2)\geq C(x2, y1)\geq C(x1, y1)$. Hence, $C(x2, y2)-C(x1, y1)\geq 0$
Comment: well, if you assume $x_2\geq x_1$ and $y_2\geq y_1$ then trivially $C(x2,y2)−C(x1,y1)\geq 0\geq -(x2−x1+y2−y1)$.
Comment: @AlbertParadek Thanks for your comment! How does it follow that $C(x_2,y_2)-C(x_1,y_1)\ge0$? A copula is non-decreasing in each argument, right? Can we conclude that $C(x_2,y_2)-C(x_1,y_1)\ge0$ if $x_2\ge x_1$ and $y_2\ge y_1$?
Comment: @AlbertParadek Thanks for drawing my attention to the case when $x_2\ge x_1$ but $y_2\le y_1$ (I edited the question accordingly). If I understand correctly, the inequality in the definition of a copula is no longer applicable in this case. You mentioned that $[0,1]^2$ needs to be divided into two parts. Could you please elaborate on that?
Answer: We have $x_1\le x_2$ but $y_1\ge y_2$. Then either  $C(x_2, y_2)\geq C(x_1, y_1)$ or $C(x_2, y_2)\leq C(x_1, y_1)$. Take the case when $C(x_2, y_2)\geq C(x_1, y_1)$.  Then, you want to prove that
$$
C(x_2, y_2)- C(x_1, y_1)\leq x_2-x_1 + y_1-y_2.
$$
From the marginal monotonicity you get
$$
C(x_2, y_2)- C(x_1, y_1)\leq C(x_2, y_2)- C(x_1, y_2).
$$
Now, you are in the previous setting, i.e. holds that
$$
C(x_2, y_2)- C(x_1, y_2)\leq x_2-x_1.
$$
Hence, $C(x_2, y_2)- C(x_1, y_1)\leq x_2-x_1. $
In the other case when $C(x_2, y_2)\leq C(x_1, y_1)$, we obtain the same
$$
C(x_2, y_2)- C(x_1, y_1)\leq y_1-y_2.
$$
Hence, together,
$$
C(x_2, y_2)- C(x_1, y_1) \leq \max(x_2-x_1,y_1-y_2) \leq x_2-x_1+y_1-y_2.
$$


Qt Frame with movable border

Question: This is probably me lacking in Google-fu.
I happen to be programming in PySide, but I assume that everyone names this feature the same across GUI toolkits.  It'll certainly use the Qt nomenclature.
What's the name of the widget, frame, or whatever, that lets you have an adjustable border between two frames?  Here's a screenshot from Argos -- I can grab the heavy vertical line and change the border between the "files" menu and the image window.
With a keyword, I can look it up.
Answer: You are looking for QSplitter. Just add the widgets inside with addWidget(QWidget *widget)
Comment: That's what I'm looking for!  For some reason one of my widgets isn't adjusting itself correctly, when a fixed QHBoxLayout allowed that.  But that's a different question.

Qt Frame with movable border


Migrate Linux Passwords into Active Directory

Question: I have a lot of boxes that are all local user accounts. We want to start consolidating them into an Active Directory system. (I know... I know.. It has to be Active Directory, not openldap, kerberos or anything like that)  I am looking for some way to not only move the accounts, but most importantly move the passwords that are already encrypted.
Is there any sort of PAM libraries or other types of scripts that could be used to just move from one setup to another?
Comment: So, I guess the problem is that any way I look at this, AD needs to have the password in clear text before it can be added to an AD system.
Answer: The issue that I see is that local unix passwords are salted hashes.  I don't think ActiveDirectory does, and there is no way to get from a salted hash to a plaintext password.  To do this you would have to essentially sniff the password as the user enters it and validates it against the hash.  You can do this (it may or may not be easy), but it is wrong in principle.
Why are you so reluctant to change passwords?  I would investigate that first, because it seems to me that whatever the reason behind that reluctance, it is probably a security concern.
Comment: That makes sense, but it sounds like you have a password security issue brewing where people are likely to choose insecure passwords and leave them long enough that they might get guessed.
Comment: We are reluctant to have them change passwords, because we have over 400 users and getting them to do anything takes a bit of organization. Also, We are only using AD for part of the infrastructure and not everything, so we are not going to link this AD system to any linux boxes.
Answer: This seems impossible to me as well.  This is why, for future reference, people put a lot of effort into Kerberos authentication on Linux boxes, or going full on Windows domain compatibility with Samba/Winbind.  It nips this problem in the bud.
So, if your users already have parallel domain accounts they do not use on the Linux boxes, what would be easier is the reverse: getting Kerberos authentication that underlies AD to work on the Linux boxes, and change the PAM to prioritize authentication with AD/Kerb before local authentication subsystems.  Not sure if that makes sense, but you have hope if that is possible for you.  That is not as bad as it sounds.
Comment: They don't have any parallel systems in place. This would be an add on that we do to produce an AD network for people to use.  Maybe if everyone thought the AD system was successful we could move it over, but that is a long way from a reality.
Comment: @RaginBajin I hear you. I re-read the question and the comments. I have been in your position before, and those users live in their own little paradise as a result.  Sorry if I was pedantic, it seems like you are well aware of alternatives based on your comments.
Comment: No need to apologize.  Thanks for the ideas though, I appreciate it.


Updating multiple images in database

Question: Thanks in Advance
I have a problem with updating multiple images in the database. so i need a help...
what i am doing is:
In the case of update i am retrieving images data in the function and calling that function in the design page. The function includes the code of fetching images fom the data, am able to display images in the update page but am not able to update the images if any one of images is removed and then updating data so previous images is updating in the database, mean to say the previous images is coming in a form of array in the $_POST["AircraftImage"]
here is the code below:-
public function getimageswithaircraftid ($AircarftID){
    try{
        // Query to retrieve Aircraft Images from database...
        $query = mysql_query ("SELECT * FROM `aircraft_image` WHERE      `Aircraft_ID` = '".$AircarftID."' ");
    if (mysql_num_rows ($query) > 0){
        $tabledata = '';
        //$_POST["AircraftImage"] = array();
        $tabledata = "File Name		File Size	Image Preview	Delete	";
        while ($execute = mysql_fetch_object ($query)){
            $filepath = $execute->uploadpath;
            $split    = explode('/', $filepath);

            $tabledata .= "
".$split[5]."	";
            $tabledata .= "<input type=text name=AircraftImage[] value=".$split[5]."::".$execute->filesize. ">	";
            $tabledata .= "".$execute->filesize."	";
            $tabledata .= "uploadpath.">uploadpath." height=70 width=70 />	";
            $tabledata .= "AircraftImageId." class=delbutton>

";
            //$tabledata .= "<input type=text name=AircraftImage[] value=".$split[5]."::".$execute->filesize. ">";
        }
        print $tabledata;
    }
    }
    catch(Exception $ex){

    }
}

here is the code for inserting/updating images..
public function uploadimage ($AircraftImage = array()){
    if (!$this->Aircraft_ID){
        if (count ($AircraftImage) > 0){
        //set_time_limit (240);
        $q = mysql_query ("SELECT MAX(Aircraft_ID) as id FROM `aircraft` WHERE `IsDeleted` = 0 AND
         `User_ID` = '".$this->User_ID."'");
        $res = mysql_fetch_object ($q);
        $maxid = $res->id;
        foreach ($AircraftImage as $k=>$v){
            $split    = explode('::', $v);
            $fullpath = "http://localhost/pz_serveroriginal/uploads/".$split[0];
            //$fullpath = "http://pilotzeus.com/pz/uploads/".$split[0];
            $filesize = $split[1];
        // Insert into aircraft image with full path...
        // select maxid from aircraft

        $insert_query = mysql_query ("INSERT INTO `aircraft_image` (`Aircraft_ID`,`uploadpath`,`filesize`)
        VALUES ('".$maxid."','".$fullpath."','".$filesize."')");
        if ($insert_query == FALSE){
            throw new Exception ("Some Error Occurred while Saving Images");
        }

    }
    }

    }

    else{
        if (count ($AircraftImage) > 0){
            //DELETE ALL
            $deletequery = mysql_query ("DELETE FROM `aircraft_image` WHERE `Aircraft_ID` = '".$this->Aircraft_ID."' ");
            //set_time_limit (240);
            foreach ($AircraftImage as $k=>$v){
            $split    = explode('::', $v);
            $fullpath = "http://localhost/pz_serveroriginal/uploads/".$split[0];
            //$fullpath = "http://pilotzeus.com/pz/uploads/".$split[0];
            $filesize = $split[1];

            //check if current image is not equal to database image then insert into database
            // if image already exists or not

            $insert_query = mysql_query ("INSERT INTO `aircraft_image` (`Aircraft_ID`,`uploadpath`,`filesize`)
            VALUES('".$this->Aircraft_ID."','".$fullpath."','".$filesize."')");
            if ($insert_query == FALSE){
                throw new Exception ("Some Error Occurred while updating images");
            }
    }
}
    }

}

Comment: Can you please post your code you have done so far for updating images?
Answer: There are two way to update image(s) into aircraft_image table when you updating data,
1) You update all previous images by ID (Primary key)
           OR
2) You deleted all previous images for that particular Aircraft_ID and insert all new images for that.

UPDATE :

For that you need to remove that particular row with jquery
  ($('rowid').remove()), so when you delete any records from the table
  its remove that row from the HTML also. now when you refresh that page
  it will obviously not displaying that row even.

Let me know if you have any Query / Issues
Thanks!
Comment: the way u have said have done but the problem is suppose i have 4 rows of images data:
in first column it includes Filename
in second column it includes
in third column filesize
in fourth column image preview
in fifth column delete image button
so when i am deleting any image with the delete button then it is removing with the javascript from the database, but unfortunately the page is not refresh so thats why it is taking previous images array in a post....i hope u understand what i mean to say...
Comment: yes u are absolutely right but if i do so then the page is totally refreshed and it go to the top and the table is below....
i have tried with this after success location.href = url but after this done the page starts from the top and the table is below
Comment: For that you can use either AJAX or jQuery scrollTop() method for scrolling your page to particular Div Id.

Updating multiple images in database


Two-state CSS-only rollover without JavaScript

Question: I am trying to create a two-state CSS rollover, so when the user rolls over a box, the box changes color and another image appears to the side, and when they roll off the image to the side it disappears and the box reverts to the original state.
The page I am working on is here:
http://www.philippedollo.com/assign.htm
Is there any standards-compliant way to do this without JavaScript?
Answer: Below is a quick example using a link and the hover property in CSS.  You'll have to replace the .twoStateInner span with your image (and add float:left to it, changing the order of that and the other span to swap sides the image will apear on), and change the color as desired in your .twoState:hover CSS.
HTML:

    text
    foo

CSS:
.twoStateInner {
    display: none;
}

.twoState div {
    float: left;
}

.twoState:hover .twoStateInner {
    display: block;
}

.twoState:hover {
    color: red;
}

Also, here's a fiddle where you can see this in action.
UPDATE:
Changed div tags to span tags within the link based on Smirkin Gherkin's comment, as spans within links are standards compliant.
Comment: @Briguy: I would love to say yes on the IE6 front, but I can't. On the sites that I have control over (UK) based the level of IE6 usage in recent months has fallen but it still accounts for over 5% so a significant number of users would have issues. I would be tempted to say that a JavaScript solution for IE6 would cover most people as this would allow graceful degredation for most people. It depends on the levels of support that you want to provide. Personally I implement the compliant IE6 support and curse the browser that doesn't die.
Comment: I think that might work, do you see any issues with doing that with two unordered lists (one for the link, the other containing the images)?
Comment: @user784576 The bottom line is that you need a common parent that supports and uses the CSS :hover attribute, and both elements need to be children of that.  The "a" tag is the one that is most widely supported for :hover, but you could look into using other elements if you know which browser(s) and versions your users will be on.  I'd have to see your code to see what you mean, but as long as the above principles are applied, you should be good to go.
Comment: @Briguy37 - as far as I am aware the only mainstream browser that doesn't support `:hover` on elements that are not `a` is IE6. The question asked for a standards compliant solution and you have a block element (`div`) as a child of an inline element (`a`) which is not standards compliant. There is a solution using conditional comments that is standards compliant for a CSS menu at [CSSplay](http://www.cssplay.co.uk/menus/latest-flyout.html) which could be adapted.
Comment: @Smirkin Gherkin:  Thanks for pointing that out.  I've updated the `divs` to `spans` based on your comments.  Also, you could ignore the incompatibility of IE6 since it will be phased out soon and just use the hovers on whatever element you choose.


CCK Images broken (because of path) on multisite after copying/moving site

Question: I've just encountered an issue I haven't seen seen before: after copying the dB/files to a new location on the server, none of the CCK images are working, regardless of if ImageCache is used or not. In other words, even when editing a node, the image preview is missing because the path is obviously wrong.
For one example, the path should be /sites/dev-[site-name]/files/homebanners/[image-name].
Instead it is /sites/dev-[site-name]/files/sites/[original-site]/files/homebanners/[image-name].
What I can't figure out is why.
Here's the steps taken:

Copy the dB
Copy the files. I forget why but the new sites/[site-name] mapping changes to sites/dev-[site-name] for the dev site (where the images are broken).
Adjusted .htaccess RewriteBase & Rewrite Rules, and the base_url for each
settings.php file
Set the new files location at admin/settings/file-system
Cleared the cache For the imagecache files, and used Drush to flush and re-build the images

For all but one site, the files use the Public setting, but the problem persists regardless of if the files are set to public or private.
Any help would be most appreciated.
Answer: Changing site URL with a multi-site setup in Drupal 6 is problematic as the paths in the file table will be incorrect.  (See Migration failed)
In Drupal 7, you set up multi-site aliasing via the sites.php file (copy and edit the existing examples.sites.php),  which should be stored in the /sites directory.
For Drupal 6 you can try applying the multi-site aliasing patch.
As a last ditch effort (not best practice) you can also try editing the database (e.g. system and files tables) to change the file paths to reflect the new path.
Comment: Wow Rider_X you're awesome. It took me a bit to figure out exactly how to use the patch and sites.php, but I got it working. Never would have found the patch without your help. Thanks!


Why is my MonoDroid/Xamarin.Android project suddenly giving me a "'java' exited with code 1." error?

Question: While working on my MonoDroid/Xamarin.Android app, it suddenly stopped building, telling me
"java" exited with code 1.

After turning on normal MSBuild output verbosity, it showed that the error occurred in Xamarin.Android.Common.targets, located in C:\Program Files (x86)\MSBuild\Xamarin\Android. The line (line 988) starts this block of xml:
<CompileToDalvik
    JavaMaximumHeapSize="$(JavaMaximumHeapSize)"
    JavaOptions="$(JavaOptions)"
    AndroidSdkDirectory="$(_AndroidSdkDirectory)"
    ClassesOutputDirectory="$(IntermediateOutputPath)android\bin\classes"
    JavaSdkDirectory="$(_JavaSdkDirectory)"
    MonoPlatformJarPath="$(MonoPlatformJarPath)"
    JavaSourceFiles="@(AndroidJavaSource)"
    JavaLibraries="@(AndroidJavaLibrary)"
    LibraryProjectJars="$(IntermediateOutputPath)__library_projects__\*.jar"
UseDx="$(UseDx)"
/>

Also, when I have the above file open, I have 53 warnings, all similar to:
The element 'PropertyGroup' in namespace 'http://schemas.microsoft.com/developer/msbuild/2003' has invalid child element 'ResolveReferencesDependsOn' in namespace
'http://schemas.microsoft.com/developer/msbuild/2003'. List of possible elements expected: 'Property, AllowUnsafeBlocks, ... [followed by a long list of elements]

I deleted all the code that I had recently added, then ended up doing a full revert to previous code that worked, but the error continues no matter what I do. I found a resolved bug that may occur on the same line, but the solution given there didn't work for me. Also, because of the warnings and the fact that my code used to work it its current revision, it doesn't seem to be the same problem. Any ideas why this would happen, and how I might fix it?
More details: I tried running a new M4A project and it worked fine, so it looks like it isn't a problem with the M4A file, but something my code.
Even more details: I was going through each class, commenting them out to see if I could find a particular block that was causing the problem, when the error suddenly changed. It now displays an error identical to the one found in this question. I am also using the 30-day trial. However, I am using Visual Studio. I'll be seeing if the answer and comments there will help me too.
Comment: I am getting the exact same :/
Comment: Did any of you find a solution ? I'm facing the same situation... Thanks guys.
Comment: It went away for me for no apparent reason. I really wish I could help you guys out, but I have no idea what changed. I just banged my head against the wall for a few days and suddenly it was working again.
Comment: @ZAD-MAn Will do but wont be for a couple days as the whole process takes hours!
Comment: Getting same error too :(  Seems to have started happening after downloading and installing the new Xamarin.Android.  Not sure if it's a problem with the new release specifically, or that updating an existing version messed something up.
Comment: Just saw your last few lines about you are using the 30-day trial. That is very interesting, as this worked fine for me when using my paid account, but after doing the updates for Xamarin.Android and Xamarin.iOS and specifying to use the 30-day free trial for Xamarin.iOS (as I don't have a license for that yet) I started getting this error (but my Xamarin.Android project is the one throwing the error). So I wonder if it has something to do with using the trial version of Xamarin?
Comment: Just bought and activated the Xamarin.iOS license, but the problem continues, so if this problem is caused by using the 30-day free trial, buying a license doesn't fix it.
Comment: Very strange, I hadn't made any code changes at all, but I am not able to build the solution successfully in Visual Studio; however it still fails with the same error message when I build it from my build scripts (i.e. calling MSBuild.exe from the command line).
Comment: @deadlydog Dang, weird. Thanks for posting the updates though. I'm starting to wish I worked on the inside so I could figure out what's going on behind the scenes...
Comment: idem, after deleting all bin/obj folders, java still exits with code 1. And my Xamarin subscriptions are valids.
Comment: So while it was working earlier, it randomly decided to start giving me this error when building in Visual Studio again :( The good news is that I emailed Xamarin support and they are going to investigate the issue. I sent them a sample project that reproduces the issue for me (the DPSF Demo Source Code actually - http://www.xnaparticles.com/Download.php); not sure if it will barf for them too though, since it may be a machine-specific problem. I'll keep you updated.
Comment: You can follow the Xamarin Bug submission at https://bugzilla.xamarin.com/show_bug.cgi?id=14579. The help desk also mentioned 2 other submitted bugs that report the same error message, and may or may not be related. https://bugzilla.xamarin.com/show_bug.cgi?id=4288 and https://bugzilla.xamarin.com/show_bug.cgi?id=14363
Answer: I had the same problem and solved it by deleting my entire solution an pulling it from source control again. If you do not have a source to pull from, then i suggest deleting all generated files such as the contents of bin and debug folders.
Comment: I tried deleting all bin and obj folders, but still same thing. I haven't tried deleting and re-pulling from source control yet though.
Comment: Downloaded project from source control into a new directory and compiled, same error :(
Answer: Yes It's a good solution I have removed same problem from my project.
Step that you have need
1. Delete Bin and obj folder from project
2. Delete Solution File From Project Folder
3. Open New Visual Studio and then Click File > Open > Project/Solution >
   Select Folder Where placed you project.
   and after all, Rebuild Solution file and then rebuild your project.

I am sure u will success about this problem.....
Answer: I encountered this problem on a colleague's computer. The problem ended up being that his old sdk was installed under Program Files, while the update installed it under AppData. Changing this folder under Options > Xamarin > Android in Visual Studio solved the problem for him.
Comment: Out of curiosity, how long ago was that?
Comment: Last week. It happened after upgrading to xamarin 5.1.
Answer: I have solved by disabling the Proguard option and able to build it.
Right Click on Project -> Click Properties -> Android Options -> Uncheck Checkbox of Enable Proguard.


Whats is the opposite of addFieldError?

Question: I am following this tutrial to apply locale on my application it perfectly works and show the error messages, but the difference is that the tutorial is providing a login page but I am providing a registration page.
In tutorial after an authentication a new page will be opended but I need to show a message to thanks user for their registration.
I am not sure how to use the same method as addFielderror not to show error messages, but to show confirmation of registration messages.
I used the following in my validate method but it does not work,
   addActionMessage(getText("confirm"));

my jsp
<s:form action="validateUser" namespace="/user">

    <s:textfield key="global.username" name="username" />
    <s:password key="global.password" name="password"/>
    <s:submit key="global.submit" name="submit" />

</s:form>

<s:url id="localeEN" namespace="/" action="locale" >
   <s:param name="request_locale" >en</s:param>
</s:url>
<s:url id="localezhCN" namespace="/" action="locale" >
   <s:param name="request_locale" >zh_CN</s:param>
</s:url>
<s:url id="localeDE" namespace="/" action="locale" >
   <s:param name="request_locale" >de</s:param>
</s:url>
<s:url id="localeFR" namespace="/" action="locale" >
   <s:param name="request_locale" >fr</s:param>
</s:url>

<s:a href="%{localeEN}" >English</s:a>
<s:a href="%{localezhCN}" >Chinese</s:a>
<s:a href="%{localeDE}" >German</s:a>
<s:a href="%{localeFR}" >France</s:a>

Comment: you did not specified    any whgere
Comment: can u show the code in jsp for action errors and action messages
Comment: @PSR question is updated
Answer: try this
<s:if test="hasActionMessages()">

      <s:actionmessage/>

</s:if>

Whats is the opposite of addFieldError?


How can I route an IP Address to another IP Address

Question: We have a Windows Server 2012 virtual machine (Web01) hosted in Windows Azure.
This server has yet to be decommissioned so for now we're allowing access from this machine to our database server (DB01) on another network.
Our database server uses replication but unfortunately returns the "local" IP address of the replica server (192.168.100.2).
I need to configure Web01 so that requests to 192.168.100.2 are actually routed to the Azure Service IP Address XXX.XXX.XXX.XXX.
Comment: Your setup is confusing me, I don't get the relation between the Web01 access to the DB01 and the replication, how are access and replication related?
Comment: Another thing, the Web01 is on Azure, where is the DB01 server? local network or also on Azure? how are both servers connected?
Comment: What you actually want to do looks to me like a DNAT. It will be easy with Linux/Iptables, but I have no idea on Windows. On Linux I'll add a rule in the NAT table at the Postrouting chain to change the target IP address for the Desired IP address.
Answer: Pretty sure you're not going to be able to redirect an IP address in the way you've described, particularly since you don't have control of the Azure networking equipment.  I would look into changing the application configuration to use the Azure Service IP Address.  If it's an ASP web application, this would hopefully be as easy as changing the relevant connection string in the application's web.config file, as long as the developer didn't hard code the database connection or store it in some other file.
Comment: Per the other answer below, that would work only if the DB server you have in Azure also has an address of 192.168.100.2.  However, since you put xxx.xxx.xxx.xxx for the Azure address I interpreted that it is not.
Answer: A static route would solve this,
Syntax:
route add <destination> mask <subnetmask> <gateway> metric <costmetric> if <interface>

For example:
route add 10.0.0.0 mask 255.0.0.0 192.168.0.1 metric 2

Taken From
https://technet.microsoft.com/en-gb/library/cc757323%28v=ws.10%29.aspx


Have the top two teams in the NHL ever met in the Stanley Cup Finals?

Question: For example, the Stars and the Caps for this year.
Edit:
This is modern era, where we've had full 4-tier playoffs.
Comment: Did you want to write "two top teams" instead of "to two teams"?
Comment: You should also clarify in your question whether you mean Stanley Cup finals or Stanley Cup playoffs.
Comment: What about Montreal - Calgary in [1988-89 season](https://en.wikipedia.org/wiki/1988%E2%80%9389_NHL_season)? And Edmonton-Philadelphia in [1986-87 season](https://en.wikipedia.org/wiki/1986%E2%80%9387_NHL_season)? Wikipedia has list of [President Trophy winners](https://en.wikipedia.org/wiki/Presidents%27_Trophy#Winners) and their playoff results - you can check there which team they played in the playoffs.
Comment: Please define more specifically when "the modern era" starts; also do you mean the top two teams league-wide (which might be in the same conference, who could obviously never meet in the Finals) or the top team from each conference?
Comment: Edited for clarity.
Comment: I did.  "where we've had full 4-tier playoffs.  It seems less likely in the scenario where there are at least 16 teams.
Answer: Yes. The NHL spent 25 years with only six teams (the "Original Six" era), and to some extent only three of those teams were competitive, so this has happened many times.
Going even further back (to the 1920s), the playoffs were just a matchup between the top two teams, so this was guaranteed to happen.


How useful is the CLT in applications?

Question: My lecturer just covered the Lindeberg-Lévy central limit theorem and the multivariate version, the Lindeberg-Feller CLT. I understood the basic concept and I can derive it, etc. But it would help my understanding a lot if someone could explain how all this used in real life applications of econometric analysis?
I've read some claims that the CLT is nice only on a piece of paper.
Some really cool industry applications or references would be appreciated.
Answer: The CLT certainly informs applications all the time, since we deal with distributions of averages or sums very frequently (including in cases that may not be always obvious; for example, $s_n^2$ - the sample variance with denominator $n$ - is an average, and so the ordinary sample variance is just a slightly rescaled average).
The CLT can tell you to expect an approach to normality with increasing sample size for a particular statistic, but not when, exactly, you can treat it as normal.
So while you know that normality should kick in eventually, to know if you're close enough at a particular sample size, you will need to check (say algebraically, or more often via simulation).
You may sometimes run into 'rules of thumb' that say "oh, n=30 is enough for the central limit theorem to kick in". Such rules are nonsense without specifying the exact circumstances (what the distribution is we're dealing with, and what properties we care about, and 'how close is close enough').
If you have an $X$ with a distribution like this:

Then sample means, $\bar X$ for $n=1000$ have a shape like this:

... which for some purposes might be just about okay to treat as normal (proportion within 2 s.d.s of the mean, say); for other purposes (probability of being more than 3 s.d.s above the mean, say), perhaps not.
Sometimes n=2 is plenty, sometimes n=1000 isn't enough.

Another example: the sample third and fourth moments are averages and so the CLT should apply. The Jarque-Bera test relies on that (plus Slutsky, I guess, for the denominator, along with asymptotic independence), in order to obtain a chi-square distribution for the sum of squares of standardized values. But as Bowman and Shenton had pointed out (5 years before!), this shouldn't be expected to work well until large sample sizes. Indeed my own simulations suggest that for normal data, bivariate normality of the skewness and kurtosis doesn't kick in well until the sample sizes are surprisingly large (at small and middling sample sizes, the contours of the joint distribution look  more like a banana than a watermelon)

Increasingly often, however, sample sizes can be huge. I've helped with several real-data problems where the sample sizes were very large indeed (in the millions). In those situations, things the CLT suggests should approach the normal as $n$ approaches infinity are often extremely well approximated by normal distributions.
I wouldn't say the CLT is useless - it tells you what distribution to look for - but it doesn't do more than point to it as an eventual outcome; you still have to check whether it's a suitable approximation for your purposes at the sample size you have.
Comment: Nicely put.  As seen in other postings on this subject the CLT can be quite misleading and of questionable value in practice, not only because of the reasons above but because when the population variance has to be estimated and the distribution is skewed, the variance no longer applies in a certain sense, and bad things happen to the distribution of the $t$-statistic.
Comment: @FrankHarrell Bad things do happen, yes. With the skewed distribution I drew at the top of my answer above (Gamma with shape 0.02), the distribution of the two-sample t statistic in medium-sized samples (say n=30) looks like the main cable on a suspension bridge - bimodal with two sharp peaks.
Comment: @Glen_b just out of curiosity, could you tell what kind of analysis, variables or statistics you were working with? did the approximation prove reasonable? just to have an idea what fields could collect so much data and use CLT, since asymptotics always looked a bit academic for me.
Comment: For example, one was a set of engineering measurements of some industrial process -- I wasn't given much detail of the exact thing being measured in that case, but I think they were a (very) large set of diameters or lengths.
Answer: Notwithstanding the problems with CLT described by Glen_b, if we are talking about econometric analysis, then practicaly all results are asymptotic (except when Bayesian analysis is used).  Hence any application which is based on econometrics is based on CLT.  For example Lars Hansen got the Nobel prize last year for work on generalized method of moments, which is based on CLT.
It might seem that such reliance on CLT is not a good thing, but on the other hand any econometric paper relying on asymptotics usually has a chapter with Monte Carlo simulations exploring the reliability of asymptotic results on small samples, and more often than not the results are not that bad.
Comment: Thanks for the answer, and thanks for noticing that I bolded "Econometrics" in my question! It is indeed under an econometrics context that im learning the CLT.

How useful is the CLT in applications?


Calculating different pseudo-$R^2$ for a betareg model

Question: Sorry if this is a bit long..
I've been trying to fit models predicting the % of area infested in a field (response between 0 and 100%, total of 61 fields), with four explanatory variables, two factorials (planting and monitor) and two covariates (area2peri and Tmin7_bef).
I used the betareg() with link = "cauchit" (after comparing LL and AIC for the same predictors with different link functions), and tried the different combinations of parameters for both mean and dispersion sub-models. Would like some help understanding the possibilities of using different pseudo-$R^2$ for the different models. I am referring to the table on the UCLA website.
There are a few things that are not clear to me, and looking at betareg documentation did not solve them..

The summary(betareg(...)) provides a pseudo-$R^2$ square that is the "squared correlation of linear predictor and link-transformed response". How is that calculated? and to which type of the pseudo-$R^2$ it relates (Efron's,McFadden's, Cox&Snell etc.)?

I tried calculating the different types myself, as shown in the betareg documentation p.20, fitted a null (intercept only) and full models and extracted the LogLik for both. However there were several issues:

The formula suggested for Mcfadden's $R^2$ in betareg is the inverse of the one presented in the UCLA website, the null model's LL is the numerator in betareg and the denominator in UCLA.. what am I missing?

Here are the results for the different $R^2$, as well as the full model summary:
    Call:
    betareg(formula = A2to5 ~ planting + area2peri_m + monitor + Tmin7_bef | planting + monitor, data = na.omit(pre_n0),
        link = "cauchit")

    Standardized weighted residuals 2:
        Min      1Q  Median      3Q     Max
    -2.1745 -0.6122  0.1443  0.9129  1.6225

    Coefficients (mean model with cauchit link):
                  Estimate Std. Error z value Pr(>|z|)
    (Intercept)  -0.766418   0.714323  -1.073   0.2833
    plantinglate -1.013075   0.409167  -2.476   0.0133 *
    area2peri_m  -0.013529   0.006384  -2.119   0.0341 *
    monitor1      0.712917   0.277825   2.566   0.0103 *
    Tmin7_bef     0.111958   0.049065   2.282   0.0225 *

    Phi coefficients (precision model with log link):
                 Estimate Std. Error z value Pr(>|z|)
    (Intercept)    0.9635     0.2577   3.738 0.000185 ***
    plantinglate   0.4337     0.3331   1.302 0.192929
    monitor1      -0.2295     0.3145  -0.730 0.465674
    ---
    Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Type of estimator: ML (maximum likelihood)
Log-likelihood: 12.55 on 8 Df
Pseudo R-squared: 0.07703
Number of iterations: 31 (BFGS) + 1 (Fisher scoring)

Mfull <-as.vector(logLik(betareg_cauchit)) # 12.54867
Mintercept <- as.vector(logLik(betareg_cauchit_intonly)) #4.207168
n <- betareg_cauchit_intonly$n #61

## McFadden's pseudo-R-squared (explained portion of variance)- according to betreg documentation
1 -(Mintercept/Mfull) #0.6647

## McFadden's pseudo-R-squared - according to UCLA
1 -(Mfull/Mintercept) #-1.9827

## adjusted McFadden's pseudo-R-squared
1-(Mfull-8)/Mintercept #-0.08117

## Cox&Snell (improvment over null model)
1-((Mintercept/Mfull)^(2/n)) #0.0352

max_cox_senll <- 1-Mintercept^(2/n) #-0.0482

## Cragg & Uhler's (improvment over null model)
(1-((Mintercept/Mfull)^(2/n)))/max_cox_senll #-0.73

Which brings me to:

In all of my calculation attempts, hopefully not erroneous,  I did not achieve the summary's pseudo-$R^2$ (relating to the first question) but what is the meaning of a negative value? Is my fit that bad?

Finally, I get that there is no consensus of which type to use, or should one report the pseudo-$R^2$ at all, but how can I really judge if my models is able to explain something in the world?
Answer:
The pseudo-R-squared reported by betareg is the squared correlation of the linear predictor and the link-transformed response (default link: logit). For the mj_vd model from example("MockJurors", package = "betareg") that you cite, this can be replicated via:
summary(mj_vd) ## reports: Pseudo R-squared: 0.03885
cor(qlogis(MockJurors$confidence), predict(mj_vd, type = "link"))^2 ## [1] 0.03885128

This pseudo-R-squared is not explicitly mentioned in the UCLA website but it is of type 3 (square of correlation).

The McFadden pseudo-R-squared provided on the UCLA website is for discrete data where the likelihood contributions are actually probabilities between 0 and 1 (and thus the corresponding log-likelihood are negative). This is not the case for beta regression. In this case Smithson & Verkuilen (2006) also call this "proportional reduction of error (PRE)". This has the inverse ratio of the log-likelihoods. See also: calculating a pseudo R2 value when deviance is negative

The negative value for the McFadden pseudo-R-squared is due to the inverse ratio of log-likelihoods. This only works if both are negative (e.g., as in logistic regression) but here both log-likelihoods are positive.

I generally find the pseudo-R-squared to be of rather limited use in beta regression. Whether the model fit is useful (for you) depends on many aspects, e.g., whether you mostly want a model for the mean or you are really interested in a probabilistic fit. A comprehensive answer for this is beyond the scope of this question, though. Alternative means of model comparisons could include information criteria (AIC or BIC), scores for the mean predicitons like (root) mean-squared error (MSE, RMSE), or probabilistic scoring rules (CRPS, log-score), or graphical model assessments (quantile-quantile plots, PIT histograms, etc.).
Comment: Thank you @AchimZeileis for your quick reply! It took me some time to go over it thoroughly, and would like to ask for some clarifications: 1. Why is the inverse ratio being used on beta regression rather than discrete distributions?  Smithson & Verkuilen do not provide an explanation and the original paper by McFadden is beyond my abilities for now... 2. I would like to understand further your reply to question 4, could you please direct me to some more information on the subject? I understood it so that probabilistic fit is the method to model the mean.
Comment: I have included some further pointers in 2. and 4. Regarding a standard reference for the proportional reduction of error (PRE) I'm not sure whether there is a simple, more accessible reference.
Comment: Yes, I came across this question yesterday.. I will further explore those options you gave on point 4, thank you very much @AchimZeileis for all your helpful explanations! In general, not just here :)


Scope when calling nested Javascript functions

Question: When I use JS on a website, I often like to split up the code into logical, complete modules using function(), usually like so:
function BigClass() {
    this.doOneThing = function() {
    }
    this.doAnother = function() {
    }
}

Later I use jQuery's .ready() to create instances of the classes I'm using and hang those onto various events.
var bigClassInstance = new BigClass();
$('a.something').click(bigClassInstance.doOneThing);

My question is... what's the best way to do execute the doAnotherThing() function from  my call to doOneThing()? Working on smaller projects, I'll just use bigClassInstance.doAnotherThing();, but that's not portable.
What's the Right Way to go about doing this?
Answer: Not sure if I understand the problem, but by using the proxy function you can change the context for the function called by the click handler i.e. make this refer to your bigClassInstance and not the jQuery click context:
function BigClass() {
    this.doOneThing = function() {
       this.doAnother();
    }
    this.doAnother = function() {
    }
}

$('a.something').on( "click", $.proxy( bigClassInstance.doOneThing, bigClassInstance ) );


How can I create a struct type in the linux kernel (sys.c) that can be accessed by regular programs?

Question: I have implemented a few of my own syscalls in the sys.c file of the linux kernel. In my implementations I used two struct types that I created in the same file. I also would like to be able to use these structs outside of the kernel. Is there a way to use kernel-prototyped structs in regular programs, in the same way that the syscalls can be accessed by the regular programs?
Specifically, I need to create one of these structs in a user program, which is then passed as an argument to the syscalls. I think I need the struct to be in sys.c because it uses "struct task_struct", which is part of linux/sched.h.
If there is a way to do this, or if I am doing something completely wrong I would be happy to know either way. Thanks!
Answer: The usual C way of using the same declarations in multiple programs (here: kernel and user program) is putting the declarations in a header file and including that in the programs. If your structure declaration uses a declaration from linux/sched.h, you may want to #include <linux/sched.h> in the header file. (For getting struct task_struct, it may be necessary to #define __KERNEL__. What your user program does with a task_struct, only you can tell.)


c# Wp8: error in getting textbox entered value?

Question: It says createPassword and repeatPassword are not in the current context. Why and what happens ?
Code;
public MainPage()
    {
        InitializeComponent();
        TextBox createPassword = new TextBox();
        createPassword.Width = 400;
        TextBox repeatPassword = new TextBox();
        repeatPassword.Width = 400;
        Button createButton = new Button();
        createButton.Content = "Create New Password";
        createButton.Click += new RoutedEventHandler(savePassword);
        StackPanel content = new StackPanel();
        content.HorizontalAlignment = HorizontalAlignment.Center;
        content.Children.Add(createPassword);
        content.Children.Add(repeatPassword);
        content.Children.Add(createButton);
        LayoutRoot.Children.Add(content);
        }
        void savePassword(object sender, RoutedEventArgs e)
        {
            string password1 = createPassword.Text;
            string password2 = repeatPassword.Text;
        }

Answer: createPassword and repeatPassword must be class members to use them in different class methods:
TextBox createPassword;
TextBox repeatPassword;

public MainPage()
{
    InitializeComponent();
    createPassword = new TextBox();
    createPassword.Width = 400;
    repeatPassword = new TextBox();
    repeatPassword.Width = 400;
    Button createButton = new Button();
    createButton.Content = "Create New Password";
    createButton.Click += new RoutedEventHandler(savePassword);
    StackPanel content = new StackPanel();
    content.HorizontalAlignment = HorizontalAlignment.Center;
    content.Children.Add(createPassword);
    content.Children.Add(repeatPassword);
    content.Children.Add(createButton);
    LayoutRoot.Children.Add(content);
}
void savePassword(object sender, RoutedEventArgs e)
{
    string password1 = createPassword.Text;
    string password2 = repeatPassword.Text;
}


Windows Server 2012 R2 DataCenter The request to list features available on the specified server failed

Question: I am trying to add the Wireless LAN Service to my server but I first had to restart it because it installed some updates a while ago. After the restart it came up with the following error:

The request to list features available on the specified server failed.

Server Manager:

Powershell:

What should I do now? I am not very experienced in Windows Server only in C# and some other programming languages.
Comment: Did you uh...try restarting it again? Windows has a funny way of sneaking in additional updates after a reboot.
Comment: @NathanC I already restarted it 3 times now.... and there are no pending updates.
Comment: If there's a pending update, or feature install, you cannot install another feature until it restarts.
Comment: Disregard my last comment, it was for another question... I apologize...
Comment: Please check the server manager - there should be a flag that tells you why the server wasn't able to proceed.
Answer: I'm pretty sure it's a stuck pending reboot request.
Go to "C:\Windows\WinSxS" and check if there's a pending.xml file. Delete that file and try rebooting again. If you're unable to delete that file, try deleting it offline. If it's a virtual server, simply map its virtual disk somewhere and delete the file that way.
Answer: Is it trying to add prerequisite features and restart first? I had a similar problem adding the WSUS role which was clashing when it also added the Windows Internal Database.
This guy mentions the error, but my solution was different. Instead of changing group policy, I had to actually provide the WID account access to the WID directory:
<code>$WIDService = "MSSQL$MICROSOFT##WID"
$Acl = Get-Acl "D:\WID\Data"
$Acl.SetAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($WIDService,"FullControl","Allow")))
Set-Acl "D:\WID\Data" $Acl
</code>
This isn't exactly your problem, but the symptom seems the same so it may lead you in the right direction at least.
Answer: I believe that the feature in powershell is named "wireless-networking", so the command would be "add-windowsfeature wireless-networking -restart"
Answer: I have received similarly obtuse messages from Windows before, when trying to install a service that is not supported on Windows Server Core.
If you are running Core edition, then the Wireless LAN service is not supported on core.


Getting nested values in Immutable.js

Question: According to the docs here: https://facebook.github.io/immutable-js/docs/#/Map/getIn
I should be able to get the deeply nested value by providing an array for the keyPath argument. This is what I've done, however I'm getting undefined as the return value.
http://jsfiddle.net/srxv4mwu/
var obj = Immutable.Map({categories: {1: 'a', 2: 'b'}});
var output = obj.getIn(['categories', 1]);
alert(output);

What am I doing wrong?
Comment: Thank you for this question, why have the docs seemingly disappeared for `getIn` ? Has the method been deprecated?
Comment: Sorry, apparently it's inherited: https://facebook.github.io/immutable-js/docs/#/Iterable/getIn
Answer: A map is simply a collection of keys with values. What you have is a map with the key categories, and the value {1: 'a', 2: 'b'}. The value does not automatically become an Immutable map just because you place it inside another map.
Now, the getIn() function will only "see" other Immutable.js maps. What you have in there is a regular ol' javascript object. If you just want to get the 1 value, you can just do:

var obj = Immutable.Map({categories: {1: 'a', 2: 'b'}});
var output = obj.getIn(["categories"])[1];
alert(output);

If you want the categories collection to also be a map, you'll have to define that explicitly. Also, as Amit pointed out, you'll need to use strings with the getIn() function.

var obj = Immutable.Map({
 categories: Immutable.Map({
  1: 'a',
  2: 'b'
 })
});
var output = obj.getIn(['categories', '1']);
alert(output);

The above code will return 'a'.
It would probably be more convenient for you to do something like below, if you have many nested maps.

var obj = Immutable.fromJS({
 categories: {
  1: 'a',
  2: 'b'
 }
});
var output = obj.getIn(['categories', '1']);
alert(output);

The fromJs() function will convert any nested objects into maps or lists automatically for you.
Comment: Now the snippets work. The Immutable libraries weren't linked before.
Comment: "Now, the getIn() function will only "see" other Immutable.js maps. What you have in there is a regular ol' javascript object...."

I posted a question related to this at https://stackoverflow.com/questions/49025635/deep-access-in-plain-objects-with-immutable

The documentation quoted there seems to indicate that plain objects are also supported with getIn ?
Answer: There are 2 problems with your code:

Immutable.Map(...) doesn't traverse the parameter to create a complex immutable. For that you need Immutable.fromJS(...).
Once you do that, you need to use strings in getIn(...), so ['categories', '1'] instead of ['categories', 1].

See working fiddle.

Getting nested values in Immutable.js


How to use the default color picker in NSToolbar?

Question: I'm learning Cocoa. And this is my simple OS X app:

It contains a custom view, where the white rect is drown, a toolbar, and a slider. I want to change the rect's fill color by clicking on the 'Colors' item in the toolbar and choosing new color in the color palette.
How can I get the new color from the palette? I know it has the "NSToolbarShowColorsItem" identifier, but don't know how to use it.
Can you please help me? Thanks.
Answer: You should probably consider walking through a couple of basic Cocoa tutorials to learn about fundamental Cocoa concepts.
A number of resources to check out:

CocoaDevCentral
Cocoa Fundamentals Guide
Tutorials on CocoaDev
Comment: Thanks for your answer! Yeah, I know these sites. But are there any action methods for that color picker, something like - (IBAction)sliderMoved:(id)sender;


WORDPRESS 403 Forbidden. You don't have permission to access this resource

Question: i have a problem with my website. I can't access to wp admin. if i click wp admin, it will redirect to

Forbidden You don't have permission to access this resource,

i already tried resetting the permission, but still nothing happened.
i have open support on Github issue bitnami, but still no reply for 3 days.
Here is the report log after i run bndiagnostic tool :
<code>>  ? Apache: Found possible issues
    ? WordPress: Found possible issues
    ✓ resources: No issues found
    ✓ mysql: No issues found
    ✓ php: No issues found

> Found recent Pagespeed related error messages in the Apache error log:

>[Mon Jul 11 06:53:00.801224 2022] [pagespeed:error] [pid 8475:tid 140283220059904] [mod_pagespeed 184.108.40.206-0 @8475] /opt/bitnami/apache2/var/cache/mod_pagespeed/shm_metadata_cache/snapshot/pagespeed_default_shm/metadata_cache/1/64/4452/128/59,.tempGmnDMS:0: opening temp file: Permission denied

>We suggest disabling pagespeed and check if that improves the behavior. Please check the following guide to disable Pagespeed:

>https://docs.bitnami.com/general/apps/wordpress/administration/use-pagespeed/#disable-pagespeed

>Found recent WordPress plugin related error messages in the Apache error log.Please check the following guide to deactivate plugins:

>https://developer.wordpress.org/cli/commands/plugin/deactivate/
</code>
how to deactivate pagespeed step by step? i have zero knowledge about coding. i'm using SSH to login the control panel.
Answer: 403 forbidden could be caused by:

a Wordpress plugin: try disabling all wp plugins on your website by renaming plugins folder

damaged .htaccess: inspect the file or upload a brand new .htaccess file

wrong permission on folder (wp-admin in this case)

In all these cases I suggest using an FTP file manager like Filezilla
Comment: If the htaccess was damaged, you'd receive a 500 internal server error, not a 403
Comment: 1) how to repair the .htaccess to new one using SSH?
Comment: you can use Putty https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

Example of command to upload a file from your computer to your server:

c:\pscp c:\yourfolder\path\to\a\file.txt user@remote:\home\user\some\path
Comment: Since SCP is based on SSH, you may also find success with WinSCP, and it's much more intuitive than Putty.
Comment: how about the permisson folder? what command need to write?
Comment: chmod 755 wp-admin
Comment: this one? sudo find /opt/bitnami/apps/wordpress/htdocs -type d -exec chmod 775 {} \;
Comment: sudo find /opt/bitnami/wordpress/htdocs/wp-admin -type d -exec chmod 755 {} \;

or

sudo find /opt/bitnami/wordpress/wp-admin -type d -exec chmod 755 {} \;
Comment: still no luck.. i can't follow that command line because it appears only No such directory.. but on my site, it can be access with 'sudo find /opt/bitnami/apps/wordpress/htdocs
Comment: better using a visual interface for checking files.
Read this guide: https://docs.bitnami.com/general/apps/wordpress-production-ready/administration/upload-files/
Comment: already login to winscp and here my folder.. https://imgur.com/XYTugfL
Comment: right click on the folder > Properties
wp-admin should be 755
Comment: yes, same https://imgur.com/5NdNRBt but still can't access the wp-admin area :(
Comment: Check .htacces, or disable plugins
Comment: i have tried the two ways still no luck.. no problem with .htaccess even i change to new one.. also when deactivate the plugin, still can't access to the wp-admin panel
Comment: uhm... do you have an error log? Something like php_errorlog in you wp root folder
Comment: i have but i don't know how to share here because the file is 162mb
Comment: Just copy the most recent logs here
Comment: [[Sun Jul 10 00:00:04.335402 2022] [mpm_event:notice] [pid 1202:tid 140263230137664] AH00489: Apache/2.4.46 (Unix) OpenSSL/1.1.1i configured -- resuming normal operations
[Sun Jul 10 00:00:04.335415 2022] [core:notice] [pid 1202:tid 140263230137664] AH00094: Command line: '/opt/bitnami/apache2/bin/httpd.bin -f /opt/bitnami/apache2/conf/httpd.conf -D DISABLE_BANNER'
[Sun Jul 10 00:00:45.032736 2022] [proxy_fcgi:error] [pid 23317:tid 140261619398400] [client 220.127.116.11:53221] AH01071: Got error 'PHP message: Unable to open /


LinkedIn post inspector encountering server error on https URL

Question: Inspecting a given URL in the LinkedIn post inspector returns the following ingestion feedback:
Error   We encountered a server error while trying to inspect the URL.

The URL redirect trail shows:
1   0 undefined     https://example.com

I inspected URLs of both the production domain (https) and a staging sub-domain (http) on the same server (with identical html, needless to say). The LinkedIn scraper is able to fetch all metadata from the http sub-domain but not the https domain which leads me to believe the problem might be related to SSL authentication between the site and LinkedIn.
Has anyone else encountered this problem and can either confirm my suspicion or point me in a direction?
As a sidenote, both the facebook share debugger and the twitter card validator are able to fetch all metadata on all of the tested URLs via both protocols.
Ronald Werkhoven asked the same question here:
Validating link in post-inspector linkedin in gives server error
Checking the URL he provided in the LinkedIn post inspector does not throw any errors, so apparently he was able to fix the problem.
Would you, Ronald, mind sharing how you were able to resolve the issue?
Comment: Did you fix this? I have the same problem
Comment: Unfortunately not, because I don't have control over the server my client's website is running on. However, Ronald Werkhoven finally answered his own question in more detail in the original thread which gives a much better understanding of the problem and how to fix it.
Answer: one thing i know is that linkedin has crawler issues with the crawlers they use for og. i do not know if they use those crawlers with the post inspector aswell. but that could definitly cause such a issue if they did.
beneath i quoted the response of the linkedin team. so i do not know if there will be a fix anytime soon if these problems are related.

Thanks for reporting your issue. We've confirmed the problem you reported. After careful assessment, we've decided that we won't be
  moving forward with a fix at this time. LinkedIn continuously
  evaluates how features and products are used and we make adjustments
  accordingly to focus our resources on providing the most value to our
  members.
We greatly appreciate your feedback and have documented the issue to
  track additional reports of the problem and for consideration to be
  addressed in a future release. If there's anything else I can help you
  with, please don't hesitate to let me know.
Comment: While LinkedIn's response is rather disappointing at least they confirm that it's a problem on their side – so thanks for sharing!
Comment: no problem, good luck further hopefully you can still continue.
Comment: can you share please th  linkedin response url
Comment: well, looks like the problem still exist... I have no idea how to fix this.
In every other social it works, only on LinkedIn is troublesome
Answer: For anyone else dealing with similar - using NextJS through Cloudflare
Turned out it was because I restricted TLS>1.3, enabling 1.2 fixed it nice.
Answer: For the benefit of other people coming from Google, I was having this problem on my website as well, but for me the problem was HTML-minification related.
Linkedin doesn't parse the short doctype <!doctypehtml> so you'll probably get a 500 server error if this is in your page.
Answer: I know this is old, but still seems to be a problem. I use NextJS/Vercel and I was getting the same error. I then set up my site through CloudFlare's edge proxy service and it started loading OG card previews--and quite fast. I highly recommend going through CloudFlare, it's free for most small websites and you get a lot of tools at your disposal.
Answer: I fixed this by removing some HTML comments that were being added to my page's HTML by a plugin after the closing  tag.  WP Super Cache's "Cache Status Messages" option to be precise.
Looks like LinkedIn want well-formed HTML.
Answer: I also experienced the same problem and found out that LinkedIn wants to parse clean HTML with no comments after/before HTML tags so my WordPress blog has an HTML compression plugin that is adding some HTML commented text  after  that was causing the issue so I removed it and it's good to go. Check your page. So first try to validate your HTML and fix it on your end.