Does Torturous Grounds prevent Cull the Weak

Question: Cull the Weak increased damaged on slowed enemies, but Torturous Grounds causes the first two seconds of Caltrops to be an immobilize effect.
Does this override the slow for the first two seconds and thus not grant the extra damage?
Comment: Not sure if this is DH specific, if so can you add the class tag too - I am only guessing based on 'caltrops' mention
Comment: It is indeed, I've updated it.
Answer: Cull the Weak will work with Torturous Ground.
Tho i'm not sure why or how it works with other immobilize effects:

All immobilize effects could count as 100% slow.
It could be that Torturous Ground adds immobilize along with slow.
Or Blizzard just made those 2 skills compatible.

More discussions here and there


Unable to marshal type, XML output for spring controller

Question: I am working in an environment where all the common dependent jars are residing in tomcat/lib folder, and application specific jars in war file.
I have a simple controller and using spring-hateoas
@RestController
@ExposesResourceFor(AccountResource.class)
@RequestMapping("/accounts")
public class AccountController {

   @RequestMapping(method = { RequestMethod.GET })
   public ResponseEntity<Resources<AccountResource>> getAccounts() {
       List<Account> accounts = //get list of accounts;
       return new ResponseEntity<Resources<AccountResource>>(
            this.accountResourceAssembler.toEmbeddedList(accounts),
            HttpStatus.OK);
   }
}

@XmlRootElement(name = "account")
@Relation(value = "account", collectionRelation = "accounts")
public class AccountResource extends ResourceWithEmbeddeds {
  private Account account;

    //getters
}

As the spring hateoas jar is in tomcat/lib, the XML marshalling of Resources class does not work, throws error as mentioned at the end.
Is it possible to set the child classloader to the Jaxb converter in spring configuration so that this error can be avoided?
com.sun.istack.internal.SAXException2: unable to marshal type "package.AccountResource" as an element because it is not known to this context.
    com.sun.xml.internal.bind.v2.runtime.XMLSerializer.reportError(XMLSerializer.java:234)
    com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:323)
    com.sun.xml.internal.bind.v2.runtime.property.ArrayReferenceNodeProperty.serializeListBody(ArrayReferenceNodeProperty.java:103)
    com.sun.xml.internal.bind.v2.runtime.property.ArrayERProperty.serializeBody(ArrayERProperty.java:144)
    com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeBody(ClassBeanInfoImpl.java:345)
    com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsSoleContent(XMLSerializer.java:578)
    com.sun.xml.internal.bind.v2.runtime.ClassBeanInfoImpl.serializeRoot(ClassBeanInfoImpl.java:326)
    com.sun.xml.internal.bind.v2.runtime.XMLSerializer.childAsRoot(XMLSerializer.java:479)
    com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.write(MarshallerImpl.java:308)
    com.sun.xml.internal.bind.v2.runtime.MarshallerImpl.marshal(MarshallerImpl.java:236)
    org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter.writeToResult(Jaxb2RootElementHttpMessageConverter.java:187)
    org.springframework.http.converter.xml.AbstractXmlHttpMessageConverter.writeInternal(AbstractXmlHttpMessageConverter.java:66)
    org.springframework.http.converter.AbstractHttpMessageConverter.write(AbstractHttpMessageConverter.java:195)
    org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:239)
    org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor.handleReturnValue(HttpEntityMethodProcessor.java:183)
    org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81)
    org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:126)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
    org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
    org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
    org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
    org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
    org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:687)

I won't be able to move the jars, so need the fix on the spring side. BTW, JSON response works just fine, issue is only with the XML response for list.
Answer: I have reproduced the error with a small Spring boot example, so I'm pretty sure it is not a classpath issue.
The problem is that when the JAXBContext for the Hateoas Resources class is being constructed, there is no reference to your AccountResource class. This means that when Spring ask JAXB to serialize your ResponseEntity it breaks when it encounters AccountResource, because this class is not registered in the JAXBContext used for serialization.
If you make a method in you controller that returns ResponseEntity directly, you can see that this works fine.
The JAXBContext is immutable, and as far as I can see there is no way to affect the construction of JAXBContext because AbstractJaxb2HttpMessageConverter.getJaxbContext() is final.
I'm not an expert in JAXB, but from the documentation, it looks like Resource.getContent() is correctly annotated with @XmlAnyElement, but for some reason AccountResource is not serialized inside Resource.
If my analysis is correct this would be a problem for everyone using Hateoas with XML, so either no one is doing that, or I'm wrong. Do you really need it to produce XML ?
If I had to debug this any further I would start by checking out the Hateoas source, and see if they have any test that verifies that XML serialization actually works, if there is no test there is a chance it is completely broken.
Edit
If you can live without the namespaces* I believe I have found a solution.
If I replace the default Jaxb2RootElementHttpMessageConverter with MappingJackson2XmlHttpMessageConverter, and use @JacksonXmlRootElement, I can get the following output (*It may be possible to add the namespaces using MixIns, but I have not checked).
<Resources xmlns="">
<links></links>
<content>
    <content>
        <account>
            ....
        </account>
        <links></links>
    </content>
</content>

In order to modify the HttpMessageConverters after construction you need Spring 4.1.3 or newer, and make you configuration extend WebMvcConfigurationSupport, this allows you to do the following:
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    for (Iterator<HttpMessageConverter<?>> iterator = converters.iterator(); iterator.hasNext(); ) {
        HttpMessageConverter<?> converter = iterator.next();
        if (converter instanceof Jaxb2RootElementHttpMessageConverter) {
            iterator.remove();
        }
    }

    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().applicationContext(this.getApplicationContext()).build();
    converters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper));
}


Why was my question about sexual orientation reduction got automatically deleted by "community" if it wasn't closed?

Question: I have no idea why this question, which wasn't closed and had only one down vote, was deleted.

What is the main component of sexual orientation?
From vast reading on the formation of sexual orientation I understand
  that all researchers, from all "political camps" accept that sexual
  orientation can have at least one of these expressions:

Visual
Odiological
Tacital (body touch)
Pheromonal (body odor)
Lingual (body taste)

I can testify that as a person romato-erotically attracted to women,
  if I see Muslim girls covered in Hijab (let alone niqab), I usually
  feel no "sexual arousal" but if I see girls with very long straight
  black hair , I usually do feel somewhat "sexual arousal";
That brought me to assume that any of the five components of sexual
  orientation might have sub components and that, humbly, if to be
  somewhat technical, in regards to the visual component applicable to
  non blind people, face and hair are the most romanto-erotically
  arousing body organ, by sexual orientation.
What is the main component of sexual orientation (by what research
  tell us)?

Why was my question about sexual orientation reduction got automatically deleted by "community" if it wasn't closed?
Answer: Downvoted questions (more specifically, questions with a negative net voting score) that remain unanswered for a period of time are auto-deleted by the bot.
Quite a few of your questions have not been well received by the community. Have you taken the tour and did you visit the help-center, notably the page on which questions to avoid?
Comment: I suggest you to delete the comment-question in your `answer-including-post`; you shouldn't have a problem to delete it as you have deleted an entire correspondence in the comments of that post.
Comment: I am now emailing the community managers about this `mismanagement-according-to-my-opinion`.
Comment: Feel free to email SE corp. Disrespectful discourse is indeed deleted as it goes against the 'be kind' convention here on SE. As said, I am just trying to help. Therefore, I see no reason at all editing my answer. Cheers.
Comment: Humbly I already felt free because I had not reason to feel not to (again a redundant saying ATMO); I found all of your comments at least partly disrespectful and certainly not trying to help and I say this with 7 years experience in the community. Cheers.
Comment: @JohnDoea - my responses weren't meant that way. The comments are hidden in the background (not deleted, just not visible) so SE corp can easily review them if they want to. I don't have anything to hide, I just don't wish to have offensive material on our site. Anyway, this is not leading anywhere, so perhaps it is best that SE corp intervenes at this point. Thanks for reaching out to them.
Comment: I don't believe that also. I think you should have notify me (at least from web accessibility standpoint) that the comments weren't deleted but were only hidden; your comments were to me at least partially offensive; it might lead to make you a better moderator by commenting comments only at the comment section (a gold principle of mine) and by notifying comments are going to be hidden.


Why was my app rejected with "(REJECT) reserved policy group 'debug': not for production use"?

Question: I uploaded my app to the store but received this error message:
found unexpected Exec with architecture 'all': ./qtcdevicedebughelper.py
 (REJECT) reserved policy group 'debug': not for production use
What does it mean?
Answer: Rejected because you uploaded a debug build of your app. Debug builds are made to test your app on devices and emulators; to upload to the store, you need to create a release build. The Publish tab in Ubuntu SDK lets you create a release build click package; increase your version number and then create a release build click package from the Publish tab and then upload it to successfully publish to the store.
This is probably because you uploaded the run-on-the-emulator click package, rather than using the Publish tab in Ubuntu SDK to make a proper release build and uploading that.
Comment: This doesn't seem to apply with a cmake built app like docviewer. I have no debug/release options available.


Is there any method to obtain the Hidden Weapon Spell other than ranking in the Bell Keepers?

Question: I'm currently just missing that sorcery and about to start NG++, and I was wondering if there's any other way to obtain it in a fashion such as the Great Chaos Fireball.
Answer: No there is no other way to obtain Hidden Weapon. It's not too hard to get it as the covenant is pretty much like being part of a gank squad .
Answer: Pretty sure you can't do it other than through ranking...alternatively, you can just get them offline, that's what I did.
Comment: @Ozmah He probably means ranking the covenant offline by killing the sometimes spawning red phantom in Belfry Sol, if you don't want to play real PVP fights. The answer is phrased a bit vaguely, but I can confirm that ranking up is the only way to obtain the sorcery according to the official guide.
Comment: @Dominic De Coco, thank you for that, I've done some research regarding the phantom you mentioned and it seems that the strategy might work.


Difference between working with tkinter and tix (as tkinter?)

Question: What exactly is the difference between starting the program with
from tkinter import *

and
from tkinter import tix as tk

Because with the latter one I'm having problems, hence the question. I've changed all tkinter elements from plain 'Button' to 'tk.Button', but that doesn't seem to be the only difference that it makes.
Particularly I have a problem in the following code bit:
class OptionMenus(OptionMenu):
    def __init__(self, master, status, *fonts):
        self.var = StringVar(master)
        self.var.set(status)
        OptionMenu.__init__(self, master, self.var, *fonts,
                            command = update_config)
        self.config(width = "9", height = "1")

or
class OptionMenus(tk.OptionMenu):
    def __init__(self, master, status, *fonts):
        self.var = tk.StringVar(master)
        (self.var).set(status)
        (tk.OptionMenu).__init__(self, master, self.var, *fonts,
                                 command = update_config)
        self.config(width = "9", height = "1")

(and just in case how I call it)
fonts_menu = OptionMenus(buttons, strings[17], *fonts)

The latter one produces an error: "TypeError: init() takes from 2 to 3 positional arguments but 4 were given."
The first one works just fine.
Comment: It's probably worth pointing out that `tkinter.OptionMenu` and `tkinter.tix.OptionMenu` are completely different classes, even though they have the same name. For example, their initialization signatures are different: `(self, master, variable, value, *values, **kwargs)` and `(self, master, cnf={}, **kw)`, respectively.
Comment: Thank you very much, I'll look into that right away. Does the tix one has more functions and options or what? Why has it been doubled?
Answer: tix and tk are two separate modules. They have some widgets that have similar names, but they are not interchangeable libraries.
If you want to use tix, you should import it separately from tkinter, and you should not do global imports because it leads to ambiguity, which is likely why you're having problems.
Import them like this:
import tkinter as tk
from tkinter import tix

Then, use the widgets like this:
tk.Button(...)
tix.OptionMenu(...)

It then becomes crystal clear which widgets come from which libraries.
Comment: I tried importing both of them separately, but then my tkinter elements stopped working properly. How should I import them both, so that both are separately usable?
Comment: @wanaryytel: that all depends on what you mean by "stopped working properly". As for how to import them, you should _not_ do global imports. Import them as `import tkinter` (or `import tkinter as tk`) and `import tix`. Do not do `import tix as tk` because that would be extremely confusing.
Comment: Thanks, I'll keep that in mind. Now that I try using `import tkinter`, all the tkinter elements start giving me errors in the following manner: NameError: name 'OptionMenu' is not defined. When I give it a try with `import tkinter as tk`, then it appears to be working (at least no errors when I tested with the first couple of elements). Any ideas as to why doesn't `import tkinter` work as it's supposed to?
Comment: I don't have a module named tix, I can only import tix from tkinter.
Comment: @wanaryytel: `import tkinter` _does_ work as it's supposed to. I think you misunderstand how importing works. When you do `import tkinter`, it imports _one thing_ - a module named `tkinter`. You can then access all the widgets by prefixing them with the module name (`tkinter.Button`, `tkinter.Label`, etc). This is how all python packages work. When you do `from tkinter import *` you don't have to use the prefix. This method is not recommended; see https://www.python.org/dev/peps/pep-0008/#imports
Comment: I solved my problems using what Bryan suggested. To inform all the tix+tkinter rookies (like me) - tix widgets don't work with tkinter frame (main thingie, `tk`). However, tkinter widgets work just fine with a tix frame. ;)
Comment: @wanaryytel: Your comment doesn't make much sense.  Make sure you use the right terminology -- I think you are referring to modules, not frames. Frames are widgets, and tix widgets work perfectly well in tkinter frames.
Comment: Isn't `tix` deprecated? I mean, there aren't much references and documentation online.


Is this double tap for a subpanel a problem?

Question: I've been reading posts but am still a little confused on this as each situation is slightly different and I am not familiar with the terminology.
Main breaker has two larger wires coming into it.  The second one feeds a panel in the garage, which was an addition.  Panel has 3 circuit breakers in it.
Here is picture. My home inspector mentioned it as a problem. Do I need to deal with this?
Comment: What is your question?  All you've done is show a picture.
Comment: It's not enough. There are many potential questions, and the OP needs to pick one. Get well soon. Hope you found all the goo.
Comment: @isherwood while I'm all in favor of using this as a teaching moment to teach OP how to use SE, I say **we pick** because one of them is much more urgent than the others.   Regardless, he *did pick* - note words 3-4 of the title.
Comment: A sub-panel should be fed from a breaker and not tied into the main lugs, but you know that because the home inspector told you, right?
Comment: no, you do not need to deal with it. just call the home inspector and tell him/her that s/he is wrong .... what do you think?
Comment: Where's the main service disconnect in this all?
Answer: My bet is your panel is full and someone wanted to add the shed subpanel anyways so they simply fed it into the utility connection to the panel. There's several problems here

They're mixing aluminum and copper. This is dangerous because the wires can corrode like this. Corroded aluminum is a fire hazard
There's no way to cut the subpanel off. I'm sure someone can quote the relevant NEC, but there's a few reasons you connect wires in the panel to a circuit breaker, and one of them is you want to be able to cut the power to that wire
Even if the subpanel has a breaker, there's a risk that the wires double-tapped can exceed their design limits (which is the other major function of a breaker). If they do, the insulation can melt and now you have unrestricted current flowing straight from the utility, likely meaning fire.

If your panel is full, you'll want a subpanel by the main panel to hook this to. That likely means you'll need an electrician. It's a mess, but I wouldn't leave this as-is.
Comment: A sub would not require a breaker at the main panel if the wire size was the same as the main feeder, but cu /al under the same lug big no no even if listed for 2 wires. They make double lugs for this.
Answer: Other than everything @Machavity has said. It is illegal to tap more than one conductor to a lug unless that lug is designed to accept more than one conductor. Looking at your picture, I can tell you that that particular lug is not designed to accept more than one conductor.
Even if you replaced that lug, see everything else @Machavity has said.Meaning you still have many more problems that need to be corrected.
Answer: The wire to the subpanel is too small
This is the biggest gotcha here.
Presumably there is a main breaker upstream of this point e.g. Outside.  Breakers protect wires. It is sized to protect the fat aluminum wires coming to this panel.  The wires to the sub are much smaller and the main breaker cannot protect them.  This sort of daisy-chaining panels is legal but all the wires must be sized for the protecting breaker (or vice versa).
There is an even worse possiblility: that this is a split-bus "Rule of Six" panel, designed to h ave 6 main breakers in its top 12 spaces and those are the only breakers.    In that case, the wires to the subpanel would have no protection whatsoever.  Daisy-chaining like this should not be done on a Rule of Six panel.
Other problems
As you observe, the lugs are double-tapped. You can't do that.  There are double lugs made for that purpose which provide 2 voids and 2 setscrews. That lets you set torque correctly for each wire type independently.
All the wires are white.  You can't do that with wire 6 AWG or smaller. If the wire is larger than 6 AWG (doesn't look that way), you still have to mark the hots with black brown red orange yellow pink blue or violet tape or shrinkwrap.  That won't matter because you have to pull the wires and replace them with correct wires.
The good news
The main wiring method is metal conduit, hence the notable lack of ground wires.  The conduit is the ground.  That makes it a lot easier to replace wrong wires.  Generally main feeders like the one to the subpanel are aluminum, but depending on the size of the conduit, you may need to use copper wires to get wires small enough to be fill-table legal in the existing conduit.
To fix it
Start by making sure our assumptions about grounds are correct.
Next figure out where your main breaker is.  If it's outside the house, we can entertain the idea of continuing the double-lugging concept:

look at the conduit for the subpanel wires and compare that with the conduit fill table. Given that conduit, what's the largest size of wire that will fit 3 in that conduit?
Look up that size on the wire ampacity table, and working out of the 60C columns, search for a "happy match" amongst your main breaker size, ampacity of wires that will fit in that conduit, and cost.
If can find a happy match, then replace that cable, and replace the lugs with double lugs.  If you cannot, then daisy-chaining won't work.

If daisy-chaining can't work, then you need to move the subpanel wires to a 2-pole breaker actually in this panel, which means making space in this panel.

You do that by setting a new subpanel right next to this panel, and moving at least 4 spaces' worth of breakers over to the new near-subpanel.  (If it's a split-bus Rule of Six panel, you need to free up these spaces in the top Rule of Six area).   Then install the two 2-pole breakers, one for the near subpanel, one for the existing subpanel.  Get a nice big subpanel so you never have this problem again.

If you haven't replaced the 3 white wires yet, now it's time to do that - 2 must be replaced with colored wires. Black-black or black-red will do, as will any legal "hot" color.


301 .htaccess redirection apache server

Question: So I am having issue I want all requests from
https://transfinmedia.com/author?url=akchopra1-A268
to be 301 redirected on
https://transfinmedia.com/author/akchopra1-A268
but when i use
RewriteEngine on
RewriteCond %{QUERY_STRING} url=(.*)
RewriteRule ^author(.*) /author/%1 [L,R=301,NC]

requests to
https://transfinmedia.com/author?url=akchopra1-A268 gets redirected on
https://transfinmedia.com/author/akchopra1-A268?url=akchopra1-A268
what am i doing wrong here, completely out of clue.
Answer: By default ,mod-rewrite appends old QueryString to the new target url. To discard QueryString ,you need to put a ?  (an empty question mark) at the end of the target url.
RewriteEngine on
RewriteCond %{QUERY_STRING} url=(.*)
RewriteRule ^author(.*) /author/%1? [L,R=301,NC]

Make sure to clear your browser cache before using this.
Answer: change RewriteRule to
RewriteRule ^author\?url=(.*)$ /author/%1 [L,R=301,NC]

Demo

301 .htaccess redirection apache server


How to solve EAGLContext crash in iOS?

Question: I am working on live video call app using OpenTok(TokBox) using this demo : https://github.com/opentok/opentok-ios-sdk-samples/tree/develop/5.Multi-Party-Call
My problem is when I navigate from live call screen to main view(root view controller) then my app is crashed.
see following screen shot for crash log

Any help would be appreciated.
Answer: Make sure that OT objects (OTSession.OTPublisher and OTSubscriber) are properly released. Something outside of your view controller may still be holding onto this objects, and when the view controller moves out, OT objects may still be alive and active and trying to access released or non existent resources.
As a side note the proper way to release OT objects is as follows(assuming a two way call, can be generalized for multi-party):
<code>    [_publisher.view removeFromSuperview];
_publisher.delegate = nil;
_publisher = nil;

[_subscriber.view removeFromSuperview];
_subscriber.delegate = nil;
_subscriber = nil;

[_session disconnect:nil];
</code>
and on sessionDidDisconnect callback you can make
<code>_session = nil; // in your case you would not wait for this as iOS takes care of it.
</code>
Comment: i remove all object in view diddisapper but not working & my project is arc

How to solve EAGLContext crash in iOS?


Problem Involving an Extension Field Automorphism and a Polynomial with Solution $\alpha$

Question: Let $E$ be a field extension over $F$.  Let $\alpha \in E$ s.t. for $p(x) \in F[x]$, we have that $p(\alpha) = 0$.  Furthermore, suppose $\phi: E \rightarrow  E$  is a field automorphism s.t. $\phi(a) = a$ for all $a \in F$.
Goal: Show that $p(\phi(\alpha)) = 0$.
Attempt:

Let $p(x) = a_0 + a_1 x^1 + \ldots + a_n x^n$.
Then $p(\alpha) = a_0 + a_1 \alpha^1 + \ldots + a_n \alpha^n = 0$.
Then $\phi(p(\alpha)) = \phi(a_0 + a_1 \alpha^1 + \ldots + a_n \alpha^n) = a_0 + a_1 \phi(\alpha^1) + \ldots + a_n \phi(\alpha^n) = 0$.
Then $\phi(\alpha) = \frac{1}{\alpha_1} [-a_0 - a_2 \phi(\alpha^2) - \ldots - a_n \phi(\alpha^n)]$.

And at this point I'm not sure how I could use the equality in (4) to my advantage.
Comment: show $\phi(p(\alpha))=p(\phi(\alpha))$ (you almost did it in step 3)
Answer: Per user8268's comment, the completed proof is as follows:

Let $p(x) = a_0 + a_1 x^1 + \ldots + a_n x^n$.
Then $p(\alpha) = a_0 + a_1 \alpha^1 + \ldots + a_n \alpha^n = 0$ by hypothesis.
Then $\phi(0) = \phi(p(\alpha)) = \phi(a_0 + a_1 \alpha^1 + \ldots + a_n \alpha^n) = a_0 + a_1 \phi(\alpha^1) + \ldots + a_n \phi(\alpha^n) = 0$ via the fact that $\phi(a_0) = a_0$, $0 \in F \implies \phi(0) = 0$, and making use of the automorphism properties.
But then $\phi(p(\alpha)) = a_0 + a_1 \phi(\alpha) + a_2 \phi(\alpha)^2 + \ldots + a_n \phi(\alpha)^n = p(\phi(\alpha)) = 0$ via the fact that $\phi(\alpha^k) = \phi(\alpha)^k$ since $\phi$ is an automorphism and combining facts obtained in (3).
Then $p(\phi(\alpha)) = 0$ as desired.


Use of revocation certificate as id.rev


How to call a class from a cs file to update or save the session expired in database?

Question: I have a class function as following & I would like to use this class to be called into my master page. Then, doing login & logout time saved of the page into my database.
namespace LogInLogOut
{
    public partial class LogInLogOut : System.Web.UI.Page
   {
       public static void updateLogoutTime(string username, string pcname, string module)
        {
          String connectionString = ConfigurationManager.ConnectionStrings["VSConfigConnectionString"].ConnectionString;
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand("UPDATE [Access]  set LogOutDate =  '" + DateTime.Today.ToString("dd/MM/yyyy") + "', LogOutTime =  '" + DateTime.Now.ToString("HH:mm:ss") + "' WHERE LoginID ='" + username + "' AND ModuleID = '" + module + "' AND comptname ='" + pcname + "' AND LogOutDate= ' '", connection);
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            cmd.Connection.Dispose();
        }
     }
}

Here is the code in master page for doing popup message, but I have no idea to write the call function for calling the upper class into my master page. Hope anyone can assist me for this problem. Thank you.
protected void Page_Load(object sender, EventArgs e)
    {
        string csname = "timeoutWarning";
        Type cstype = this.GetType();
        if (!Page.ClientScript.IsStartupScriptRegistered(cstype, csname))
        {
            string strconfirm = "";
            Page.ClientScript.RegisterStartupScript(cstype, csname, strconfirm, false);
        }
}

Comment: Are you aware that you want to mix client-side and server-side code?
Comment: I think I didn't involved the server-side code. The upper is class function in a file named LogInLogOut.cs & downward is in another master page. Then, if I want to call & update my database just used LogInLogOut.LogInLogOut.updateLogoutTime(lblUserName.Text, lblComputerName.Text, "UR"). But now my problem is this updateupdateLogoutTime function doesn't save the correct logout time in my database, so how am I going to solve this problem?
Answer: You cannot call a server function like that in you javascript code.
To call a server function, you have to send a request to the server first. This is usually a Postback in asp.net.
If you do want to call a function like that, you have to mark it as a WebMethod. Asp.net will hide all the js that is needed to call the function.
This blog on WebMethods will get you started.
Your code should look like this:
 [System.Web.Services.WebMethod()]
 [System.Web.Script.Services.ScriptMethod()]
 public void LogoutTime(string username, string pcname, string module)
    {
      String connectionString = ConfigurationManager.ConnectionStrings["VSConfigConnectionString"].ConnectionString;
        SqlConnection connection = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand("UPDATE [Access]  set LogOutDate =  '" + DateTime.Today.ToString("dd/MM/yyyy") + "', LogOutTime =  '" + DateTime.Now.ToString("HH:mm:ss") + "' WHERE LoginID ='" + username + "' AND ModuleID = '" + module + "' AND comptname ='" + pcname + "' AND LogOutDate= ' '", connection);
        cmd.Connection.Open();
        cmd.ExecuteNonQuery();
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

You can now call this function in javascript using PageMethods
PageMethods.LogoutTime('lblUserName.Text', 'lblComputerName.Text', 'UR', update);

You should put that function in your master page if you want it on all pages, not in a separate page.
Comment: Hi, it didn't shows any error message but still cannot saving the logout time in my database. Any other suggestion?
Comment: There was an error in reply, function names were different. Corrected it. `PageMethods.LogoutTime` should be available in javascript. Type this in a console or alert box and check the function exists.


How to load markers from MySQL using PHP and ajax?

Question: I am new to Leaflet and I was wondering how to load markers from a MySQL database onto a leaflet map.
I don't want to only load the markers when the map is initialised but rather with a function because I would like the user to be able to, for example, select between dates and then load markers from those dates. I have done the following so far but I get an error:
leaflet.js:6 Uncaught TypeError: Cannot read property 'lat' of undefined.

I am not sure what I am doing wrong.
jQuery
$( document ).ready(function() {
    var markerpositions;
    var map = L.map('map').setView([-55.7770641,55.6602758], 13);
    L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        maxZoom: 19,
        attribution: '© OpenStreetMap'
    }).addTo(map);
    getlocations();
    var marker = L.marker(markerpositions).addTo(map);

function getlocations(){
var id = "1";

    $.ajax({
        type: "POST",
        url: "getlocationstomap.php",
        data: {id:id},
        dataType: 'json',
        cache: false,
    })
    .success(function(response) {
        if(!response.errors && response.result) {

            $.each(response.result, function( index, value) {
                markerpositions = '['+value[0]+','+value[1]+']';
           });

        } else {
            $.each(response.errors, function( index, value) {
                $('input[name*='+index+']').addClass('error').after('
'+value+'
')
            });
        }
    });
}
})

PHP (getlocationstomap.php)
<?php
// assign your post value
$inputvalues = $_POST;

// assign result vars
$errors = false;
$result = false;

$mysqli = new mysqli('localhost', "root", "", "traxi");

 /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }

    // escape your values
    foreach ($inputvalues as $key => $value) {
        if(isset($value) && !empty($value)) {
            $inputvalues[$key] = $mysqli->real_escape_string( $value );
        } else {
            $errors[$key] = 'The field '.$key.' is empty';
        }
    }

if( !$errors ) {
        // select your query
        $addresult = "
            SELECT `latitude`, `longitude`
            FROM `positions`
            WHERE `deviceid` = '" . $inputvalues['id'] . "'

         ";
//$returnResult = array();
         if( $result = $mysqli->query($addresult) ) {
            // collect results
            while($row = $result->fetch_all())
            {
                // assign to new array
                // make returnResult an array for multiple results
                $returnResult = $row;
            }
        }
    }

    // close connection
    mysqli_close($mysqli);

    // print result for ajax request
    echo json_encode(['result' => $returnResult, 'errors' => $errors]);

    exit;
?>

Answer: When you parse the ajax response, you are overwriting the variable markerpositions again and again, so only the last parsed variable will ever be added to the map.
Also the  L.marker() method needs an array as input, but your lat long data is assigned as a string in the variable markerpositions instead of an array.
Add your response data to the map like this:
$.each(response.result, function( index, value) {
    L.marker([ value[0], value[1] ]).addTo(map);
});

Answer: I know this is answered and accepted but i thought i'de throw in another way (a way in which you'de never encounter the problem you ran into). When you have control over PHP and the output you're sending, i find it best to generate the data in GeoJSON format:

GeoJSON is a format for encoding a variety of geographic data structures.

http://geojson.org/
It's easy to do and saves you a lot of hassle when using the data on the clientside and it's easily testable by using GeoJSON lint, something you can't easily do with a custom generated JSON structure. Also, GeoJSON can be used by virtually any GIS application out there, so your data is interchangable across a multitude of application.
You'll need to turn your MySQL rows into GeoJSON features, put them all in a GeoJSON collection, encode them to JSON and send them to the client. There you can load them at once into Leaflet's L.GeoJSON layer. An example in code:
Functions to generate a new/empty GeoJSON features and collections:
<?php

function createFeature () {
    $feature = new stdClass();
    $feature->type = 'Feature';
    $feature->properties = new stdClass();
    $feature->geometry = new stdClass();
    $feature->geometry->type = 'Point';
    $feature->geometry->coordinates = array();
    return $feature;
}

function createCollection () {
    $collection = new stdClass();
    $collection->type = 'FeatureCollection';
    $collection->features = array();
    return $collection;
}

Now when grabbing your rows from MySQL insert the data from each row into seperate features and push those features to a collection and send it to the client:
<?php

$query = "SELECT name, latitude, longitude FROM locations";

if ($result = $mysqli->query($query)) {

    // Create a new collection
    $collection = createCollection();

    while ($row = $result->fetch_object()) {

        // Create a new feature
        $feature = createFeature();

        // Add (optional) properties to the feature
        $feature->properties->name = $row->name;

        // Add coordinates to geometry coordinates array
        // Mind that GeoJSON works with lng/lat NOT lat/lng
        $feature->geometry->coordinates[] = $row->longitude;
        $feature->geometry->coordinates[] = $row->latitude;

        // Add the feature to the collection's features array
        $collection->features[] = $feature;
    }

    // Encode collection object to JSON and send to client
    echo json_encode($collection);

    $result->close();
}

You'll end up with an output similar to this:
{
    "type": "FeatureCollection",
    "features": [{
        "type": "Feature",
        "properties": {
            "name": "Foo"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [1, 1]
        }
    }, {
        "type": "Feature",
        "properties": {
            "name": "Bar"
        },
        "geometry": {
            "type": "Point",
            "coordinates": [2, 2]
        }
    }]
}

Now loading that into Leaflet is a breeze, L.GeoJSON will automaticly create L.Marker's from GeoJSON point features:
// Grab the data via jQuery's getJSON
$.getJSON('url', function (collection) {

    // Create new GeoJSON layer with collection and add to map
    new L.GeoJSON(collection).addTo(map);
})

Using properties is very easy using L.GeoJSON's onEachFeature method:
new L.GeoJSON(collection, {
    'onEachFeature': function (feature, layer) {
        layer.bindPopup(feature.properties.name);
    }
}).addTo(map);

That's it hope it might enlighten, here's some reference:

L.GeoJSON reference: http://leafletjs.com/reference.html#geojson
L.GeoJSON tutorial: http://leafletjs.com/examples/geojson.html
Comment: wow that seems like an ideal approach for me! thank you so much ! I shall definitely read up on it.


IE6 + IE7 on a clean XP install

Question: We need to test a website in both IE6 and IE7. We've had bugs appear running on actual windows machines that aren't visible under vmware (?!), so we have an actual windows laptop to do this - but only one. Is it possible to install IE6 and IE7 side-by-side in such a way that they absolutely, positively, behave exactly like they would if there was only one of them? How?
Answer: The officially sanctioned way is to use the microsoft-provided Virtual PC installation and VPC images. You don't need additional windows licenses to run these.
http://blogs.msdn.com/ie/archive/2006/11/30/ie6-and-ie7-running-on-a-single-machine.aspx
http://www.microsoft.com/downloads/details.aspx?FamilyId=6D58729D-DFA8-40BF-AFAF-20BCB7F01CD1&displaylang=en
http://www.microsoft.com/downloads/details.aspx?FamilyId=21EABB90-958F-4B64-B5F1-73D0A413C8EF&displaylang=en
Answer: Take a look at http://tredosoft.com/Multiple_IE. Bear in mind that running both side by side is not supported by Microsoft (http://blogs.msdn.com/cwilso/archive/2006/02/01/522281.aspx) and there's no guarantee that they will work absolutely fine side by side - a Windows Update could easily break something and sometimes people find conditional comments don't work properly amongst other things. All I can suggest is you give it a go and see how you get on.
Comment: I've found some edge cases in CSS don't work the same in multiple IE or IETester as they do in IE6 unfortunately
Answer: The only really reliable way I've found is to use Virtual PC and have an image with IE6 on it, Multiple IE or IETester don't always work exactly the same as the original versions
Answer: If you can publish your pages on the web, you can try http://browsershots.org/
I always use it when I have to test a new layout with almost any browser on the planet.
Answer: Virtual PC 2007 is the latest version of VPC.  You should use the newer version if you're running Windows Vista.  VPC 2004 isn't supported for Vista.
Download page for Virtual PC 2007 SP1
Microsoft Virtual VPC Homepage where you can find the latest version of VPC

IE6 + IE7 on a clean XP install


how to obtain URLs from Dmoz ODP

Question: I want to use a database of URLs present in DMOZ ODP for my application. ( an array of URL strings OR a file containing the same ). Is there any way of obtaining it , ( other than the manual copy-paste ) ?
EDIT :
Is there any script / code to parse the rdf file..
Answer: Take a look at http://rdf.dmoz.org/, you'll need to find a way to parse the RDF into your database.
I did this the other day using the odp2db scripts from Steve's Software. They're old, but the format hasn't changed significantly so they work fine.
I found I didn't need to do the iconv and xmlclean.pl steps suggested in the readme, just uncompressed the dumps and ran the structure2db.pl and content2db.pl scripts. You'll need to create the database tables manually (see the SQL at top of script for that) and modify the connection details in the scripts before you start.
With the mid-January 2009 dump I used, there's 756,962 categories and 4,436,796 websites. It took a while to run through them all, but not excessively long, though I did dispense with the site descriptions as I didn't need them. Also, may be worth adding database indices after creating the tables to speed access up later. The raw structure and content files were 75MB and 300MB compressed respectively. 848MB and 2GB respectively.
Comment: Ya actually i downloaded it and tried to extract data with extreme DMOZ extractor but could get only 1000 urls as it was an evaluation version . Is there any other extractor (freeware) for extracting complete DMOZ directory ???
Comment: Or is there any script to parse it.. I'm not that familiar with rdf files.. please help.. i need it badly..
Comment: I did this the other day, have modified my answer accordingly. Hope it helps!
Comment: I have a few doubts - 1.what will the size of content < list of urls > be .. How much disk space will it require ?    2.i have mysql.. what'll the modified perl script be for mysql instead os PostgreSQL ?
Comment: I have added some stats on the raw file sizes to my answer above. I can't tell you how big the database will be as I dispensed with the descriptions (although now I find I might need them so will have to do it again). The database could well be smaller than the RDF files as there's a lot of XML and RDF cruft.

I can't see any problem with using MySQL instead of PostgreSQL. Just modify the DBI->connect statement, which you'd have had to anyway with login details.
Answer: I've actually done this in java.  I just used the SAX API to read through the RDF files.  It was pretty straight forward.  In my case I wanted to pull out every URL that was in a topic with "Weblogs" in the topic name.
Basically what did was implement a org.xml.sax.helpers.DefaultHandler
Then to setup the code you do:
       InputSource is = new InputSource(new FileInputStream("filename.rdf"));
       XMLReader r = XMLReaderFactory.createXMLReader();
       r.setContentHandler(new MyHandlerClass());
       r.parse(is);

and that's pretty much it. In my handler class I had to implement:

startElement(String uri, String localName, String qName, Attributes attributes) then I had an if statement to see if it was an "ExternalPage" tag, in which case I went to another state to look for "topic","Title" and "Description".  I had another
characters(char[] ch, int start, int length) where I read in the topic, title, and description text depending on which one had been most recently sent to startElement
endElement(String uri, String localName, String qName) where I checked to see which element was ending, and if it ExternalPage, that meant the end of the current element.

The whole thing was 80-90 lines of code for the basic parsing. So pretty easy to write. It was able to chew through the multi-gigabyte files in... I don't remember maybe a minute or two? If you just want to query out some specific data, it might be easier just to write the code to do that in your handler, rather then trying to load it into a DB.
If you find a tool that works well, that's obviously better then writing your own code.  But writing your own code isn't hard!  RDF is just an XML format, and it's not nested or anything.  A simple SAX parser is easily doable in a day or so.
Comment: Hey Chad,

I am doing exactly the same thing. While parsing small files, it works fine but when I try to parse complete file, I get this exception -

org.xml.sax.SAXParseException: Character reference "" is an invalid XML character.
 at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(Unknown Source)
 at test.com.amazon.lm.dao.entity.SaxDMOZParser.main(SaxDMOZParser.java:35)

This special character is present in later part of the file. What do I need to do?
Comment: @tyro I don't know, I didn't have that problem, maybe they added something to the data since then and aren't checking to make sure it's valid. Maybe you could manually process the file and remove that character reference.

Something like this Unix command might be able to do it:

`sed -e "s/\&\#11//ig" broken.xml > fixed.xml`

I'm not sure about the escaping, but that should help
Comment: ... I did that and problem got resolved.
btw thanks for your concern.
Answer: You could always pay one of the currupt editors there and they will help you out :)

how to obtain URLs from Dmoz ODP


Cube/Circle/etc without one point on the boundary convex?

Question: Reading this paper here, about convex optimization (photo page 2-3).

What about if the object misses the corner point? I think it is still convex but I am not sure whether my intuition fails me here. Is it convex or not? Is a ball without the boundary convex? I doubt it because if I select a point, I can always go nearer-and-nearer (never really reaching the point without extended Number system ofc). I am not sure about the general case with limit points like if I have non-dense space like missing points $\mathbb R^{N} \text{ (exclude sign here please) } \mathbb Q^{N}$ from the space $\mathbb C^{N}$.
Answer: The boundary of a convex set has special points, called extreme points, which generalize corners. You can remove any of those and the remaining set will be convex. If you remove an ordinary boundary point that is not an extreme point then you may end up with a set that is not convex.
All points in the boundary of a ball are extreme and so you can remove any or all of them. In the wikipedia illustration, the extreme points appear in red; you can remove any or all of them. But if you leave the endpoints of the red segments then you cannot remove any of the ordinary boundary points without breaking convexity.
A related result is the Krein–Milman theorem, which says that a compact convex set is the closure of the convex hull of its extreme points. Informally, you can recover the shape of a compact convex set from its extreme points.
Answer: I'm not sure I understand all of what you're saying, but from what I understand it seems that you've misunderstood the definition of convexity. In the slides you link to, convexity is introduced by the condition
$$f_i(\alpha x + \beta y) \le \alpha f_i(x) + \beta f_i(y)$$
for $\alpha+\beta=1$, $\alpha\ge0$, $\beta\ge0$ on the constraint functions $f_i$ in the constraints
$$f_i(x)\le b_i\;.$$
That is, if the constraints are fulfilled for $x$ and $y$, they are also fulfilled for all convex combinations of $x$ and $y$, that is, for all points on the line segment joining $x$ and $y$. Thus, the constraints define a convex set, which is a set containing all convex combinations of its points.
Thus, you don't have to think about whether you can approach or reach the boundary to decide whether a set is convex. A cube without its corners and a ball without its boundary are both convex, since these boundary points don't lie on line segments joining any other points. By contrast, if you were to remove the midpoints of the sides of a cube, it would no longer be convex, since those midpoints do lie on line segments joining other points, e.g. on the face diagonals – this is similar to the third example in the image.


Django: dealing with non-ascii parameters

Question: I'm running into an issue dealing with non-ascii POST parameters. Here's a CURL request that shows the problem:
curl "http://localhost:8000/api/txt/" -d \
"sender=joe&comments=Bus%20%A3963.33%20London%20to%20Sydney"

The pound sign in comments is causing the issue: when I try to do just about anything with request.POST['comments'] I get:
UnicodeEncodeError: 'ascii' codec can't encode character u'\ufffd' in position 4: ordinal not in range(128)

For example, if I just try to log what comments is:
message = request.POST.get('comments', None)
file('/tmp/comments.txt', 'wb').write(message)

I get the above error. Or when I try to decode it, I get the same error:
try:
    message = message.decode('ISO-8859-2','ignore').encode('utf-8','ignore')
except Exception, e:
    file('/tmp/ERROR-decode.txt','w').write(str(e))

produces ERROR-decode.txt with:
'ascii' codec can't encode character u'\ufffd' in position 4: ordinal not in range(128)

Ideas?
Answer: %A3 is wrong. It should in fact be %C2%A3 or %C5%81 in order to be correct UTF-8.
Also, "Unicode In Python, Completely Demystified".
Comment: Well that's closer. Now just read that article to understand why.
Comment: @Parand: No you haven't. How do I know? You still insist on decoding a `unicode`.
Comment: The request is coming to me from an external service, so I don't have  control over its contents. I did try testing with %C2%A3, and it just changes the error: 'ascii' codec can't encode character u'\xa3' .
Comment: Thanks Igancio. I've read that presentation many times now, and tried the .decode().encode() sequence as seen above. It gives the error mentioned above. Is there something beside .decode().encode I should try?
Answer: I think you have to pass it first into urllib.unquote() to remove the quoting performed by HTTP, then, you can convert the string to unicode with the proper encoding
>>> unicode(urllib.unquote("Bus%20%A3963.33%20London%20to%20Sydney"), \
            "iso-8859-2").encode("utf-8")
'Bus \xc5\x81963.33 London to Sydney'

Comment: Sorry Stefano, I didn't make it clear it was in the context of Django; django already unquotes the POST parameters for you, so 'comments' is an unquoted string already.
Comment: @Parand: ah ok. fair enough. then what you receive is a string which must be converted to unicode via the proper encoding. I use `unicode(str, "encoding")` which is clear in intent. Then you can `.encode()` this unicode object to utf-8 if you please.
Comment: No, what is received is a string that has already incorrectly been converted to a `unicode`, hence the presence of U+FFFD.


Proof of Fourier Transform

Question: Where F is the fourier transform,
how can you show that $$\mathcal F(x\cdot f(x)) = −i \frac{d\mathcal F}{dw}.$$
I understand that you are meant to apply the inverse transform to the left hand side, but I just can not seem to get it to work.
Many thanks, Rachel.
Answer: Actually, for a simple case (when f(x) is a continues function and xf(x) is absolutly integrable on the real line), you can just insert the differentiation inside the integral, that is
$$ \frac{d}{dy} \int_{-\infty}^{\infty} f(x)e^{-ixy}dx = \int_{-\infty}^{\infty} \frac{d}{dy} (f(x)e^{-ixy})dx =  \int_{-\infty}^{\infty}  -ixf(x)e^{-ixy} dx = -i \int_{-\infty}^{\infty}  xf(x)e^{-ixy} dx $$
since it can be shown that both $$ f(x)e^{-ixy} $$ and $$ -ixf(x)e^{-ixy} $$ are continues, and the integral $$ \int_{-\infty}^{\infty}  -ixf(x)e^{-ixy} dx $$ converges uniformly (for every y) .
for functions that are not continues, other techniques are required, like Lebesgue's dominated convergence theorem.
Answer: i think this is what you're asking...
integrating by parts we have (assuming $f\to 0$ at $\pm\infty$)
$$\mathcal{F}(-if'(x))(y)=\int -if'(x)e^{-ixy}dx=\int f(x)ye^{-ixy}dx=y\mathcal{F}(f(x))(y)$$
so that the fourier transform of $f'$ is $iy$ times the fourier transform of $f$

Proof of Fourier Transform


call myFunction daily, at specific time, in shiny?

Question: im looking for a way to call a function daily at %H:%M in server.R of a deployed shiny app.
using an infinite loop to "watch the clock" is probably a sin and doesnt work. any ideas?
ui.R
library(shiny)
shinyUI(fluidPage("floou", textOutput("foo")))

server.R
library(shiny)
myFunction <- function() {...}
repeat {  # same behavior with while (T)
  # Sys.sleep(60)  # also tried sleeping
  if (format(as.POSIXlt(Sys.time(), tz = "GMT"), "%H:%M") == "21:00") {
    myFunction()  # func not called + rendering blocked -> approach not working
  }
}
shinyServer(function(input, output) {
  output$foo <- renderText("not rendering with infinite loop")
})

Comment: I highly suggest not doing this with shiny. A Shiny session is not meant to be open 24/7. What you want to do should be done with a cronjob (the cronjob can call an R script)
Comment: If the problem is that your computer isn't always on, then you can buy a server from amazon EC2 or digitalocean ($5/month) and that server will always be on
Comment: You mean like [this](http://stackoverflow.com/questions/24880355/schedule-task-on-a-shiny-application)?
Comment: @daattali thanks for the hint. have scheduled a script via windows task scheduler on my local pc..works fine, but that process isnt fully autark though as it requires my pc to be running and online..how should i set things up for such a repetitive task to run autonomously?
Comment: thanks @daattali goin 2 get me a server then
Answer: It may be done in this way.
But you have to hold an open session.
server.R
timeStop <- "22:45:20"
trick <- reactiveValues()
trick$catch <- FALSE

  observe({
    invalidateLater(200, session)
    if (strftime(Sys.time(),  format="%H:%M:%S") > timeStop) {
      trick$toFire <- "after"
    } else if (strftime(Sys.time(),  format="%H:%M:%S") < timeStop){
      trick$toFire <- "before"
    } else if(strftime(Sys.time(),  format="%H:%M:%S") == timeStop & trick$catch == FALSE){
      trick$toFire <- "exact"
}
  })

  observe({
    invalidateLater(200, session)
    if (trick$toFire == "exact") {
           trick$toFire <- "after"
            trick$catch <- TRUE
            Sys.sleep(1)
          #your code or functions
            trick$catch <- FALSE
        }
  })


`xdg-open .` opens file manager, but opens Audacious with sudo permissions

Question: xdg-open . opens file manager, but opens Audacious with root permissions. It then proceeds to play all system sounds! I'm just trying to open the file manager with sudo. Is there a better way to do it?
(On Lubuntu so I don't have nautilus or gnome)
Answer: xdg-open is not always configured to open the correct application by default.  You can start Lubuntu's file manager directly by running pcmanfm.
Comment: And since Lubuntu 18.10 (with the switch to LXQt), it's `pcmanfm-qt`.


Python Encoding String Issue: String "Île-de-France" is being written to CSV file as "√éle-de-France"

Question: I'm trying to write a string "Île-de-France" to a CSV file, however, what is being written to file is "√éle-de-France".  I tried encoding="utf-8" in the open and it didn't work.  What am I missing?   Thanks!
with open('/tmp/directwrite.csv', 'w', newline='') as csvfile:
    fieldnames = ['location']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({'location': 'Île-de-France'})

Answer: It's an issue with your viewer. If using Excel or some other windows program, useencoding='utf-8-sig'. That writes a signature at the beginning of the file that Windows programs recognize as a UTF-8 file; otherwise, it assumes an ANSI encoding for the file.


Why are my ggplot2 aesthetics the wrong length?

Question: I am trying to average reps of data, subset one treatment, then make a bar graph of the response and another factor. My plot ends up not working. Any help would be much appreciated.
My data:
data <- structure(list(Sample = c(1011L, 1012L, 1014L, 1024L, 1025L,
1026L), Collection = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
"2"), class = "factor"), Irrigation = structure(c(3L, 3L, 3L,
5L, 5L, 5L), .Label = c("Rate1", "Rate2", "Rate3", "Rate4", "Rate5"
), class = "factor"), Variety = structure(c(2L, 1L, 3L, 3L, 2L,
1L), .Label = c("Hodag", "Lamoka", "Snowden"), class = "factor"),
Suc = c(0.7333, 0.4717, 0.5883, 0.6783, 0.8283, 0.6833),
Gluc = c(0.03, 0.04, 0.043, 0.075, 0.057, 0.087), L = c(59.48,
57.59, 59.25, 66.45, 68.29, 65.65), a = c(4.36, 6.85, 3.43,
1.7, 0.78, 2.84), b = c(26.82, 27.6, 26.2, 26.14, 25.37,
27.19), NoDefect = c(100L, 100L, 100L, 92L, 100L, 100L),
Defect = c(0L, 0L, 0L, 8L, 0L, 0L)), row.names = c(NA, 6L
), class = "data.frame")

Averaging between reps:
dataAvgSuc <- data %>%
  dplyr::group_by(Collection, Irrigation, Variety) %>%
  dplyr::summarise(meanSuc=mean(Suc))

Made 'Collection' a factor:
dataAvgSuc$Collection <- as.factor(dataAvgSuc$Collection)

Subset by variety:
subLamoka <- subset(dataAvgSuc, Variety=="Lamoka")
subHodag <- subset(dataAvgSuc, Variety=="Hodag")
subSnowden <- subset(dataAvgSuc, Variety=="Snowden")

Attempted ggplot:
sucPlot <-ggplot(data=subLamoka, aes(x=dataAvgSuc$Collection,
y=meanSuc)) + geom_bar(stat="identity")

Error code:
Error: Aesthetics must be either length 1 or the same as the data (10):
x, y

However, both the x and y have 30 entries when I look at them.
Comment: subLamoka, the source of your y, has 2 observations, while the x from dataAvgSuc$Collection has 6. Did you mean Collection instead of dataAvgSuc$Collection, thus using the version from subLamoka? Or perhaps you want `ggplot(data=dataAvgSuc, aes(x=Variety, fill = Collection, y=meanSuc)) + geom_bar(stat="identity")`
Comment: Don't use `$` in the `tidyverse`.
Comment: @JonSpring Thanks for the reply! The plot that you shared is a little off from what I'd like. I want to eventually have a ggplot with Suc on the Y axis and the collection on the x axis for each of the three varieties. Changing dataAvgSuc$Collection to just Collection made the function work (I think so), but my plot doesn't have the correct values. I think that the meanSuc should be somewhere between 0.4 and 0.8, as that is the range of values it's drawing from, but here it's coming up as greater than 3. Any idea if I'm doing something wrong with getting my means?
Comment: @Trev it might help to clarify what you want in your desired plot. did you want meanSuc on your y axis? right now, within each variety, you have multiple meanSuc values for a given collection. for example, subLamoka has 2 meanSuc values for Collection #1 (2 different irrigation rates); did you want those added together (.733+.828=1.5)? could that be what you are seeing for your higher numbers?
Comment: @Ben thanks for the response! I would like meanSuc on my y axis and the two collections on the x axis. I would like to have one of these graphs for each of the 3 varieties. What you mentioned sounds like it could be the problem; I am ignoring the different irrigation rates for now (non-significant factor) and would like those averaged together. Do you have an idea as to how I'd do that? Thanks again!
Comment: if you would like to ignore the irrigation rates for now, then you don't need to include the variable 'Irrigation' in group_by: just do group_by(Collection, Variety)...also, instead of subsetting the data based on Variety, you can use facet_wrap to show a separate graph for each Variety (see suggested answer by Jonni). the only change would be removing Irrigation...is this what you had in mind?
Comment: That completely solved it, it was the irrigation variable causing issues. I wasn't familiar with the facet_wrap function until now, but that seems much more efficient than subsetting everything. Thanks a ton!
Answer: Trev,
Had some trouble re-generating the issue as the sample data provided are for just 6 observations, not 30. So not sure if the below solution would work for you or not.
I used the code you supplied to create the dataframe:
data <- structure(list(Sample = c(1011L, 1012L, 1014L, 1024L, 1025L, 1026L),
        Collection = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
        "2"), class = "factor"),
        Irrigation = structure(c(3L, 3L, 3L,5L, 5L, 5L), .Label = c("Rate1", "Rate2",
        "Rate3", "Rate4", "Rate5"
         ), class = "factor"), Variety = structure(c(2L, 1L, 3L, 3L, 2L,
        1L), .Label = c("Hodag", "Lamoka", "Snowden"), class = "factor"),
                   Suc = c(0.7333, 0.4717, 0.5883, 0.6783, 0.8283, 0.6833),
                   Gluc = c(0.03, 0.04, 0.043, 0.075, 0.057, 0.087),
                   L = c(59.48, 57.59, 59.25, 66.45, 68.29, 65.65),
                   a = c(4.36, 6.85, 3.43, 1.7, 0.78, 2.84),
                   b = c(26.82, 27.6, 26.2, 26.14, 25.37,27.19),
                   NoDefect = c(100L, 100L, 100L, 92L, 100L, 100L),
                   Defect = c(0L, 0L, 0L, 8L, 0L, 0L)),
       row.names = c(NA, 6L), class = "data.frame")

data$Collection

However, your Collection factor is defined with two levels but only one is shown in the example. Perhaps this could be why the averages were coming out greater than 1?I modified the code below to have 2 levels of collection represented in the data.
data2 <- structure(list(Sample = c(1011L, 1012L, 1014L, 1024L, 1025L, 1026L),
        Collection = structure(c(1L, 1L, 1L, 2L, 2L, 2L), .Label = c("1",
        "2"), class = "factor"),
        Irrigation = structure(c(3L, 3L, 3L,5L, 5L, 5L), .Label = c("Rate1", "Rate2",
        "Rate3", "Rate4", "Rate5"
         ), class = "factor"), Variety = structure(c(2L, 1L, 3L, 3L, 2L,
        1L), .Label = c("Hodag", "Lamoka", "Snowden"), class = "factor"),
                   Suc = c(0.7333, 0.4717, 0.5883, 0.6783, 0.8283, 0.6833),
                   Gluc = c(0.03, 0.04, 0.043, 0.075, 0.057, 0.087),
                   L = c(59.48, 57.59, 59.25, 66.45, 68.29, 65.65),
                   a = c(4.36, 6.85, 3.43, 1.7, 0.78, 2.84),
                   b = c(26.82, 27.6, 26.2, 26.14, 25.37,27.19),
                   NoDefect = c(100L, 100L, 100L, 92L, 100L, 100L),
                   Defect = c(0L, 0L, 0L, 8L, 0L, 0L)),
       row.names = c(NA, 6L), class = "data.frame")

data2$Collection

Since you're using dplyr just keep piping that object into ggplot-- I don't think you would need to create subsets of new dataframes, but can instead graph them all separately with a facet_wrap command. I also am using geom_col instead of geom_bar, which the latter is generally trying to graph count data. Since you want to plot an average, geom_col may be better. Also since the example below is piping to the next line, the "data=" definition typically used in ggplot commands is not needed.
First with data:
data %>%
        dplyr::group_by(Collection,Irrigation, Variety) %>%
        dplyr::summarise(meanSuc=mean(Suc)) %>%
          ggplot(aes(x = Collection, y = meanSuc)) +
            geom_col() +
             facet_wrap(.~Variety)

Incorporate Irrigation:
data %>%
        dplyr::group_by(Collection,Irrigation, Variety) %>%
        dplyr::summarise(meanSuc=mean(Suc)) %>%
           ggplot(aes(x = Collection, y = meanSuc, fill = Irrigation)) +
             geom_col() +
              facet_wrap(.~Variety)

And using data2 instead, as defined above, will produce the Collection levels 1 and 2 side by side on the graph. With this method I was able to generate a result and all averages were less than 1, between .4~.8


Clearing a timer without storing it in nodejs

Question: Is there a way to clear a setTimeout without storing it in a variable and then passing it to clearTimeout?
Or somehow make setTimeout return an id instead of an object, that I would pass to clearTimeout?
Comment: I just came across this exact issue. Everyone is showing var id = setTimeout(...), but an did is not returned, it is an object. Did you find an answer or workaround?
Answer: function myTimeout(f, ms) {
    var id = setTimeout(f, ms);
    return {
       cancel : function() {
          clearTimeout(id);
       }
    };
}

var t = myTimeout(somefunc, 5000);

// ...

t.cancel();


Iterm2 weird/duplicate/missing characters when pasting large amounts of code

Question: Does anyone else notice this problem? I get repeated characters or missing characters or weird spacing when pasting into iterm2. Does anyone else notice this?
Like this is what happens when I try pasting a large amount of sql into a psql session on iterm2:
syntax error at or near "ORORORORORORORORORORORORORORORORORORORabs"
LINE 23: ORORORORORORORORORORORORORORORORORORORabs.ordeOROR DESC

Anyone else notice this?
Answer: iTerm2 splits large text into chunks and then sends these chunks with some small delay.
This happens because because iTerm2 has very small delay by default.
To fix large text pasting you can change chunk size and delay options using defaults command. Just run commands bellow in your iTerm2:
defaults write com.googlecode.iterm2 QuickPasteBytesPerCall -int 1024
defaults write com.googlecode.iterm2 QuickPasteDelayBetweenCalls -float 0.08


How to retrieve MTLLanguageVersion in Metal

Question: There is an MTLLanguageVersion enum documented at https://developer.apple.com/documentation/metal/mtllanguageversion?language=objc which, if I understand correctly, returns current Metal shading language version at runtime.
The problem is, I can't figure out where to retrieve it. I can't find any related property on MTLDevice or some global function for this, and documentation doesn't help either.
Answer: MTLLanguageVersion enum is used for configuring one of the compiler options, namely, languageVersion.

You can configure the Metal compiler's options by setting any or all
of an MTLCompileOptions instance's properties, including the
following:

Target previous OS releases by assigning the languageVersion property to an MTLLanguageVersion case.

You can compile a library with your compile options instance by
calling a MTLDevice instance's newLibraryWithSource:options:error:
or newLibraryWithSource:options:completionHandler: method.


Does the "Deathblow" animation grant i-frames?

Question: I had a discussion with a friend about the mechanics of Sekiro, and we came up with some interesting variations in our experience. Some were about the usefulness of certain abilities - his experience was that (for example) using the grappling hook on certain enemies was pointless, as it simply drew him closer, just in time for to be hit by the enemy. I, on the other hand, had a window big enough to attack, then retreat, without being hit. I believe this was simply a timing issue.
The other main issue he had, was to do with the deathblow animation. Personally, I have used this to avoid damage from other enemies. When I'm surrounded by other enemies, I would be grateful for the opportunity to inflict a Deathblow, as it meant I was safe from other incoming attacks. He, however, has not experienced this. It did only happen once, but in a similar situation, just as he entered the deathblow animation, a Club/Mallet Soldier hit him, and he died.
To be honest, I have not played much of the game, and I have only played up to the first boss, so my experience of the mechanics is still fairly fresh. What, including the deathblow animation, causes I-frames, and what is the exact window, and can it be affected by specific enemies?
Answer: What causes I-Frames:

Dash/dodge grants a few I-Frames. They are way less than e.g. in Dark Souls
Deathblow animation

As the quesiton is pretty specifically asking about the deathblow, let me explain a bit. The deathblow animation grants I-Frames for as long as you have no control of the character. This means, that as long as you are still opting to execute the deathblow or not, you can still be hit, as you still have control over the character. As soon as you chose to execute the deathblow, you are invincible. The invincibility holds as long as you are on the enemy. This includes the execution of any ninjutsu. As soon as the whole animation is finished (regain of full control of character), you are no longer invincible.
I guess you both simply have a different understanding of what exactly the deathblow animation is (option to execute deathblow vs actually executing the deathblow).
While we are at it, lets also have a look at the grappling hook. My experience is, that it should be used to close big distances to bosses. It does not grant any I-Frames. The hook normally "staggers" the enemies for you to be able to land the aerial attack.
While fighting the Demon of Hatred, I was always able to land the aerial attack. Also I experienced the fact that one is not invincible as his fire on the ground attack dealt damage shortly before the grappling animation had started.
Comment: You mention two "phases" of the deathblow - the option to execute, then the execution. I am unaware of this? How are these two phases determined/controlled? Can you opt out of the execution?
Comment: The option to execute is shown via the red dot on the enemy. If it is not a stealth kill, this option only is available, as soon as you deal enough posture damage (completely fill the bar at top of screen). Then you need to go close to the enemy and attack him to actually execute the execution. If you simply wait a bit, this option passes, as the posture regenerates. I believe that it is a different timeframe for different types of enemies. As fas as I know, there is no way to interrupt the actual execution. So once you chose to execute an enemy, the enemy is dead (looses 1 health bar)
Comment: Regarding missing the window of actually executing the enemy: Bosses need to be executed twice on the last health bar to actually kill them. A failed attempt to actually execute the Snake boss: [video](https://youtu.be/hWnHFpf2Dls?t=309).
Comment: Jumping also grants _some_ I-Frames.
Comment: @Exa do you have any proof for that? So far I got hit on by every attack while jumping, unless that attack is supposed to be dodged by jumping (low round slashes; Demon of Hatred charge etc.)
Answer: I am pretty sure it does grant i-frames, as I have used deathblow surrounded by enemies and didn't get hut during the animation. I was however using the deathblow smoke ability, so that may factor into the i-frames. – JoeryJV in a comment


Derivative of integral with varying domain? Fundamental theorem of calculus?

Question: Say I want to find the $n^{th}$ derivative of
$$\int_{V_x} F{(x_1,...,x_k)}dV$$
where $V_x$ is some $k$-dimensional volume dependent on $x$. In the $1$-dimensional case this is the fundamental theorem of calculus for $n=1$ and we can take higher derivatives after applying the fundamental theorem. To be concrete, say $V_x$ is the cube $[0,x]^k$. What can I do in general? Is this Stokes theorem?
Comment: This isn't a complete answer because I'm not familiar with the general theorem, but I Googled "leibniz integral rule higher dimensions" and found [the "higher dimensions" section of the Leibniz Integral Rule page on English Wikipedia](https://en.wikipedia.org/wiki/Leibniz_integral_rule#Higher_dimensions), which highlights something called the [Reynolds transport theorem](https://en.wikipedia.org/wiki/Reynolds_transport_theorem) which seems to be what you want (except more general as it allows $F$ to depend on $x$ as well).
Answer: Do a change of variable to eliminate the dependence on $x$ in the integral bounds and note that $x$ inside the integral is a dummy variable. Namely, $$\int_{V_x} F(x)\,{\rm d}x = \int_{[0,x]^k} F(y)\,{\rm d}y$$Now write $g\colon [0,1]^k \to [0,x]^k$ as $y = g(z) = xz$. Then $Dg(z) = x{\rm Id}_{\Bbb R^k}$, so $\det Dg(z) = x^{k}$. So ${\rm d}y = x^k\,{\rm d}z$, and so $$\int_{[0,x]^k} F(y)\,{\rm d}y =\int_{g([0,1]^k)} F(y)\,{\rm d}y =\int_{[0,1]^k} F(xz)\, x^k\,{\rm d}z = x^k\int_{[0,1]^k} F(xz)\,{\rm d}z.$$Hence $$\frac{{\rm d}}{{\rm d}x} \left(x^k\int_{[0,1]^k}F(xz)\,{\rm d}z\right) = kx^{k-1}\int_{[0,1]^k} F(xz)\,{\rm d}z + x^k \int_{[0,1]^k} \langle \nabla F(xz), z\rangle\,{\rm d}z.$$To bring the domain back to what it was in the beginning, we undo the change of variable, to get: $$\frac{{\rm d}}{{\rm d}x}\left(\int_{[0,x]^k}F(y)\,{\rm d}y\right) = \frac{k}{x} \int_{[0,x]^k}F(y)\,{\rm d}y + \frac{1}{x}\int_{[0,x]^k} \langle \nabla F(y), y\rangle\,{\rm d}y.$$
Note that it makes perfect sense for this formula to become singular for $x=0$, as this is the case where your domain of integration $[0,x]^k$ degenerates to a point.
Comment: Very nice answer; of course we can deal with the general case where $V_x =\phi(x,\cdot)[A]$ is given as the image of some fixed set under a smooth mapping $\phi$ (I tried to work it out but then I stopped halfway once I realized that differentiating the determinant which comes up from change of variables theorem is going to be a pain). And of course calculating the $n^{th}$ derivative as OP intended will be much more cumbersome.
Comment: Although, to differentiate $\det D\phi(x,\cdot)(z)$ in general, the chain rule would give us some trace, and the second total derivative of $\phi(x,\cdot)$, so Hessians and Laplacians would probably show their ugly heads in higher order derivatives.
Comment: Yes! And that's why I only showed the case where $V_x = [0,x]^k$, in hopes it would illustrate the idea enough :P

(and with this answer I hit 62k rep here --- the endorphins are appreciated, since I'm stuck home)
Answer: The general problem would be to compute the derivative of
$$ F(\mathbf{x},\mathbf{u}) = \int_{\Omega(\mathbf{u})} f(\mathbf{x})d\mathbf{x} $$
with respect to $\mathbf{x}$ with $\mathbf{u} = \mathbf{T}(\mathbf{x})$ (in this case $T = I$ is the identity map). The generalized Leibniz rule gives:
$$ \frac{\partial F}{\partial \mathbf{u}} = \int_{\partial \Omega(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma $$ Combining this result with Leibniz rule again for differentiation under the integral sign and using the chain rule  the gradient with respect to $\mathbf{x}$ is:
$$ \frac{\partial F}{\partial \mathbf{x}} =  \int_{\Omega(\mathbf{u}))} \nabla_{\mathbf{x}}f(\mathbf{x})d\mathbf{x} + \frac{\partial T}{\partial \mathbf{x}}^{\top}\int_{\partial \Omega(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma   $$
The hidden complexity here is how to compute the "velocity" of the boundary points as the domain change. As an example consider the two-dimensional domain $\Omega = [0,x_1] \times [0,x_2]$ and the function $f=1$ then $F = \int_{\Omega} f d\mathbf{x} = x_1 x_2$ and obviously $\nabla F = [x_2 \, \,  x_1]^{\top}$. Applying the previous machinery we get:
$$  \frac{\partial F}{\partial \mathbf{x}} =  \int_{\Omega(\mathbf{u}))} \nabla_{\mathbf{x}}f(\mathbf{x})d\mathbf{x} + \frac{\partial T}{\partial \mathbf{x}}^{\top}\int_{\partial \Omega(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma =  \int_{\partial \Omega(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma = \int_{\Gamma_2(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma + \int_{\Gamma_3(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma $$
Being $\Gamma_2$ and $\Gamma_3$ the right and upper sides of the rectangle that are the only ones that have non-zero velocity of their boundaries. Since $\Gamma_2$ is moving in the horizontal direction we have $\frac{\partial \mathbf{x}}{\partial\mathbf{u}}^{\top} = \begin{bmatrix} 1 & 0 \\ 0 & 0\end{bmatrix}$ on $\Gamma_2$ while $\frac{\partial \mathbf{x}}{\partial\mathbf{u}}^{\top} = \begin{bmatrix} 0 & 0 \\ 0 & 1\end{bmatrix}$ on $\Gamma_2$ (i.e. $\Gamma_2$ is moving vertically) then we have:
$$ \frac{\partial F}{\partial \mathbf{x}} = \int_{\Gamma_2(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma + \int_{\Gamma_3(\mathbf{u})} f(\mathbf{x})\frac{\partial \mathbf{x}}{\partial \mathbf{u}}^{\top} \mathbf{n}(\mathbf{x})d\Gamma = \int_{\Gamma_2(\mathbf{u})} \begin{bmatrix} 1 \\ 0 \end{bmatrix} d\Gamma + \int_{\Gamma_3(\mathbf{u})} \begin{bmatrix} 0 \\ 1 \end{bmatrix} d\Gamma  = \begin{bmatrix} x_2 \\ x_1 \end{bmatrix}$$


Is it possible to programatically enable/disable hardware?

Question: In our project, we've received a requirement where the the user is to be capable of enabling/disabling a COM Port / USB Port / Ethernet Port via our application's gui.
Is it possible to manipulate harware's enabled/disabled state programatically in C#?
Comment: There's a similar question here:

http://stackoverflow.com/questions/668889/port-enable-disable
Answer: According to responses in this discussion thread, USB ports can be disabled by modifying a registry key.  You can certainly do that in C#.
In general, this is really a Windows hardware question more than a C# question.  C# does not have any special access or control of hardware - anything you want to do in C# will have to be done using the Windows OS APIs or configuration tools.  Just about any unmanaged Windows API can be called from managed .NET code (C# or otherwise) using .NET's PInvoke.
Answer: Shot in the freaking dark here, if you can write a separate *.exe file or something to do it, you can call the *.exe file in C# code.
Checkout System.Diagnostics.Process API.
<code>System.Diagnostics.Processp = new Systems.Diagnostics.Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "cmd";
p.StartInfo.Arguments = "..."; // Your command and args here
p.StartInfo.RedirectStandartOutput = true;

p.Start();
p.WaitForExit();
</code>
Good Luck!


Geometrically distinguishing between relative positioning of 3 points on a line

Question: Scenario: we have a line in a 2D plane, and we place 3 points on it each having a different color. For example:

we see in this case that the blue point is the first point, the green is the second and the red the last one.
Here's a second scenario where the red point is behind the green point, i.e. green comes last:

I am trying to find out if by a simple geometric criterion one can figure out if the red point is past the green point (as in the 1st image) or if the red point is behind the green one and past the blue (as in the 2nd image).
The drawn vectors are my attempt to solve the mentioned problem: with the vectors defined as: $\vec{x}$ connecting blue to green, $\vec{y}$ connecting green to red, and $\vec{z}$ connecting blue to red, we can form the shown triangles, which relates them as $\vec{x} + \vec{y} = \vec{z}.$ And the triangle inequality tells us the norm of $z$ is smaller or equal to the sum of the two other norms. But I am getting stuck in how to use this triangular relation in order to distinguish between the two cases.
Question:

Is there a simple geometric criterion, possibly based on this vectorial formulation, that for a given set of 3 points, allows us to distinguish between the 1st image and the 2nd? For simplicity we assume the blue point to be always the first point, but the relative positioning of the next two points can change.
Comment: If the line can have any shape,  $||\vec{z}||>||\vec{x}||$ should not be sufficient. Think of a very steep parabola (far steeper than the one on your second image). The blue point can be at a very large vertical distance from the next, but a very short horizontal distance from the last. This would render irrelevant the comparison of the lengths.
Comment: Can you compare the first components of the points? If there are no loops in the line I think it should be enough
Comment: @Patricio yes this is also an approach, but then there cases such as the line being along the y-axis, therefore all 3 points having the same x-component. So one would write out a set of conditions covering all such cases. And moreover, circular lines are also allowed :/
Comment: FYI - in English mathematics, we usually call these shapes "curves", reserving the term "line" specifically for curves that are straight. I.e., follow a path that minimizes distance.
Comment: @PaulSinclair you're right, thanks very much!
Answer: There is no way to distinguish order strictly by the vector representations. You have to know something more about the curve to determine the order. For example, in your second example, you would get the exact same three vectors from a curve that headed more directly towards $x$, then turned tightly to head back towards $y$. But in that case the order of the points on the curve are "origin, $x$, $y$", instead of the "origin, $y$, $x$" in your example.
How else you handle this is going to depend on what you are trying to do, and whether there is anything more that you know about the curve. If you just have a collection of points, and are trying to guess the order in which they are traversed, then an "always go to the closest" rule (with some tie-breaker clause) is the best you can hope for. Either that or "minimize the sum of the angles over the whole path".


Why aren't my pets getting paid?

Question: I have The Sims 2 installed with all expansions and official patches (I miss stuff packs however).
I have a problem concerning pets: basically when they come back from work (after a few game days where everything works fine) they don't get a salary. They also can't get a promotion: it seems that the pets coming back home fails to trigger some routine.
I also tried totally erasing the Sims2 directory in my Documents and Settings folder (thus forcing the program to recreate the neighbors from scratch) but I still have the same problem.
However, this doesn't seem to be a common problem around the Internet. Is this bug known? Do you know how to solve it?
Comment: I'm picture a dog going to work and demanding his salary with a series of barks.
Comment: I havent played sims in a long time, but am i getting this right?
you can now send your DOG to work? and it get promotions... and pay?
Comment: @Trew And still no diving board.
Comment: @Trew Yes you can.
Answer: Found a couple other people and have the same problem myself.  Seems to go away if Apartment Life is removed.  No other fix found yet.
Comment: I re-installed everything except Apartment Life and the problem disappeared. I guess that last pack is very buggy...

Why aren't my pets getting paid?


URL to open Compose mail in new window with Unity Mail

Question: I use the "Unity Mail" app, and it does what i need. It's a really nice app.
But there's a thing i can't figure out.
I have made a custom URL in "Compose" in the preferences, so that instead of opening gmail with a new compose mail in the corner, I get an new clean tap with only the new compose mail.
https://mail.google.com/mail/?ui=2&view=cm&fs=1&tf=1&shva=1
The question are, what piece of code do i need to ad, to make it open in a new separate window instead of a new tap? -and possible in a predefined size?

I use Chromium, but firefox behaves the same.
Answer: Asked at launchpad:
Exec:chromium-browser --new-window 'https://mail.google.com/mail/?ui=2&view=cm&fs=1&tf=1&shva=1'


How do I search partial words in Lucene when using MultiFieldQueryParser?

Question:  public SearchResult search(String queryStr, SortBy sortBy, int maxCount)
      throws ParseException, IOException {
    String[] fields = {Indexer.TITLE_FIELD_NAME, Indexer.REVIEW_FIELD_NAME, "name"};

    QueryParser parser = new MultiFieldQueryParser(fields, analyzer);
    Query query = parser.parse(queryStr);

    Sort sort = null;
    if (sortBy != null) {
        sort = sortBy.sort;
    }

    return searchAfter(null, query, sort, maxCount);
}

Above method just gives me the result, but for that I have to search for the whole word but if I search partial word it doesn't work.
Answer: By default MultiFieldQueryParser (and QueryParser, which this class inherits from) will look for the whole words you are searching, however it can also generate wildcard queries. The word "elephant" can be matched by using elep*, elep?ant (i.e. ? mathes a single letter) or ele*nt. You can also use fuzzy queries, like elechant~.
You can read the whole syntax specification here: http://lucene.apache.org/core/7_5_0/queryparser/org/apache/lucene/queryparser/classic/package-summary.html (below the class list).


How to convert an "IO (Either e a) into an ExceptT e m a

Question: I'm using Control.Monad.Except and am stuck in a place where I have to force execution of an ExceptT AppError m a action to obtain an IO action, and then to wrap it back again into an ExceptT AppErr m a. If you're wondering why this is required, it is because the underlying library function that I need to run, only accepts IO action. In this case it would be Database.PostgreSQL.Simple.withTransaction :: Connection -> IO a -> IO a
How do I write the conceptual equivalent of the following:
type AppM = ExceptT AppError (ReaderT Env (LoggingT IO))

runAppM :: Env -> AppM a -> a

withTransaction :: AppM a -> AppM a
withTransaction appm = do
  conn <- getDbConnection
  env <- getEnv
  liftIO $ PGS.withTransaction conn $ runAppM appm

Here's the error that I'm getting:
Excepted type: ExceptT AppError (ReadertT Env (LoggingT IO)) a
Actual type: ExceptT AppError (ReadertT Env (LoggingT IO)) (Either AppError a)

Comment: The title and body of your question are completely different questions.
Answer: Use the constructor ExceptT : m (Either e a) -> ExceptT e m a
withTransaction :: AppM a -> AppM a
withTransaction appm = do
  conn <- getDbConnection
  env <- getEnv
  ExceptT $ PGS.withTransaction conn $ runAppM appm

Comment: Still gives an error: `Expected type: ExceptT AppError (ReaderT Env (LoggingT IO)) a // Actual type: ExceptT AppError IO a`
Comment: This answer is wrong, presumably because the question in the title is not the same as the actual question in the body.
Comment: `PGS.withTransaction conn $ runAppM appm` evaluates to an `IO (Either e a)` and it needs to be converted to an `ExceptT e m a`. Is there a gap in my understanding of what's happening here?
Comment: I see. `ExceptT $ liftIO $ PGS.withTransaction conn $ runAppM appm` is right. `liftIO` lifts `IO (Either e a)` to `ReaderT Env (LoggingT IO) (Either e a)` and then `ExceptT` lifts it to `AppM a`


Enhancements to programming languages that had to be withdrawn after release?

Question: Are there examples of significant enhancements to major programming languages that were fully released and then found to be sufficiently flawed that they had to be withdrawn?
UPD @Jeff Foster has an example of a feature that is not consistently implemented and I'd take those as answers
UPD There is a grey area between Deprecated and withdrawn. I suspect that there are thousands of Deprecated examples - which can still be used but are not advised. I can conceive that there are features which some creators thought they could implement fully or consistently but actually broke the integrity of the system.
I was particularly looking for enhancements (not original features) as these will have been planned (probably with community involvement) and released after testing, etc.
Comment: If you're willing to step outside *programming* languages, then the HTML 'font' element is probably the standard-bearer for "no, now we come to think about it, we've changed our minds"...
Comment: Having been intimately involved in the XML process I contrast this with both SGML (too complex to implement completely) and HTML (not enough community resolve). So, yes, I'd probably include major meta-languages of this sort :-)
Answer: C++ has a keyword "export" which very few compilers implement.  It's not been withdrawn, but since so few compilers implement it that it is effectively useless.  See here for more information.
Comment: Also a recent C++0x committee straw poll supported deprecating it: http://herbsutter.wordpress.com/2009/10/23/deprecating-export-considered-for-iso-c0x/ But the C++ standard is not a good place to look for an "enhancement" which has been "removed", since by definition that requires three releases, and C++ has so far only ever had the original standard plus corrections ;-)
Comment: So if something is "wrong" there have to be three (?major) releases before it's removed? Be interesting to know more
Comment: No, I just mean that in this question, for something to be an "enhancement" as opposed to an original feature, it would have to not be in the first release, but be added in a revision. Then for it to be "removed" there must be a third release. Some languages, such as Perl, have had dozens or hundreds of releases. But C++ is almost a demonstration exercise in big design up-front, so there aren't really opportunities for language features to just come and go. C++ implementations do change of course.
Comment: Also it's ISO good practice only ever to remove deprecated features. So unless something is so disastrously wrong that it breaks the rest of the standard, then actually it should take two releases to remove it - one to deprecate, then one to remove. It's a slow process with ISO, because they really care about backward compatibility. For instance everyone knows `gets` is rubbish, but it isn't even deprecated in C99.
Comment: C has/had "entry" as a registered keyword. It was supposed to be used to give C-functions multiple entry points, kind of symmetric with allowing them to have multiple exit points.
Answer: reduce() in Python has been removed from the global namespace from python 3.0. It can still be found in the functools module though, so I don't know if it really counts. The reasoning behind this is given in GvR's blog entry: http://www.artima.com/weblogs/viewpost.jsp?thread=98196.
Comment: Good example (by chance we were discussing it yesterday!)
Answer: Even though this is entirely catered toward programming languages it's inevitable to deal with HTML on the web, so I apologize but must mention that..
applet, basefont, center, dir, font, isindex, menu, s, strike, u elements are deprecated in HTML 4.01, most usually in favor of CSS for styling as presentation and structure shouldn't be mixed.
Comment: Given that HTML requires huge amounts of code to be written I think this is a reasonable example of withdrawal. In one sense they are not technically flawed, just ugly and superseded by better ways of doing things
Answer: Deprecated features in PHP 5.3.x include magic_quotes, register_globals, and these functions are deprecated:

call_user_method() (use call_user_func() instead)
call_user_method_array() (use call_user_func_array() instead)
define_syslog_variables()
dl()
ereg() (use preg_match() instead)
ereg_replace() (use preg_replace() instead)
eregi() (use preg_match() with the 'i' modifier instead)
eregi_replace() (use preg_replace() with the 'i' modifier instead)
set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
session_register() (use the $_SESSION superglobal instead)
session_unregister() (use the $_SESSION superglobal instead)
session_is_registered() (use the $_SESSION superglobal instead)
set_socket_blocking() (use stream_set_blocking() instead)
split() (use preg_split() instead)
spliti() (use preg_split() with the 'i' modifier instead)
sql_regcase()
mysql_db_query() (use mysql_select_db() and mysql_query() instead)
mysql_escape_string() (use mysql_real_escape_string() instead)
Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
The is_dst parameter to mktime(). Use the new timezone handling functions instead.
Comment: Were these enhancements introduced post V1.0? and then found to be flawed?
Answer: Having spent many years hacking FORTRAN here are some of the delightful constructs removed from F77 (http://en.wikipedia.org/wiki/Fortran#Obsolescence_.26_deletions):

In this revision of the standard, a
  number of features were removed or
  altered in a manner that might
  invalidate previously
  standard-conforming programs. (Removal
  was the only allowable alternative to
  X3J3 at that time, since the concept
  of "deprecation" was not yet available
  for ANSI standards.) While most of the
  24 items in the conflict list (see
  Appendix A2 of X3.9-1978) addressed
  loopholes or pathological cases
  permitted by the previous standard but
  rarely used, a small number of
  specific capabilities were
  deliberately removed, such as:
* Hollerith constants and Hollerith data, such as:

    `GREET = 12HHELLO THERE!`

* Reading into a H edit (Hollerith field) descriptor in a FORMAT

specification.
      * Overindexing of array bounds by subscripts.

    DIMENSION A(10,5)
>         Y= A(11,1)

* Transfer of control into the range of a DO loop (also known as

"Extended Range").

Oh the heartbreak of no longer being able to jump into the middle of deeply nested DO loops.
Answer: There don't seem to be any clear examples.


The XPath id() function

Question: I can't find any good explanation of the id() function in XPath. What does it do? How do you use it?
From the available descriptions, it sounds like it will give you id of a node.
So I played with it like this, but got an error:
//bookstore/id(book)

Then got a little fancier and tried
//bookstore/book[name = id(book/@category)]

which didn't return an error, but got no hits.
Can someone explain this function for me, and future Stack fans and Googlers?
Here's the XML I'm playing with:
<?xml version="1.0" encoding="ISO-8859-1"?>

<bookstore>

<book category="COOKING">
  <title lang="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J. K. Rowling</author>
  <price>29.99</price>
</book>

<book category="WEB">
  <title lang="en">XQuery Kick Start</title>
  <author>James McGovern</author>
  <author>Per Bothner</author>
  <author>Kurt Cagle</author>
  <author>James Linn</author>
  <author>Vaidyanathan Nagarajan</author>
  <year>2003</year>
  <price>49.99</price>
</book>

<book category="WEB">
  <title lang="en">Learning XML</title>
  <author>Erik T. Ray</author>
  <year>2003</year>
  <price>39.95</price>
</book>

<book category="OPENSOURCE">
  <title lang="en">Open Source</title>
  <year>2003</year>
  <price>39.95</price>
</book>

<book category="WEB">
  <title lang="en">WEB</title>
  <year>2012</year>
  <price>21.99</price>
</book>

</bookstore>

Comment: You should play with a document that does contain `id` attributes, isn't it? :)
Answer: It appears that based on the spec that you would only use the id() function if you have defined unique IDs in your DTD.

The id function selects elements by their unique ID.
...
An element node may have a unique identifier (ID). This is the value of the attribute that is declared in the DTD as type ID.

I also came across this SO question that discusses the ID type in a DTD and how to define that.
Answer:
I can't find any good explanation

Let me recommend my book ;-).
I don't think the id() function will help you because I don't think your source document has any ID attributes. It has very few attributes, and those it has are not unique, so they cannot be IDs.

The XPath id() function


What screws should I have used for drywall? (And can I fix this situation?)

Question: I'm installing an IKEA Bjurstra wall-mounted table.
The primary load-bearer is the vertical column, and I've successfully fastened this to a wood stud using 2x #12x2 pan head drill screws:

But the same screws applied to the braces that keep the table flush to the wall, ended up only stripping the dry wall:

So now, though the vertical column is holding up the table just fine, the screws on the braces are loose and hanging out.

What kind of screws should I have used?
Aside from starting over and installing the table at a different height, what can I do to amend this situation?

I am not a DIY-savvy person, so I would prefer ease or convenience over cost-savings. Thank you.
Comment: Or, did the drywall strip because of how I screwed things in? I used a power drill to first drill a pilot hole, then the power drill again to screw in the screws with moderate but not strong pressure.This actually seemed to have worked for 1 of the 4 screws, but the rest stripped.
Comment: Next time, try and find the nearest stud - a vertical strip of timber holding up the plasterboard - and screw into that instead, if it is close enough. Otherwise, as noted, use a "readi-driver" or any other type of plasterboard anchor (not just a rawl-plug - they don't have enough holding power for plasterboard)
Answer: I expect you want some kind of wall plug. You would take the table down, install the wall plugs (which generally need a bigger hole than screws so your exiting screwholes shouldn't be an issue) and then screw the shelf to the wall plugs.
Here in the UK I would look at something like this, but i'm not sure how american drywall compares to our plasterboard (also not sure if that one is the right size, I generally judge sizes of such things by eye rather than measurements).
Comment: Here is an American equivalent.  The term is wall anchor or screw anchor.  There are other types, but I do like these.
http://www.homedepot.com/p/E-Z-Ancor-Twist-N-Lock-75-lb-Medium-Duty-Drywall-Anchors-50-Pack-25310/100040265
Answer: Agree that you want some dry-wall anchors. Just running a screw into drywall has absolutely no holding power - you need to get something with a very coarse thread, or an anchor that goes through the wall and holds it from the rear side.
Whatever you select, look for the load rating, and divide by 4 for the maximum weight of table and its loading. I prefer Toggler metal connectors (these have a 265lb rating in drywall - and I doubt that the table and contents will weigh more than 66lb).
To install these you need a 1/2" drill bit - so you can reuse the holes you've already drilled for the screws that Bjursta'd out.


python equation calculation with exp() function

Question: Here is the equation I'm tryin' to solve:

the correct answer most be 0.347 and this is what I got:
from math import *

exp(((-4.4 + 0.6*(0.6/1.2))*tan(25)) + ((3.07*sin(25))*(log(2*4.29))/(1+sin(25))))

output:
0.6318

I tried to use radians : tan(radians(25))
I keep getting wrong results
Comment: How do you know that the correct answer is actually 0.347?
Comment: `log` is the natural log. `log10` is the base10-log
Answer: 0.347 (ignoring the rounding error) is correct if you use the base 10 logarithm and your arguments are in degrees for the trigonometry functions.
0.6318 is correct for natural logarithm and radians.
>>> from math import exp, log, sin, tan, radians
>>> exp(((-4.4 + 0.6*(0.6/1.2))*tan(radians(25))) + ((3.07*sin(radians(25)))*(log(2*4.29, 10))/(1+sin(radians(25)))))
0.34627767629783546