What animal are these coffee-ground-like leavings around my doorframe from?

Question: We are finding strange stuff around the frame of our bathroom door. It looks almost like ground coffee, and has no discernible smell. It's getting out of hand: we cleaned it up yesterday and this much has showed up again today:

There is nothing above or around the frame where this could have come from: no holes or cracks.
Is this the work of some form of woodworm, termite, or some other animal?
We live in a hot, arid climate on the Canary Islands.
Comment: Brew up  cup and try it. MMMMM Termite dung coffee :)  ( Just a joke, do  not do that ).
Answer: I'm not a pest control specialist but that's got insect written all over it, and given the proximity to that wooden architrave/post/whatever-it-is I'd be worried about termites or some other wood boring critter. Call an exterminator post haste.
Comment: I agree, that looks like dry-wood termite excrement. They make "dump holes" in the galleries they carve out while munching away at your woodwork. Zap em with Term-Out.
Comment: Definitely termites. Do a google image search for "termite excrement"
Answer: Its termite droppings. No smell cuz it's pretty much sawdust
Comment: Carpenter ants are another possibility.


What would be the proper connectors to use to enter the box?

Question: Running 1 1/2 PVC with 2-2-2-4 inside to an 8x8x4 PVC J box to connect to 2-2-2-4 SER cable inside box.
Answer: You'll use a 1 1/2" PVC male terminal adapter, to fit through the knockout in the box. Then a 1 1/2" locknut inside the box, to hold the terminal adapter in place.

For the SER cable, you can use a 1 1/2" cable clamp.
Comment: @KathleenWeymouth, NO, the SER MUST terminate in a proper connector. I'd use a 1-1/4" SER connector. Like the one shown, only the bottom half of the "saddle" is rounded not flat.
Comment: Thank you. What about the 2-2-2-4 ser ? Can I run it in to the bottom of the box threw a 1 inch male adapter. I have been told SER cannot be run threw conduit - but I think a male adapter would be alright , just not sure.


Prove a sequence to the power n converges

Question: Here is my question:
Let $a \in \Re$ such that $|a|\lt 1$ and  $\{a_n\}$ a sequence. Prove that if $a_n \to a$, then $a_n^n \to 0$
Thanks for your help.
Answer: Hint: Since $\dfrac{\lvert a\rvert+1}2>\lvert a\rvert$, eventually $\lvert a_n\rvert<\dfrac{\lvert a\rvert+1}{2}$
Answer: Hints:
Put $\;1-|a|=\epsilon>0\;$ , then there exists $\;N\in\Bbb N\;$ s.t. for $\;n>N\;$ we have
$$|a_n|<|a|+\frac\epsilon2\implies |a_n|^n\le\left(|a|+\frac\epsilon2\right)^n$$
Comment: Im sorry Im not able to complete the proof
Comment: @Fadmad $$\left(|a|+\frac\epsilon2\right)^n\xrightarrow[n\to\infty]{}0\;\;\text{since}\;\;0<|a|+\frac\epsilon2<1\;\ldots$$and now just apply the squeeze theorem.
Comment: I see, but why set 1-a=E, it implies that E is less then 1, but E can also be greater than 1.
Comment: Also, E/2 could be a large number therefore it would go to infinity, we cant just make E dependable on a
Comment: @Fadmad If we put $\;1-|a|=\epsilon\;$ and **we know that** $\;|a|<1\;$ , how can $\;\epsilon>0\;$ be a greater than $\;1\;$ ?? This is **exactly** the point !


Unable to yum install in fedora even as root user

Question: Getting the error Error: This command has to be run under the root user. when I try to install in Fedora as root user.  Tried in different ways:
Sun May 20 20:18:57 kbsbng@tr
$ sudo yum install mod_ssl
Error: This command has to be run under the root user.
Sun May 20 20:19:00 kbsbng@tr
$ sudo bash
Sun May 20 20:19:03 root@tr
$ yum install mod_ssl
Error: This command has to be run under the root user.
Sun May 20 20:19:15 root@tr
$ su -
[root@tr ~]# yum install mod_ssl
Error: This command has to be run under the root user.

Is there any security setting that is causing this?  I am trying all of the above commands by remotely sshing to the machine.
Comment: your root user seems to be corrupted, can you do this? `usermod -g root root` or `usermod -G root root`? If you can, after doing logout and login.
Comment: You're welcome. For future users, I'll post this as an answer too.
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.
Comment: Ok, is there a way I can move this question to Super User? Also, in a way, it is related to programming, since I encountered the issue when I am trying to run a server for the code that I have built.
Answer: Your root user seems to be corrupted. If user group of root is assigned something out of root (or defined groups in visudo), it'll not perform.
This will solve your problem since you'll be setting user root to group root.
usermod -g root root
usermod -G root root

after entering this, logout and login.
Comment: Stack Overflow is a site for programming and development questions. This question appears to be off-topic because it is not about programming or development. See [What topics can I ask about here](http://stackoverflow.com/help/on-topic) in the Help Center. Perhaps [Super User](http://superuser.com/) or [Unix & Linux Stack Exchange](http://unix.stackexchange.com/) would be a better place to ask.


JQuery getScript with livequery - asynchronous execution throwing off my results

Question: We had a "utility" js function that was included in several js files in our site, so to reduce code repetition we moved it to a utilities file and modified all the js files to load it before using it with getScript. This worked in most cases, but with one piece of code that uses livequery I'm getting errors.
The code that I am using successfully wherever we need to use the new function:
$.getScript("js/utilities.js", function(){
   ... use parseQueryString function ....
});

Code before:
$('.preview')
    .livequery(function(){
            $(this).attr('rel','myPage.cfm?' + parseQueryString($(this).attr('rel')));
        });

Basically, whenever an element with a class of "preview" shows up on the scene, we want to parse the rel attribute and replace it with the newly parsed string.
Code after:
$('.preview')
    .livequery(function(){
            var preview = $(this);
            // load utilities.js so that we can access the parseQueryString function
            $.getScript("js/utilities.js", function(){
                preview.attr('rel','myPage.cfm?' + parseQueryString(preview.attr('rel')));
            });
        })

The problem is, this seems to be continuing to the next iteration of the $('.preview').livequery loop before executing the callback of the getScript call. So the preview variable gets reset before we can replace its rel attribute with the appropriate value. How can I get this to execute correctly?
Answer: I think you named the problem in your title :) 'asynchronous' is exactly the cause - loading the utility is on and since the request will be made and execution will move on meanwhile..entering yet another livequery callback if more matches are available. Frankly I think it's really bad idea to put a script loading inside a function that will be looped multiple times - it's just somewhat pointless. I see no reason not to just include it like a normal script:

I think this is the simplest and most reasonable solution.
However, if you really can't use this for some reason, either ensure local copy of the variable for the callback via context (see $.ajax context option since getScript is a $.ajax shortcut it should have it too) or try synchronous ajax...the last one is an option, but please don't really try it in this case :)
Comment: I don't think you can include the script in the js file using your code, can you?
Comment: Why not? It's a script file available on the server you request with Ajax multiple times. Why not let the browser get it with the rest of the page content a single time?
Comment: see http://stackoverflow.com/questions/950087/include-javascript-file-inside-javascript-file
Comment: It's a slightly different direction to what i was thinking, but I am looking at it and it is there:
"2 - Add a script tag with the script URL in the HTML." in the answer
Your js code needs to be added to the page one way or another, it's more than OK to include the utility it uses before it, just like you invclude jQuery in advance in order to make use of it.
Answer: A work-around I just came up with that seems to be working... Put the getScript call around the livequery loop:
 // load utilities.js so that we can access the parseQueryString function
$.getScript("js/utilities.js", function(){
    $('.preview')
        .livequery(function(){
            $(this).attr('rel','myPage.cfm?' + parseQueryString($(this).attr('rel')));
        })
});

Comment: This looks somewhat better, however I'm not sure your liveQuery will function properly if you dynamically add more matching elements as this one is enclosed in the callback and once it finishes looping...


Is the closure of $ X \cap Y$ equal to $\bar{X} \cap \bar{Y}$?

Question:
$U$ is a topological space. $X$ is an open subset of $U$, and $Y$ is a closed subset. Let $Z = X \cap Y$. Does $\bar{Z} = \bar{X} \cap \bar{Y}$.

Here, $\bar{X}$ denote the closure of $X$, and $\bar{Y}$, $\bar{Z}$ respectively. (So, $\bar{Y}=Y$.)
It is clear that $\bar{Z} \subseteq \bar{X} \cap \bar{Y}$, but is it true in the reversed direction?
Comment: Think of an open and a closed ball of radius $1$ around $(\pm 1,0)$ in the plane, for example.
Comment: One-dimensional example: think of $X = (0,1)\subset \mathbb{R}$ and $Y = \{0\}$.
Comment: Yet another example: the open upper half plane in $\mathbb{R}^2$ and the open lower half plane.
Answer: A word on intuition. At least for metric spaces (and more generally for first-countable spaces), you can think of $\bar{X}$ as the collection of all points which are limits of sequences of points in $X$ (and in general you can replace "sequence" with "net" or "filter"). Then $\overline{X \cap Y}$ is obviously contained in both $\overline X$ and $\overline Y$ (as sequences of points in $X \cap Y$ are sequences of points in $X$ and also sequences of points in $Y$), but on the other hand a point in $\bar{X} \cap \bar{Y}$ is

a limit of a sequence of points in $X$ and
a limit of a different sequence of points in $Y$

and there's no obvious way to use either of these sequences to cook up a sequence of points in $X \cap Y$; the two sequences above may be disjoint, and in fact $X \cap Y$ may be empty while $\bar{X} \cap \bar{Y}$ is non-empty. With that in mind it isn't hard to find a counterexample.
Answer: Let $X$ be open and $Y = U \smallsetminus X$. Then $X \cap Y = \emptyset$. However, $\overline{X} \cap Y = \partial X$ won't be empty in general. Take $X$ to be an open ball in $\mathbb{R}^n$, for example.
Comment: @Shinya: Well, I must say that I was a bit ashamed for posting this counterexample as an answer without elaborating at all, I'm glad it helped nevertheless. Take it as a general strategy: If you don't manage to prove something, look for a simple counterexample. This will help in any case: If the statement turns out to be true, if you don't see how to concoct a counterexample, you might manage to extract the reason why you fail. Qiaochu wrote an answer recently with [some good advice](http://math.stackexchange.com/questions/53926/ideas-of-finding-counterexamples/53945#53945) on that.
Comment: What is the delta-x in English? "Boundary"??
Comment: $\partial X$ is a notation often used to mean the boundary of $X$, and it seems clear from the context that that's what it means in this case.  But it's coded as "\partial X", not as "\delta X", since that looks like this: $\delta X$.
Comment: @Michael: I was reading/writing from my phone and sometimes the markup doesn't render! I should have just reloaded and looked it up :) Thanks, though!
Comment: @Theo: Thanks very much for this example. I was wrong only to think of proofs without looking for counterexamples.
Comment: @Theo: It's very kind of you, and I just can express my gratitude. I will try this method in finding counterexamples next time.


close all child pop ups for a dynamic application

Question: we are using a jsp application, here we can open help window(window.open) from any page, but if that is opened we have to close it on clicking of logout, not necessarily on the same page where the help window was opened, How can i get Handler for a opened window across pages?
Answer: If my memory serves me right, window.open() returns the window object, so you can simply save it to a variable.
var window = window.open(...);

or
var windows = [];
windows.push(window.open(...));
windows.push(window.open(...));
windows.push(window.open(...));
windows.push(window.open(...));

Comment: correct johan but when i go to a different jsp this varialbe is no more alive


Connecting to sever through ssh

Question: I tried to connect to my sever through the ssh using ubuntu but it does not work.
 sudo apt-get install openssh-server openssh-client
[sudo] password for user:
Reading package lists... Done
Building dependency tree
Reading state information... Done
openssh-client is already the newest version (1:8.2p1-4ubuntu0.3).
openssh-client set to manually installed.
openssh-server is already the newest version (1:8.2p1-4ubuntu0.3).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
user@12122017-Dell:~$ ssh localhost
ssh: connect to host localhost port 22: Connection refused

I don't know what i am missing. What should i do? Please help me. Thank a lot
Comment: Welcome, the host must have the port 22 open. You can open ports with `ufw` (you have to install it).
Comment: Does this answer your question? [Connect two computers with SSH in a home LAN](https://askubuntu.com/questions/1107987/connect-two-computers-with-ssh-in-a-home-lan)
Comment: @schrodigerscatcuriosity UFW wouldn't block connections via the localhost interface AFAIK
Comment: So the SSH server is installed - have you verified that it is actually running (`systemctl status ssh` or `service ssh status` for example) and listening on the default port 22 (`sudo netstat -nlpt | grep sshd`)
Comment: A VPN will block local connections in some cases.
Comment: @steeldriver right! I commented in the general way, but OP's is trying with localhost then.
Comment: Thank you. So i have a remote server. Should i try it with my server to see how it's going?
Comment: I tried and here was the result.

`user@12122017-Dell:~$ systemctl status ssh

System has not been booted with systemd as init system (PID 1). Can't operate.

Failed to connect to bus: Host is down

user@12122017-Dell:~$ sudo systemctl start ssh

[sudo] password for user:

System has not been booted with systemd as init system (PID 1). Can't operate.

Failed to connect to bus: Host is down`

What should i do.
Comment: It looks like `systemd` is not installed. Which version of Ubuntu are you using?
Comment: can you install `net-tools` by `sudo apt update` and `sudo apt install net-tools` then execute `netstat -tulpn4` and add the output to your question ? that should show if your computer is listening to `ssh` service. another thing that i missed up, are you trying to connect a server? can you be more specific about what pc you are using and what machine you are trying connect to ?
Comment: I did every thing and here is the result
```user@12122017-Dell:~$ netstat -tulpn4
(No info could be read for "-p": geteuid()=1000 but you should be root.)
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name```
I wanted to connect to a hosting sever which i rented, i got a shop on that sever but it is too laggy so i tried to connect through the ssh and install some cached on it to see how it's going. I am using a dell laptop. the processor ```Intel(R) Core(TM) i5-4200M CPU @ 2.50GHz   2.50 GHz```
Comment: have you installed the `open-ssh` program on your server as well? try to run the `netstat -tulpn4` on your server after installing `net-tools` on the server.
Comment: I tried the ssh mysever@IP sever and i got. ```ssh: connect to host IP port 22: Resource temporarily unavailable```.
What does this mean and what should i do.
Answer: As you have already tried, it's definitely worth trying ssh to your localhost, to see if it's listening locally:
ssh username@localhost

If this works but you can't get it from another computer, it's probably something with your network connection, including firewwall
In your case, this doesn't work so it's unlikely to be network connection or firewall.
Have you checked that the ssh service is running?
systemctl status ssh

It should say active. If it doesn't, try starting the ssh server:
sudo systemctl start ssh
# or - alternative - if not using systemd
sudo /etc/init.d/ssh start

A machine restart is also worth trying.
Comment: And now this answer is the top result when searching for the 'no hostkeys error' :)
Comment: I tried and here was the result.

`user@12122017-Dell:~$ systemctl status ssh

System has not been booted with systemd as init system (PID 1). Can't operate.

Failed to connect to bus: Host is down

user@12122017-Dell:~$ sudo systemctl start ssh

[sudo] password for user:

System has not been booted with systemd as init system (PID 1). Can't operate.

Failed to connect to bus: Host is down`

What should i do.
Comment: DId you try an internet search? https://linuxhandbook.com/system-has-not-been-booted-with-systemd/ `sudo service ssh start` if that doesn't work, try `sudo /etc/init.d/sshd start`
Comment: Thank you i will try it. Thank you a lot.
Comment: I tried and here is what i got
```user@12122017-Dell:~$ sudo service ssh start
 * Starting OpenBSD Secure Shell server sshd                                                                            sshd: no hostkeys available -- exiting.```
What should i do
Comment: Try an internet search. Maybe with the search term *sshd: no hostkeys available -- exiting.* I think you might be able to solve it...
Comment: Thank you i will try it.
Comment: Ok, so the irony is not lost on me!! The point I was trying to make is that the answer is already out there and I was trying to encourage a little bit of research rather than spoon feeding. However, it seems the situation has now changed if this is the top answer!

Connecting to sever through ssh


IntelliJ Scala "Package" not in "New" menu

Question: I am using IntelliJ and would like to create a new Scala Package. In all of the instructions that I find online I see that I am supposed to select "Package" from the "New" menu. However, my "New" menu does not include "Package" as an option.

How can I add "Package" to this list or otherwise add a package to my Scala application?
Also as a side note, I am developing Scala applications and as such I would like for primarily Scala related templates to appear in this list as opposed to the menagerie or irrelevant templates that currently presents itself. How can I edit the list of templates that appears in this menu?
Comment: This might mean that the folder you selected and right-clicked is not identified as a Scala *source root* by IntelliJ. You can define Scala source roots manually under "Project Structure", or using the build tool of your choice (SBT, Gradle...) and reloading the IntelliJ project. If this needs further clarification - please add more information to the post: show the folder tree, explain how you set up the project, etc.
Answer: I solved this problem by taking the following steps:

Making sure to install both the Scala and SBT plugins. (I was missing the SBT plugin)
Copying all the source files (<code>*.scala</code>) into a temporary location
Deleting the project.
Creating a new project with the same structure and copying the source files into their proper location.

Now "Package" appears in the menu (and full syntax hilighting now works, which was the reason why I wanted to fix this in the first place). Note that simply installing the SBT plugin (step 1) was not sufficient in fix this problem.
Maybe it was a bug.
Comment: AFAIR if you have Scala plugin, SBT is obsolete. Also you don't have to delete everything, just `.idea` directory. Just make sure you use *new project from sources* instead of clicking *recent project* to have a control over settings.
Comment: The SBT IDEA plugin may be obsolete, SBT is certainly not.


Basement subfloor (dricore) with existing exterior framing & insulation

Question: Basement subfloor (Dricore) with existing exterior framing & insulation
I have a 2016-built house in Ottawa, Ontario with a basement that is largely unfinished (only the landing area was finished by the builder). The exterior basement walls were framed and filled with batt insulation (bottom layers removed in pictures for upcoming electrical installation). Against the foundation wall, there is black house-wrap paper as well as a small section of vapour barrier that extends up 6 inches from the floor and wraps underneath the bottom plate of the framing (photos 2+3). Of course, there was/would be another layer of vapour barrier before drywall goes up.
We're going to be installing Dricore as the subfloor system which I understand can be installed with existing walls/framing, although I also understand that building framing on top of the Dricore is preferred.
Does anyone have any advice or thoughts on using the existing insulation solution? Is it worth taking the framing down to re-build on top of Dricore/perhaps exploring an alternative insulation solution?
Comment: Clay, did you try to edit your question under the user name "mods"? If so, please register your "Clay" account and you'll always be able to edit your own post without having to have it reviewed. At a minimum, return to the browser where you wrote the post - the cookies may still be there allowing you to edit it.
Comment: You've got one layer of vapo(u)r barrier and you want to put up another one? That's a recipe for moisture collection between the barriers, leading to mold, mildew, rot, etc. Generally considered a Bad Idea™. Either that or I'm misreading your text (can't see the images right now, so maybe it's explained in the pictures).
Comment: Yes, I did. Thanks for the tip! I edited the post to clarify the vapour barrier - there is only a small section behind the black wrapping; it starts at 6" above the floor and extends underneath the bottom plate of the framing and up the other side to cover. There was a full layer of vapour barrier against the framing (removed in the pictures). This is how the builder did it in 2016.
Answer: I have laid many DriCore panels. I have had walls built on them and had it meet walls. Either way is good that I recall. Make sure your floor is flat enough, or get the shims that come with the system. Glueing is not needed in the T&G, but I did it anyway.


How should I alternate componentWillMount()?

Question: I'm using React.js, and as you know, componentWillMount() is going to be deprecated.
I wanna replace my componentWillMounts.
I'm going to move its logics into constructor. Is there any difference between executing some logic in componentWillMount and in constructor?
For example,
before
class Hello extends React.Component {
    componentWillMount() {
      doSomething();
    }

  render() {
    return
{this.state.name}

  }
}

after
class Hello extends React.Component {
    constructor(props) {
      super(props);

      doSomething();
    }

  render() {
    return
{this.state.name}

  }
}

Also, when doSomething is setState, is there any difference setting state in constructor and in public prop?
in constructor
constructor(props) {
  super(props);

  this.state = { foo: 1 };
}

in public prop
state = { foo: 1 };

Comment: Possible duplicate of [constructor vs componentWillMount; what a componentWillMount can do that a constructor cannot?](https://stackoverflow.com/questions/40828004/constructor-vs-componentwillmount-what-a-componentwillmount-can-do-that-a-const)
Answer: constructor is not the right place for performing some actions. Because it will hold other operations until it's finished.
componentDidMount is the right choice because it's an asynchronous function so that actions are run in the background and there'll be no hamper in the UI rendering.

Here's a list that you can choose when to use between constructor and componentDidMount:
constructor
Do:

initialize state
bind event handlers

If you don't initialize a state and you don't bind methods, you don't need to implement the constructor.
Don't:
Avoid introducing any side-effects or subscriptions. Do not set state by using setState() in the constructor.
componentDidMount
Do:

initialization that requires DOM nodes
load data from a remote endpoint (where to instantiate the network request)
set up any subscriptions (don't forget to unsubscribe in componentWillUnmount())

You may also be interested to read the comment from the creator of react, Dan Abramov:

I won't like to wait for the component to be mounted to dispatch an ajax call to fulfill the component data dependencies. I would like to do it as soon as possible, like in the constructor, not even in componentWillMount.
If it's an async request, it won't be fulfilled by the time the component mounts anyway, regardless of where you fire it. This is because JS is single threaded, and the network request can't "come back" and be handled while we are still rendering. So the difference between firing it earlier and later is often negligible.
You're right that it matters in some rare cases though and for those cases it might make sense to break the recommendation. But you should be extra cautious as state can update before mounting, and if your data depends on state, you might have to refetch in that case. In other words: when in doubt, do it in componentDidMount.
The specific recommendation to avoid side effects in the constructor and Will* lifecycles is related to the changes we are making to allow rendering to be asynchronous and interruptible (in part to support use cases like this better). We are still figuring out the exact semantics of how it should work, so at the moment our recommendations are more conservative. As we use async rendering more in production we will provide a more specific guidance as to where to fire the requests without sacrificing either efficiency or correctness. But for now providing a clear migration path to async rendering (and thus being more conservative in our recommendations) is more important.

For further interest, you may also visit this post.
Comment: FYI, Dan Ambrov is not the creator of React. He created Redux.
Answer: getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
So If you want to perform some action just once, on before mount of component, then getDerivedStateFromProps is not appropriate option.
Use componentDidMount method.
Have more details in https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html
Answer: Use getDerivedStateFromProps() it's next method called after constructor.
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
Comment: This is not right choice. How would you perform some actions without receiving the props?
Comment: Just moving into `constructor` is not enough?
Answer: setState in a constructor will perform unnecessary computation, you can either use the state property as you suggest or this.state = { ... } in your constructor if you need to perform more computation or access props.
The React documentation recommends you use constructor (or a class property) over componentWillMount for initialising state. For side-effects (e.g. http request) that could update state you should consider componentDidMount or componentDidUpdate. With asynchronous state updates, you should always make sure that your component handles the state without that data.
Comment: No problem. These two approaches are very similar but `this.state =` in the constructor allows you to access props however initialising state from props can be dangerous https://medium.com/@justintulk/react-anti-patterns-props-in-initial-state-28687846cc2e.
Comment: Sorry, the code in the question was wrong! I wanna compare `this.state=` in constructor and `state=` as public props of the component.


isapi 3 - strip all query strings from domain and subpages

Question: I would like to know how to strip out all query strings, i.e.
domain.com/?a=123 -->> domain.com

And
domain.com/page.asp?b=456 -->> domain.com/page.asp

Comment: I've edited the formatting of your post a bit, but it is still rather unclear. Could you edit for additional clarity?
Answer: Robert, I guess this is the third time I reply to your issue:
RewriteEngine on
RewriteBase /

RewriteCond %{QUERY_STRING} .+
RewriteRule (.*) /$1? [NC,NS,R=301,L]

Believe me, I know that's a good rule, however we need to know other rules it may conflict with.


When am I ready for sunglasses?

Question: I keep finding a guy in various levels who wants to sell me sunglasses but he keeps telling me I am not ready. When will I be ready? What do they do?
Answer: The Sunglasses Vendor will start outfitting Mario once you have collected 30 shine sprites.
The Sunglasses darken all light on the screen (Duh!) and can be toggled on and off by talking to said Vendor. Once you enter the final level, he will start outfitting Mario with a shine-sprite tropical shirt as well.
More on Mario Wiki

(note the darkened screen)

When am I ready for sunglasses?


The integral problem: $\int_{0}^{16}\frac{dx}{\sqrt{x^2+9}-\sqrt{x}}$

Question: I have met this kind of problem today.in fact, I spent hours trying to solve this problem on its own. My method was just to calculate the indefinite integral. I looked at Wolfram Alpha after I failed. Wolfram couldn't evaluate this integral. I don't know the spesific reason.

The integral:
$$\int_{0}^{16}\frac{dx}{\sqrt{x^2+9}-\sqrt{x}}$$
Comment: @Szeto That was my first thought too, but unless I'm missing something, it doesn't work. You'd really need $\sqrt{x^2 + 9} - x$ on the denomintor instead.
Comment: The inverse symbolic calculator's interpretation of Wolfram Alpha's numerical result is $-\frac{3}{2}-\frac{9\pi}{7}+\frac{47e}{14}$. The $e$ dependence looks implausible, which is unfortunate because I was hoping it would give us a clue.
Comment: @TheoBendit See Travis's answer. That's what I mean.
Comment: Rationalize it and seperate...
Comment: @Theo Bendit You are right.
Comment: Plugging it in to wolfram alpha gives me the numerical approximation http://www.wolframalpha.com/input/?i=integrate+1%2F(sqrt(9%2Bx%5E2)-sqrt(x))+from+x%3D0+to+x%3D16
Comment: You have met his problem where? In a textbook?
Answer: As observed in the comments, this would be much easier if $\sqrt{x}$ were replaced with $x$.
Nevertheless, we can still evaluate this integral by hand by rationalizing the denominator and splitting the integrand into two summands, giving:
$$\int \frac{\sqrt{x}}{x^2 - x + 9} dx + \int \frac{\sqrt{x^2 + 9}}{x^2 - x + 9} dx .$$
To evaluate the first integral, we can rationalize by reverse-substituting $x = u^2, dx = 2 u \,du$, giving
$$2 \int \frac{u^2}{u^4 - u^2 + 9}.$$
To rationalize the second integral, apply the Euler substitution $\sqrt{x^2 + 9} = x + t$ (or $x = \frac{9 - t^2}{2 t}$, $dx = -\frac{t^2 + 9}{t^2}$), giving
$$-\int \frac{(u^2 + 1)^2 \,du}{u (u^4 + 2 u^3 + 18 u^2 - 18 u + 81)} .$$
We've now reduced the problem to evaluating two integrals of rational functions, so we can in principle apply the method of partial fractions. Generically the quartics appearing in the denominators might mean an awful mess, but those appearing here both factor into quadratics over $\Bbb Q[\sqrt{7}]$ (this just means that we can write the real partial fractions decomposition using only rational numbers and $\sqrt{7}$.) The radicals in the coefficients make this factorization and the subsequent integration ugly, but as soon as we have the quadratic factors of the quartics, the rest of the problem is procedurally routine.
The antiderivative is long and unenlightening, so I won't reproduce here, but Maple finds for the definite integral the closed-form expression $$\tiny-\frac{1}{\sqrt{5}}\arctan \left( 5\,{\frac {-221\,\sqrt {53}+371\,\sqrt {
5}}{91\,\sqrt {5}\sqrt {53}+22525}} \right) +\frac{\pi}{\sqrt{5}} -\frac{1}{\sqrt{7}}\ln  \left( {\frac {1}{166}}\,\sqrt {265}\sqrt {7}+{\frac {95
}{498}}\,\sqrt {7}+{\frac {35}{498}}\,\sqrt {265}+{\frac {19}{166}}
 \right) +\ln  \left( \frac{3}{-16+\sqrt {265}}
 \right) ,
$$ which should agree with the other answers here after some simplification.
Comment: That's exactly what I meant.
Comment: (+1) Thank you for answer. But if this integral indefinite , is it possible to find a closed-form expression?
Comment: @Math It will be, yes. tedious, but definitely possible.
Answer: According to Maple 18, the integral is equal to
\begin{align*}
&\frac15\arctan \left( \frac{\sqrt {5}}{5} \right) \sqrt {5}+\frac{1}{14}\sqrt {7} \ln  \left( \sqrt {7}+1 \right) -\frac{1}{14}\sqrt {7}\ln  \left( \sqrt {7}-1 \right) \\
&-\frac{1}{14}\sqrt {7}\ln  \left( \sqrt {5}\sqrt {7}\sqrt {53}+19 \right) +\frac{1}{14}\sqrt {7}\ln  \left( \sqrt {5}\sqrt {7}\sqrt {53}-19 \right) \\
&+\frac{1}{5}\sqrt {5}\arctan \left( {\frac {13\,\sqrt {53}}{265}} \right)
+\frac{1}{5}\sqrt {5}\arctan \left( \frac85\sqrt {5}-\frac{1}{5}\sqrt {7}\sqrt {5} \right) \\
&+\frac{1}{5}\sqrt {5}\arctan \left( \frac85\sqrt {5}+\frac{1}{5} \sqrt {7}\sqrt {5} \right)+\frac{1}{14}\sqrt {7}\ln  \left( 19-4\,\sqrt {7} \right) \\
&-\frac{1}{14}\sqrt {7}\ln  \left( 19+4\,\sqrt {7} \right) +\ln \left( 3 \right) -\ln  \left( -16+\sqrt {5}\sqrt {53} \right).
\end{align*}
Enjoy.
Comment: :):):):):):) (+1)
Comment: Did you see J.G.'s comment?
Comment: I did, but this wasn't inverse symbolically calculated. This was Maple working it out analytically. It took longer than most integral computations too.
Comment: @Zacky If you can fit this answer into a comment, be my guest!
Comment: @Math This answer is much more plausible than the one I got from the ISC. If someone with maple 16 access change the $16$ to several other values, they can probably spot an antiderivative, then prove it's right just by differeniating.
Comment: @J.G. Is this answer a closed form?
Comment: @math this is a closed answer


VBScript: Function visibility inside a Class with identical property name

Question: Given that we have a script
Option Explicit

Class CClass
    Private m_date

    Private Sub Class_Initialize()
        m_date = CDate("1970-01-01 00:00:00")
    End Sub

    Public Function Foo()
        Dim d : d = Date()
        WScript.Echo "d is " & FormatDateTime(d, vbGeneralDate)
    End Function

    Public Property Get Date()
        Date = m_date
    End Property

    Public Property Let Date(p_date)
        m_date = CDate(p_date)
    End Property

End Class

Dim obj : Set obj = NEW CClass
Call obj.Foo()

How can class function CClass.Foo() call built-in VBScript function Date() without the property CClass.Date interfering?
My current solution is to introduce a dummy Date_() function which can be called instead. But that just seems wrong. I'm thinking there should be some way to specify that we want to call something outside the class scope.
Answer: I am almost positive that there is no way to do what you're asking in VBScript.
But even if you could figure out a way to do this, you really shouldn't. You need to choose names for your own functions that don't conflict with the names of built-in functions. Anything else is completely unmaintainable for a dynamic scripting language like VBScript.
Pick a different name for your Date property. Preferably something more descriptive: what kind of date does that property return? What does the date refer to? How is it likely to be used? Whatever you do, don't rename it to Date_—that's not any better.
Comment: I'm sure you're right on that it'll never work. What comes to property naming, I didn't want to repeat the name of the class in the property: e.g. class is CEvent, property is EventDate; seemed redundant at best. What you suggest seems reasonable, though. Maybe I should just endure it. I'll give some time to others to raise opinnions and mark you accepted, if nothing relevant turns up.
Comment: @msk: If that's the case, I would definitely go for `EventDate`. (Or something even more descriptive, like `ScheduledDate`.) You're trading a tiny bit of redundancy for clarity, as well as eliminating the possibility of hiding built-in methods. If the typing really bothers you, my best suggestion is to find an old copy of VB 6 and take advantage of its IntelliSense (auto-completion) functionality. It works just as well for VBScript code, even if you never use the compiler.
Answer: You can call it from inside the class like:
Dim d : d = me.Date()
Me in VBScript is the same as you use This in Javascript for example
Comment: I think you misunderstood. I definitely didn't want to call the class property.
Comment: Ah, OK. Yes, I misunderstood. You can do dirty hacks with the ExecuteGlobal() statement and global variables. Or passthru-functions outside your class that just pass the result from Date(), but it won't get more beautiful. So, I have to agree with Cody Gray.
Answer: Too late to the party, but there is a solution using eval function.
see eval function docs for details
Class CClass
    Private m_date

    Private Sub Class_Initialize()
        m_date = CDate("1970-01-01 00:00:00")
    End Sub

    Public Function Foo()
        Dim d : d = eval("Date()")
        WScript.Echo "d is " & FormatDateTime(d, vbGeneralDate)
    End Function

    Public Property Get Date()
        Date = m_date
    End Property

    Public Property Let Date(p_date)
        m_date = CDate(p_date)
    End Property

End Class

Dim obj : Set obj = NEW CClass
Call obj.Foo()


Scrapy upload pdf files to specific form(id) using FormRequest.from_response

Question: I'm trying to upload pdf files to a website(Flask server) where the forms ids are the filenames
Example of a form with id = 1, so i need to upload the 'arquivos/1.pdf' to it, I'm trying to use the scrapy.FormRequest.from_response but when i try adding the multipart/form-data as Content-Type header the server doesn't find or receive the file.
<title>Upload 1 new File</title>

Upload 1 new File

    <form id=1 action="" method=post enctype=multipart/form-data>

<input type=file name=file>
        <input type=submit value=Upload>
    </form>

Scrapy code
filename = '../arquivos/%s.pdf' % 1

with open(filename, mode='rb') as file:
                yield scrapy.FormRequest.from_response(response, formid=1, formdata={'file': file, }, headers={'Content-Type': 'multipart/form-data'})

Flask Server Snippet
if request.method == 'POST':
        print(request.headers)

        print(request.files['file'])
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('index'))

When i execute the Scrapy spider my server log gives
Answer: That functionality is still in PR, and I couldn't find any reference to multi part form data in the existing Scrapy docs, which matches your experience.
Feel free to vote for that issue, but otherwise you'll have to generate the request by hand, assuming Scrapy will allow posting a "raw" request body :-(
Comment: I've decided to use selenium instead it's a bit slower but got the job done, thanks for the reply.


How can I fix this error in a web template

Question: I just installed a new theme, now I am having a problem. Whenever a customer checks out, the following error is displayed:

Notice: Error: Could not load template
  C:\xampp\htdocs\nowahala/catalog/view/theme/default/template/checkout/simplecheckout_shipping.tpl!
  in
  C:\xampp\htdocs\nowahala\vqmod\vqcache\vq2-system_engine_controller.php
  on line 75

How do i fix it?
Answer: The simple answer is add the file. The error is pretty simple to understand. The template file is missing from your simple checkout. Open the modification and load the files into there (notice that it is the default folder)
Comment: I have searched the all the folders, no such file named simplecheckout_shipping.tpl, and if i create a blank template file, it shows a blank page on the front end
Comment: Correct, you need to add the file from the simple checkout mod that you installed previously into your default template's folders (or copy it from your custom theme folder if you moved it into there)
Comment: Hi Jay Gilford, there is no such file in either the module folder or even my theme folder
Comment: Contact the developer of SimpleCheckout. They will be able to tell you where the file is (may even be missing in the latest release)
Comment: ok, thanks for your help Jay Gildord, please i dont know how to contact him, do you know his email address? if yes, pls send it to me, thanks
Comment: Find the extension in your opencart account's order history section, and it will give you should be able to view the extension page from that. Send him a message in the comment section of the extension page


Bertini theorem - composite with a pencil

Question: Let $X$ be a smooth projective surface over the field of complex numbers. Suppose $L$ is a base point free line bundle such that the dimension of $H^0(X,L)$ is two. The Bertini's theorem says that a general element is not necessarily irreducible. Can anyone give me some examples where the general element of  the curve is reducible. I would like to know an example especially when $X$ is a K3 surface.
More generally if $|L|$ is composite with a pencil, is there a criteria as to when general element of the linear system reducible?
Comment: I am not sure I understand. If you take $X=\mathbb{P}^1\times C$ where $C$ is a smooth projective curve and $L$ is the pull back of $O(1)$ from $\mathbb{P}^1$, then $H^0(X,L)$ has dimension 2, it is base point free and all members are irreducible.
Comment: @Mohan, I am sorry. My question is wrong . I will rewrite it.
Answer: Bertini theorem says, in particular, that a general element  of a pencil is smooth away from the base locus. Then a general element of a pencil without base points is reducible if it is not connected.
Choose elliptic curves $E_1$ and $E_2$ and let $S = E_1\times E_2$. We have that $E_1$ has a $2$-fold covering $\pi \colon E_1 \rightarrow \mathbb{P}^1$. Then consider the  map $\sigma = \pi\circ pr_1 \colon S \rightarrow \mathbb{P}^1$ i.e. $\sigma(x,y) = \pi(x)$.
Therefore you can choose $L = \sigma^\ast \mathcal{O}_{\mathbb{P}^1}(1)$. A general element of $|L|$ is given by two copies of $E_2$.
I would like to point out Dino Festi notes on elliptic $K3$ surfaces as I think the OP may be interested.


CSS issues in IE only

Question: I've a page: http://volumee.dk/
everything is aligned to the left in IE only - what is the reason??
Answer: Your page is using Quirks Mode, which causes IE to pretend to be IE5.5.
The reason this is happening to you is detailed here: divs appearing different on different browsers

The reason you're getting Quirks Mode
  is the two UTF-8 byte order
  marks
  at the start of your file:
ef bb bf ef bb bf 3c 21 44 4f 43
.  .  .  .  .  .  <  !  D  O  C

You'll need to save your file without
  this. It should be an option in
  whatever editor you're using.
Comment: Last version of header.php was sabed using Notepad... can this be a reason?
Comment: Try using [Notepad++](http://notepad-plus-plus.org/) and on the "Encoding" menu pick "Encode in UTF-8 without BOM", then save your file. And listen to @songdogtech - you need to check multiple files. There are probably two files with this problem.
Comment: THANKS! I've saved it without "BOM" and it's Ok now :)
Answer: 1) Change the text encoding of index.php - and probably other theme files - to Unicode no-BOM. "The Unicode Byte-Order Mark (BOM) in UTF-8 encoded files is known to cause problems for some text editors and older browsers. You may want to consider avoiding its use until it is better supported."
2) Fix the code errors - the table errors are the most important - as those will give display problems in some browsers, like IE.[Invalid] Markup Validation of  volumee.dk  - W3C Markup Validator. Scroll down in the validation report to see line numbers and source code.
3) Try not to use a meta tag like <meta http-equiv="X-UA-Compatible" content="IE=edge" /> and get your site to mostly valid xhtml and css for best results in all browsers.
Answer: Add this to your header:
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
it might help, it makes newer versions of IE use their most up-to-date rendering capabilities.

CSS issues in IE only


Google-cloud + Node, grpc error

Question: I am creating a sample desktop application using electron framework. When i include google-cloud node library in application i got this error.

Uncaught Error:
  /home/user/Desktop/projects/sample_desktop_app/node_modules/grpc/src/node/extension_binary/grpc_node.node:
  undefined symbol: GENERAL_NAME_free

OS: Ubuntu
Node Version: v7.10.0
Your help would be appreciated
Answer: Grpc id a native module that also is not officially supported for electron. This is because native modules are generally hard with electron as they need special treatment or recompilation for the respective platform.
Best way is to follow this thread https://github.com/grpc/grpc/issues/6138 but you are more or less on your own with it. I would try to have your own backend and proxy grpc calls.

Google-cloud + Node, grpc error


Installing Lubuntu 12.04 on a Mac G4 Powerbook

Question: I recently got 3 powerbooks from a friend of mine, only one of which I intend on using. I installed Lubuntu dual boot with OSX and restarted. When the Powerbook restarts, I hear the beep, and then I see a gray screen with a box in the middle that has a question mark in it. One second later, the box changes to the finder icon, and OSX boots up.
Can anyone tell me what I need to do to boot to Lubuntu and restore the Grub menu? (I assume that is what Lubuntu uses, I use Ubuntu for my main computer so I am unfamiliar with other ubuntu distros.)
The Powerbook I am using,
PowerBook G4 2004 15" aluminum
1.33 GHz PowerPC CPU
512 MB SDRAM (Will add more soon)
OSX: 10.3.9
Lubuntu 12.04 PowerPC version
Answer: On PowerPC processor, the bootloader used by Linux is Yaboot, regardless of the distro. Same for Ubuntu and all *buntus. See  http://en.wikipedia.org/wiki/Yaboot. So it is the yaboot menu that is not showing up yet.
I don't know why yet, because I am just learning how myself.
See https://wiki.ubuntu.com/PowerPCFAQ#What_do_I_need_to_know_for_dual-booting.3F


get timezone of Google Calendar via Google Calendar API

Question: I'm using the Google Calendar API to insert events in my customers Google Calendars. I want to insert events in the timezone of their calendar but currently I can only use one timezone via the Google Calendar API.
How can I get the timezone of a specific Google Calendar using the Google Calendar API?
By now I'm using the following code to add an event to a Google Calendar:
$eventName='You have ListingAppointments.com Appointment';
$Address='testing-456';
$email@example.com';

if ($client->getAccessToken()) {
    $_SESSION['token'] = $client->getAccessToken();
    //print_r($events);
    $event = new Google_Event();
    $event->setSummary($eventName);
    $event->setLocation('testing234');

    $start = new Google_EventDateTime();
    $start->setDateTime('2013-07-19T10:25:00.000-07:00');
    //print_r($start);
    $event->setStart($start);

    $end = new Google_EventDateTime('2013-07-19T10:25:00.000-07:00');
    $end->setDateTime($end);
    //print_r($end);
    $event->setEnd($end);
    $attendee1 = new Google_EventAttendee();
    $attendee1->setEmail($Ausers);
    $attendees = array($attendee1);
    $event->attendees = $attendees;
    $createdEvent = $cal->events->insert('primary', $event);
    print_r($createdEvent);
}

Answer: Give this code a try:-$calendar = $cal->calendars->get('primary');echo $calendar->getTimeZone();
line one gets you the primary calendar and line  two gets you the timezone using getTimeZone() method.
or simply $cal->calendars->get('primary')->getTimezone();
Comment: getting this error  Call to a member function getTimezone() on a non-object in /home/content/70/8448970/html/test.com/wp-content/themes/renegade/google_calendar.php on line 199
Comment: try this `$cal->calendars->get('primary')->getTimezone();`
Comment: are you setting up the client library correctly? try setting up the library again, i guess you might be missing something there. check the link https://developers.google.com/google-apps/calendar/setup
Comment: I am including following files require_once 'google/Google_Client.php';
require_once 'google/contrib/Google_CalendarService.php';
Comment: I have checked files both library files does not exist. Can you please send me the library link in which apiclient.php  and  apiCalendarService.php exist ?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/33858/discussion-between-user1734190-and-karanbir-singh)


SQL query - attempting to display results based on certain conditions using AND/OR and JOINS

Question: Attempting to display all proposals in the system as long as they satisfy the following conditions:

the source must be supervisor
the status_code in the record table must not be 8 or 3

I have attempted a number of way in trying to make this work but I keep getting different data back which is not what I want.
The problem is how the tables have been set up. In theory a proposal can be applied for by a student and if that happens a record is automatically added to the 'record' table with a status set to '6' for pending. This status is then changed a number of times throughout the application process.
What I need is to show the users all proposals which have not been taken. The status codes to indicate this is '3' (accepted by a student so another student cannot take it) and '8' (not available).
NOTE: not all proposals may have a record in this table (a student has not applied for them)
This is the query so far which satisfies the first condition of being a "supervisor"
SELECT p.proposal_id, p.proposal_title,
p.description, u.user_record_id, u.forename,
u.surname, c.course_title, r.*,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags
FROM proposal p
      LEFT JOIN user u on u.user_record_id = p.user_record_id
      LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
      LEFT JOIN tag_details t on t.tag_code = pt.tag_code
      LEFT JOIN course_details c on c.course_code = p.course_code
      LEFT JOIN record r on r.proposal_id = p.proposal_id
      WHERE p.source = "Supervisor"
      GROUP BY p.proposal_id

My attempt at getting it to display all records which are available:
SELECT p.proposal_id, p.proposal_title,
p.description, u.user_record_id, u.forename,
u.surname, c.course_title, r.*,
GROUP_CONCAT(DISTINCT t.tag_title) AS tags
FROM proposal p
      LEFT JOIN user u on u.user_record_id = p.user_record_id
      LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
      LEFT JOIN tag_details t on t.tag_code = pt.tag_code
      LEFT JOIN course_details c on c.course_code = p.course_code
      LEFT JOIN record r on r.proposal_id = p.proposal_id
      WHERE p.source = "Supervisor"
      AND (r.status_code != 3 OR r.status_code !=8)
      GROUP BY p.proposal_id

The above query still returns proposals with the status code 3 and it fails to display any proposals which have yet not been applied for.
SQLFiddle Generated: http://sqlfiddle.com/#!9/b89a9/1/0
Any help would be much appreciated guys! Thank you.
Comment: Try changing "AND (r.status_code != 3 OR r.status_code !=8)" to "AND (r.status_code not in (3,8) )
Comment: `3 != 3 => false`, `3 != 8 => true`, so `false OR true` is `true`
Comment: @dbinns66 that does successfully return those with status codes that are not 3 or 8 but how would i return all the proposals which do not have status codes since they have not been applied for and therefore are available
Comment: @RoyalBg how would that fit into the current query. thanks
Comment: @user610 - not sure I follow, NULL would not be 3 or 8 and since you're doing LEFT JOIN it should return records with r.status being NULL - can you put together an sqlfiddle for this with create's and data?
Comment: @dbinns66 i have removed all the other tables which are in the main query because they're not needed for this specific bit. here is the sqlfiddle http://sqlfiddle.com/#!9/b89a9/1/0 as you can see it only returns those proposals which have status' which are not 3 or 8. does not return those which do not have a record. In total i have 7 proposals in the table. 1 which is unavailable and 1 which is source "student" so it should display 5 but displays 3. hope you can help!
Comment: @user610 - you have 7 records in proposal, 1 is source Student (now 6), 2 have status of 3 or 8 (now 4) and one which is unavailable (now 3) ... the query returns 3 rows... again, not sure I understand what the issue is, you don't have any proposals that don't have a `record` record...
Comment: @dbinns66. Thanks for looking. the one proposal which has a status of 3 or 8 is the same proposal so that would be classed as 1 proposal since its the same. it should return proposal id 3 and 6 also since that does not have a record in the table.
Comment: @dbinns66 summary: I have 7 records in proposal, 1 is source Student (now 6), 1 has a status of 3 or 8 (now 5). 2 which do not have a row in record (proposal id 3 and 6) and 3 which are in record (proposal id 2,5 and 51)
Answer: Turned out I was missing a OR statement to achieve my goal.
To get the end result i needed, the query was modified to:
SELECT p.proposal_id, p.proposal_title, p.description, u.user_record_id, u.forename, u.surname, c.course_title, r.*, GROUP_CONCAT(DISTINCT t.tag_title) AS tags FROM proposal p
      LEFT JOIN user u on u.user_record_id = p.user_record_id
      LEFT JOIN proposal_tags pt on pt.proposal_id = p.proposal_id
      LEFT JOIN tag_details t on t.tag_code = pt.tag_code
      LEFT JOIN course_details c on c.course_code = p.course_code
      LEFT JOIN record r on r.proposal_id = p.proposal_id
      WHERE p.source = "Supervisor"
      AND (r.status_code not in (3,8) OR r.status_code IS NULL)
      GROUP BY p.proposal_id

Successfully brings back all proposals which are available, are from the supervisor and those which have no record in the 'record' table.
Thank you to everyone who helped


How do I delete the blue gnome wallpaper from my wallpaper selection in prefs?

Question: I just got rid of adwaita theme in my ubuntu install, but the blue striped wallpaper is still there, how do I find it and remove it manually or run command in terminal to delete it?
Answer: You should delete the folder /usr/share/themes/Adwaita with either this command in a terminal:
sudo rm -r /usr/share/themes/Adwaita/
or press Alt+F2, enter gksu nautilus /usr/share/themes and your password when asked, select the folder "Adwaita" and press Shift+Del.


translating a let as lambda

Question: From page 69 of R⁷RS I know what I can substitute a let with a lambda:
(let (a 10) something)
; is equivalent to
(lambda (a) something) 10

So I took this (from SICP):
(define new-withdraw
  (let ((balance 100))
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))))

and translated it to:
(define w-lam
  (lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds")) 100))

but the behaviour in the REPL is different:
(new-withdraw 80)

;Value: 20

(w-lam 80)

;Value: 100

What am I missing?
Comment: You misread the macro expansion; it is `(let (x e) body) --> ((lambda (x) body) e)`
Answer: Equivalent of
(let ((a 10)) something)
; With 2 pairs of parenthesis, but I take that is a typo

isn't
(lambda (a) something) 10

But
((lambda (a) something) 10)

(lambda (a) something) 10 isn't a valid construct anyway. It is 2, unrelated valid constructs (and, depending on the context, it may be legal or not to have two constructs one after the other). It is first a function, that does something in a context where a is a parameter. And then, a number, 10. You don't want a function that evaluate something. You want to actually evaluate something. So you need to call that function.
(lambda (a) something) 10 is like print; 10; in an imperative language. It means nothing. It is just a function (print) and then a number. Without connections. It happens to be legal, but void, in many languages. The function is not called. It is just a value (that happens to be a function). Which is ignored, since we do nothing with it.
((lambda (a) something) 10) on the other hand calls that function with parameter 10. Like print(10); in my analogy.
So, equivalent of
(let ((balance 100))
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds")))

is

((lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))) 100)

tl-dr: here is the working code
Or, enclosed in your define w-lam
(define w-lam
  ((lambda (balance)
    (lambda (amount)
      (if (>= balance amount)
          (begin (set! balance (- balance amount))
                 balance)
          "Insufficient funds"))) 100))

Note that the equivalent let/lambda isn't just black magic. You don't need to find "formulas" in textbook for that. It is just logic.
(let ((a 10)) something)

Means that we create a new environment, in which symbol a is associated to value 10. And in this environment, something is evaluated
(lambda (a) something)

is a function that evaluate something, in a local environment in which a is the parameter passed to that function.
And, as you know
(f 10)

Calls function f with parameter 10.
So, just replace f by previous function (lambda (a) something).
And you get
((lambda (a) something) 10)

Which calls (lambda (a) something) with 1st parameter being 10.
And we know that calling this function means evaluating something in an environment where a is the 1st parameter passed, that is, here, 10.
If you are more familiar with more imperative languages, it just a replacing
{ // New block
    int a=10;
    printf("%d\n", a)
}

By
void f(int a){
    printf("%d\n", a);
}
f(10);

Or, in javascript (which has closer to scheme constructs)
{
    let a=10;
    console.log(a);
}

by
(function (a){
    console.log(a);
})(10);

Or
((a)=>console.log(a))(10)

Which is something people really do in javascript to create local environments.
So, it is just using parameters of a lambda (or anonymous functions in my analogies) as a local environment, and calling that function immediately with values we want to set in this local environment.

translating a let as lambda


How to check if a condition in foreach function matched in Javascript?

Question: I have a Javascript function.
I check a condition for every element in an array and if there is a match, I stop the loop.
For example:
var myarray = [5,6,7,8,9,10];
myarray.forEach(function(element){
  if(element == 8)
    break;
});

//myother functions here..

Everything seems okay so far. But after breaking the loop, my other functions continues to run.
If a match happens in foreach function, i don't want to continue to next functions, if nothing match it can continue.
How can I do this?
Comment: Your other functions are called outside the loop? The break only breaks out of the loop and doesn't continue to check the rest of the array elements.
Comment: Yes, my other functions are outside the loop. I want to stop them if a condition matches in loop.
Comment: If @Jameson 's answer wasn't the case post the full code
Comment: *"Everything seems okay so far. But after breaking the loop"* - The `break` statement doesn't exit a `.forEach()` loop, and the code shown would give an error.
Answer: For example you could use (version without functions)
var myarray = [5,6,7,8,9,10];
var found = false;
myarray.forEach(function(element){
  if(element == 8)
    found = true;
});

if (!found) {
  //myother functions here..
}

Or if you are just looking for a single element
if (myarray.indexOf(8) == -1) {
  //myother functions here..
}


Can't install NME from source

Question: <code>$ haxelib list
format: [3.0.2]
hxcpp: [3.0.2]
nme: [dev:C:\Users\NME/]
nmedev: [dev:C:\Users\nmedev/]
svg: [1.0.7]
swf: [1.0.0]

$ nme
Error: Library nme version dev is not installed
</code>
Anyone run into this? Everything is up to date.
Answer: https://code.google.com/p/haxe/issues/detail?id=1853
"Editing the file manually and removing the trailing slash resolves the problem"
Edit the .dev file inside the lib that's giving you the problem.
IE C:\Program Files (x86)\HaxeFoundation\haxe\lib\nme.dev
was C:\some\path\NME/
edit to C:\some\path\NME

Can't install NME from source


Array/Hash strange behaviour

Question: I have performed the following test:
irb(main):023:0> a=[]
=> []

irb(main):024:0> b="1"
=> "1"

irb(main):025:0> a.push(b)
=> ["1"]

irb(main):026:0> a
=> ["1"]

irb(main):027:0> b="2"
=> "2"

irb(main):028:0> a
=> ["1"]

So far so good. Now, but as soon as I change b into a hash:
irb(main):012:0> a=[]
=> []
irb(main):013:0> b={}
=> {}
irb(main):014:0> b[:file]="one"
=> "one"
irb(main):015:0> a.push(b)
=> [{:file=>"one"}]
irb(main):016:0> a
=> [{:file=>"one"}]
irb(main):017:0> b[:file]="two"
=> "two"
irb(main):018:0> a
**=> [{:file=>"two"}]**

I didn't even push the b value into the a array. What happened here?
Answer: b is not a hash. It is a reference to a hash. And pushing a reference somewhere else won't make it point to a new instance.
Copy your hashes explicitly where you want to, using b.dup.
Sometimes even that might not be enough, as the same applies to values inside a hash: the new hash will have the same references inside, it's a so-called "shallow copy".
(Here I was claiming that strings are immutable in Ruby, but @BroiSatse pointed out that it's not true, and he's right, follow the link in the comments.)
Regardless, the explaination is similar: assignment of a new string into a variable produces a new reference to a string (doesn't mutate existing one), writing a new value into a hash doesn't produce a new hash reference (mutates existing hash instead).
Comment: I know that it is a reference but why Hash becomes a reference and String does not
Comment: @D-side - Strings are so mutable!
Comment: @BroiSatse Um, yeah? Point me into the docs please, so I can be sure. Feel free to edit the answer as well.
Comment: @BroiSatse Nevermind, you are correct. Found evidence of otherwise. Deleting.
Comment: I can't delete an accepted answer, huh? Alright, I'll point that out shortly.
Answer: You need to understand how ruby variables and Arrays works. Variable holds a reference to the object, which means that if you do:
a = b = []

Both a and b are referencing exactly some object!
a << 1
b    #=> [1]

Array is nothing else but an object which holds many references at the same time. But again, they just reference objects, so if you do:
a = {}
b = [a]

Then b[0] and a variable are referencing to the same object.
a[:foo] = :bar
b    #=> [{:foo => :bar}]

Now the reason why it seemed to work differently in your first example is that assignment does not modify the object, but rather changes the reference itself.
a = []
b = '1'
a.push(b)

Now both a[0] and b are pointing to the very same object. However if you do:
b = '2'

You create a new string and changes the reference for variable b, but a[0] is still referencing the old string. However, if instead of changeng the reference you execute some modifying method:
b.replace('2')

You'll see it will give you:
a   #=> ['2']

Comment: @meso_2600 - You can even do `a = []; a.push(a)`.
Comment: So why this does not apply to the string?
Comment: It does, but you did not modify string, you've created a new string and assign it to the first variable. It does not modify the second variable, which still points to the previous string. Try using some string modifying methods, like `gsub!` or `replace` to see it applies there as well. I beleive it is explained in the answer, I'll try to reword it a little.
Comment: This one is good :)
irb(main):012:0> a=[]
=> []
irb(main):013:0> b=[]
=> []
irb(main):014:0> b.push("1")
=> ["1"]
irb(main):015:0> a.push(b)
=> [["1"]]
irb(main):016:0> b.push(a)
=> ["1", [[...]]]
irb(main):017:0> a
=> [["1", [...]]]
irb(main):018:0> b
=> ["1", [[...]]]

Array/Hash strange behaviour


Iterating over a string in Vimscript or Parse a JSON file

Question: So I'm creating a vim script that needs to load and parse a JSON file into a local object graph.  I searched and I couldn't find any native way to process a JSON file, and I don't want to add any dependencies to the script.  So I wrote my own function to parse the JSON string (gotten from the file), but it's really slow.  At the moment, I iterate through each character in the file like so:
let len = strlen(jsonString) - 1
let i = 0
while i < len
    let c = strpart(jsonString, i, 1)
    let i += 1
    " A lot of code to process file....
    " Note: I've tried short cutting the process by searching for enclosing double-quotes when I come across the initial double quotes (also taking into account escaping '\' character.  It doesn't help
endwhile

I've also tried this method:
for c in split(jsonString, '\zs')
    " Do a lot of parsing ....
endfor

For reference, a file with ~29,000 characters takes about 4 seconds to process, which is unacceptable.
Is there a better way to iterate over a string in vim script?
Or better yet, have I missed a native function to parse JSON?
Update:
I asked for no dependencies because I:

Didn't want to deal with them
Genuinely wanted some ideas for best way to do this without someone else's work.
Sometimes I just like to do things manually even though the problem has already been solved.

I'm not against plugins or dependencies at all, it's just that I'm curious.  Thus the question.
I ended up creating my own function to parse the JSON file.  I was creating a script that could parse the package.json file associated with node.js modules.  Because of this, I could rely on a fairly consistent format and quit the processing whenever I'd retrieved the information I needed.  This usually cut out large chunks of the file since most developers put the largest chunk of the file, their "readme" section, at the end.  Because the package.json file is strictly defined, I left the process somewhat fragile.  It assumed a root dictionary { } and actively looks for certain entries. You can find the script here: https://github.com/ahayman/vim-nodejs-complete/blob/master/after/ftplugin/javascript.vim#L33.
Of course, this doesn't answer my own question.  It's only the solution to my unique problem.  I'll wait a few days for new answers and pick the best one before the bounty ends (already set an alarm on my phone).
Comment: Please search http://www.vim.org/scripts. There are several plugins that can do JSON parsing.
Answer: The simplest solution with the least dependencies is just using the json_decode vim function.
let dict = json_decode(jsonString)

Comment: It's important to note that that support was added in [vim8](https://github.com/vim/vim/blob/master/runtime/doc/version8.txt#L48-L50) (it also existed in Neovim way before that point).
Answer: Even though Vim's origin dates back a lot it happens that its internal string() eval() representation is that close to JSON that its likely to work unless you need special characters.
You can lookup the implementation here which even supports true/false/null if you want:
https://github.com/MarcWeber/vim-addon-json-encoding
Better use that library (vim-addon-manager allows to install dependencies easily).
Now it depends on your data whether this is good enough.
Now Benjamin Klein posted your question to vim_use which is why I'm replying.
Best and fast replies happen if you subscribe to the Vim mailinglist.
Goto vim.sf.net and follow the community link.
You cannot expect the Vim community to scrape stackoverflow.
I've added the keyword "json" and "parsing" to that little code that it can be found easier.
If this solution does not work for you you can try the many :h if_* bindings or write an external script which extracts the information you're looking for, or turns JSON into Vim's dictionary representation which can be read by eval() escaping special characters you care about correctly.
Comment: In VAM-kr we use this code:eval(join(readfile(file, 'b'), '')). In older Vim versions join is known to be slow, thus consider using system('cat file') instead if you're on a unix like environment. webapi supports parsing xml; github.com/mattn/webapi-vim.git
Comment: [webapi](github.com/mattn/webapi-vim.git) is using matchlist() and regular
expressions. On vim.sf.net there is a java lexer somewhere. But in the end
VimL is known to be slow, its the wrong tool if you have much data. I've painfully learned that a lot of times.
Comment: I am surprised that in your plugin you do not use existing solution for securing eval used in VAM. Also **do never use `==` for string comparison**. There is `==#` and `is#`. Funcrefs look nicer for special values (as they cannot possibly be encoded in JSON in any other way), why did you comment them?
Comment: `string(json_encoding#*())` calls at [line 47](https://github.com/MarcWeber/vim-addon-json-encoding/blob/master/autoload/json_encoding.vim#L47) and below are also good candidates for caching.
Comment: The correct place to put such "change requests" and "hints" is github, not a stack overflow comment
Answer: If you seek for completely correct solution omitting dependencies is one of the worst thing you can do. The eval() variant mentioned by @MarcWeber is one of the fastest, but it has its disadvantages:

Using solution for securing eval I mentioned in comment makes it no longer the fastest. In fact after you use this it makes eval() slower by more then an order of magnitude (0.02s vs 0.53s in my test).
It does not respect surrogate pairs.
It cannot be used to verify that you have correct JSON: it accepts some strings (e.g. "\<C-o>") that are not JSON strings and it allows trailing commas.
It fails to give normal error messages. It fails badly if you use vam#VerifyIsJSON I mentioned in p.1.
It fails to load floating point values like 1e10 (vim requires numbers to look like 1.0e10, but numbers like 1e10 are allowed: note "and/or" in the first paragraph).

. All of the above (except for the first) statements also apply to vim-addon-json-encoding mentioned by @MarcWeber because it uses eval. There are some other possibilities:

Fastest and the most correct is using python: pyeval('json.loads(vim.eval("varname"))'). Not faster then eval, but fastest among other possibilities. (0.04 in my test: approximately two times slower then eval())
Note that I use pyeval() here. If you want solution for vim version that lacks this functionality it will no longer be one of the fastest.

Use my json.vim plugin. It has an advantages of slightly better error reporting compared to failed vam#VerifyIsJSON, slightly worse compared to eval() and it correctly loads floating-point numbers. It can be used for verification of strings (it does not accept "\<C-a>"), but it loads lists with trailing comma just fine. It does not support surrogate pairs. It is also very slow: in the test I used (it uses 279702 character long strings) it takes 11.59s to load. Json.vim tries to use python if possible though.

For the best error reporting you can take yaml.vim and purge YAML support out of it leaving only JSON (I once have done the same thing for pyyaml, though in python: see markedjson library used in powerline: it is pyyaml minus YAML stuff plus classes with marks). But this variant is even slower then json.vim and should only be used if the main thing you need is error reporting: 207 seconds for loading the same 279702 character long string.

Note that the only variant mentioned that satisfies both requirements "no dependencies" and "no python" is eval(). If you are not fine with its disadvantages you have to throw away one or both of these requirements. Or copy-paste code. Though if you take speed into account only two candidates are left: eval() and python: if you want to parse json fast you really must use C and only these solutions spend most time in functions written in C.
Most other interpreters (ruby/perl/TCL) do not have pyeval() equivalent so they will be slower even if their JSON implementation is written in C. Some other (lua/racket (mzscheme)) have pyeval() equivalent, but e.g. luaeval('{}') is zero meaning that you will have to add additional step explicitly and recursively converting objects into vim dictionaries and lists (e.g. luaeval('vim.dict({})')) which will impact performance. Cannot say anything about mzeval(), but I have never heard about anybody actually using racket (mzscheme) with vim.


Starting with Selenium

Question: I am new in selenium and i learned the concept things in selenium but i haven't experience and proper knowledge that how to start automation of a web application. I need few tips so i can start the automation in a proper way like which framework to use.
it will be grateful help that someone provide me the guideline of start automation in selenium web driver through java. Below is the application link that i wanna start automation.
http://talentrack.in/
Please review the application and please suggest me to startup guidelines.
Thanks
Answer: i am answering this question as i had solved one query regarding this website.
So start your Automation scripting with sign-up page, filling the details of the form.
Page object model is very useful for this type of sites.
So basically create test cases with pom.xml i.e maven. and create everything by calling methods i.e. for every page create a different class and anything you do on that page, the method related to it should be in that class.
See the below example..
My test is
<code>//MAximize the Screen
driver.manage().window().maximize();
//Go to Gmail Login Page
SignInPage SignInPage = WebUtils.GoToSignInPage(driver);
//Sign in to Login page -Send Username
SignInPage.SendkeysMethodForSignInPAge(driver, By.cssSelector("input[id='Email']") , "email@example.com" );
//Click on Next
SignInPage.ClickToLogin(driver, By.cssSelector("input[id='next']"));
//Wait for password field to be visible
SignInPage.WaitForElementTobeVisible(driver, By.cssSelector("input[id='Passwd'][type='password']"));
</code>
So when i call the method SendkeysMethodForSignInPAge i wont write it in @Test.
See SendkeysMethodForSignInPAge method: public class SignInPage {
<code>public void SendkeysMethodForSignInPAge(WebDriver driver, By by, String s) {
WebUtils.Sendkeys(driver,by,s);
</code>
}
I created a new class and there i defined it. This is basic flow. Hope you can relate this. Now you create a common method Sendkeys(WebDriver driver, By by, String s ) in class WebUtils which will be used by each page object class here it will be called by SendkeysMethodForSignInPAge Method.
Reply to me, if your are still stuck. Happy Learning :-)
Comment: Thanks for providing such a wonderful help, i will start and will contact you if i am stuck anywhere. Really helpful. Thanks!
Comment: Yes anytime. Enjoy. :-)
Comment: @ Kishan, I am still stuck, can you please elevate in brief. Or u can give me an example of my website signup page. It will be very helpful for me
Comment: Where are you stuck ? Post it

Starting with Selenium


mod_rewrite PHP $_GET empty

Question: I have the following .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule api/(.*)$ api.php?m=$1 [QSA,NC,L]
</IfModule>

The URL rewriting works great.  I can go to http://myserver.com/api/example and it will behave as if I went to http://myserver.com/api.php?m=example.  The problem is that the PHP $_REQUEST and $_GET variables are empty.  Shouldn't I still be able to get the value of $_REQUEST['m']?
After some googling, I found a suggestion to disable MultiViews.  If I add Options -MultiViews, I get a 404 error.
What am I doing wrong?  Thank you.
Answer: Sounds like you don't have mod_rewrite enabled. Since it's not enabled, the IfModule container is ignored. See: How to enable mod_rewrite for Apache 2.2
You must turn off Multiviews in order for this to work, otherwise mod_negotiation is activated and will automatically map /api/ to /api.php without giving mod_rewrite a chance to do anything. So you need the line:
Options -MultiViews

If you can't enable mod_rewrite, you could alternatively change your api.php script so that it looks in the PATH_INFO variable:
$_SERVER['PATH_INFO']

to get the "example" part.
Comment: mod_rewrite is enabled.  I checked phpinfo() and used the function in_array('mod_rewrite',apache_get_modules()).  It is a shared server that I do not have administrative access to, if that matters.  Additionally, the rewrite is actually working - it's sending /api/example to /api.php?m=example.
Comment: Actually I take that back, MultiViews is making /api/whatever redirect to api.php...and then I'm losing the $_GET.  I moved the Options -MultiViews outside the IfModule and that worked.  I still do not understand why I got a 404 error when it was inside IfModule.
Comment: I accepted this as the answer because MultiViews was a part of the problem.  I also had to provide the full path to api.php.

mod_rewrite PHP $_GET empty


Luigi overwrite to S3

Question: I have a routine task to upload and share a dump on S3 bucket. While the code below works, for some reason it does not want to overwrite file.
From the docs, I need to
1) define solution for two parallel executions:
    path = luigi.Parameter(default=glob(DATA_DIR)[-2], batch_method=max)
2) add resources = {'overwrite_resource': 1}
While it works for the local files - it does not for the S3.
class report_to_S3(luigi.Task):
    client = S3Client()
    path = luigi.Parameter(default=glob(DATA_DIR)[-2], batch_method=max)
    local_dump_path = '../../../data/local_db_dump.csv'
    resources = {'overwrite_resource': 1}

    def requires(self):
        return upload_tweets(path=self.path)

    def output(self):
        self.s3_path = "s3://qclm-nyc-ct/dump/dump.csv"
        return S3Target(self.s3_path, client=self.client)

    def run(self):
        c = sqa.create_engine('postgresql:///qc_soc_media')
        df = pd.read_sql_query('SELECT id, user_id, timestamp, lat, lon, ct FROM tweets WHERE ct IS NOT NULL', c)
        N = len(df)
        df.to_csv(self.local_dump_path, index=None)
        self.client.put(self.local_dump_path, self.output().path,
                        headers={'Content-Type': 'application/csv'})
        send_S3_report(N)

if __name__ == '__main__':
    luigi.run(local_scheduler=True, main_task_cls=report_to_S3)

Answer: If the target specified in the output() method already exists, the run() method will not execute. You may want to work the timestamp into the filename, or create another sentinel/flag that indicates the work is done.
Comment: 'overwrite_resource' is just a technique for creating a resource that prevents multiple tasks from running at the same time- you could use any string there. (typically resources are limits on things like concurrent API connections, etc). If you don't want to work the timestamp into the filename, just create some other indicator to use in the output() method. The task will not run if the output already exists.
Comment: cool. I should also note that if you don't want to have any output target that is unique to your task run with params, you can write a custom complete() method for the task. (in case existence of your log file is not an atomic indicator of task success)
Comment: Thank you. Unfortunately, I don't want that. Original Luigi allows to overwrite this behavior using resources = {'overwrite_resource': 1} for the local targets, but it seems it does not work for the S3 bucket (a bug?)
Comment: Thanks, I made a log file as a target, it seems to work.
Comment: Thanks. In the end, It appeared to be a little bit more complex than I anticipated: I created an additional LocalTarget for the logfile as a class parameter, and then overwrote `complete` with checking if this localTarget exists.

The reason for this workaround is that I still need the `output()` to point other tasks to the correct data path (Duh)

Luigi overwrite to S3


API to read admin drive share settings

Question: i am looking for an API to read admin drive share settings. Could not find any reference to reading share settings via an API
Appreciate any help, thanks.
Answer: Google Drive apps can manage permissions and sharing settings of files. The Permissions collection provides apps the ability to read, update, and delete permissions for users, Google groups, Google Apps domains, and the public.
In addition to managing permissions through the API, apps can display a standard Google Drive sharing dialog to let users share files. Each permission in the Google Drive API has a role. A role defines what users can do with a file.
Every permission of a file or folder has a type. The type is the scope of the permission, and determines which users have a role. Permissions with types user and groups also have an emailAddress. Permissions with type domain have a corresponding domain property that specifies the domain name.
For additional information on manipulating permissions, see the reference guide.
Answer: Drive API v2 about.get() returns a domainSharingPolicy attribute which tells you if the user is allowed to share files outside their domain. So far Drive v3 does not have an equivalent.

API to read admin drive share settings


Must I completely remove tile adhesive before I paint my basement floor?

Question: My basement floor years ago had a tiled floor. Tiles were adhered with what looked like a black tar type adhesive. Tiles came loose and were removed. Even though the floor is smooth I am unable to get all the substance off the floor. Can this stuff be painted over or do I have to retire the floor. Prefer to paint if possible.
Comment: intuitively, if you can't remove it, neither would moderate traffic...
Comment: A lot of that "mastic" has asbestos in it, so sanding or grinding will only make it airborne.
Comment: Good point on making sure it doesn't have asbestos before grinding it away.
Answer: Rent a concrete floor grinder from a local tool rental. It should get rid of the majority of the adhesive and any other surface coatings. Then, you should be able to go through the normal process of proper concrete painting (make sure to read up on proper surface preparation for your selected product to ensure best adhesion and results).


Are compounding type [dis]advantages implemented?

Question: Based on the "super effective" and "not very effective" messages, it's obvious type [dis]advantages are implemented in Pokémon Go. However, I noticed immunities do not seem to be implemented (I hit a Pidgeot with the ground-type move Dig). Since originally posting this question, I've learned that the multipliers are different (1.25/0.8 vs the old 2/0.5), but still don't know about compounding [dis]advantages.
Do type [dis]advantages compound like in other Pokémon games, or is all [dis]advantage equal? E.g., will the damage Golbat (poison/flying) receives from a bug type attack be 0.8x, or will it be 0.64x? And will a Dragonite (dragon/flying) take 1.25x or 1.5625x damage from an ice type attack?
This answer claims that compounding [dis]advantages are not implemented, but my personal experience having a Golbat battle a much higher CP Pinsir made it feel as if they were (but that's hardly a confirmation).
Is there any information to indicate how thoroughly type [dis]advantages are implemented, since type immunities indicate this may differ from the games?
Comment: Damage taken x2 and Damage done x0.5 make it look like 1/4 without actually having it this way. You need to take that into account as well.
Answer: Coming back to this, I realized that the answer I linked to in my question has since been updated to answer my question as well. I'll echo @Joakim Isoaho's answer here:

Through testing on the subreddit /r/TheSilphRoad, the answers to 1 and
  2 are:

It uses a modified 6th Gen chart as evidenced by the Fairy and Steel
  types.
There are no 4x or 0x attacks, so Ground can hit Flying, and
  Normal can hit Ghost etc. -Values have been changed: -2x --> 1.25x
  -1/2x --> 0.85x As for 3, Same Type Attack Bonus (STAB) has been found in the game files to be 1.25x as well.

So, no, type [dis]advantages are not compounded. An Ice-type attack against a Dragonite (dragon/flying) gets the same bonus that it does against a Fearow (normal/flying).
Comment: so 4x --> 1.25x and 0.25x --> 0.8x?
Comment: @scenia Yes, that is correct.


What does the arrow in the bottom left corner do?

Question: When watching someone's drawing bring drawn, in the bottom of the drawing area (above the letters) there are two icons.
I know the one on the right, which looks like two arrows around each other, shuffles the letters around.
What does the one on the left do? It looks like a curved arrow pointing to the right, but I've not been able to notice any function. I thought it might be to redraw the opponent's drawing, or to skip to the final result, but it never seems to do anything when I press it, either while the drawing is in progress or when it's finished.
Answer: That arrow recalls all the letters that you've put down so far. So try guessing incorrectly, then pressing the button; all the letters will recall to the letter cache.
Comment: Not sure how I didn't notice that before...I'm going to go ahead and say it's because *my first guess is always correct.*


Activate target membership for a custom font in Xcode

Question: Searching for a reason why a custom font does not work can be really nerve racking!
One possible issue could be to not include the font in the target membership in Xcode
How do I include the custom font correctly?
Answer: You just need to select the font and select the target Membership checkmark for your app as seen in the picture.
Comment: What should we do if ticking the box is not available?
Comment: These controls may not be available. The problem is more hideous Apple UI: https://stackoverflow.com/questions/52958090/missing-target-membership-panel-in-xcode10


Spliting dataframe in 10 equal parts and merge 9 parts after picking one at a time in loop

Question: I need to split dataframe into 10 parts then use one part as  the testset and remaining 9 (merged to use as training set) , I have come up to the following code where I am able to split the dataset , and m trying to merge the remaining sets after picking one of those 10.
The first iteration goes fine , but I get following error in second iteration.
df = pd.DataFrame(np.random.randn(10, 4), index=list(xrange(10)))

for x in range(3):
    dfList = np.array_split(df, 3)
    testdf = dfList[x]
    dfList.remove(dfList[x])
    print testdf
    traindf = pd.concat(dfList)
    print traindf
    print "================================================"

Comment: Why not scikit-learn Cross Validation?  http://scikit-learn.org/stable/modules/cross_validation.html#random-permutations-cross-validation-a-k-a-shuffle-split
Comment: I am doing this as an assignment as a part of course and trying to implement validation.
Answer: I don't think you have to split the dataframe in 10 but just in 2.
I use this code for splitting a dataframe in training set and validation set:
test_index = np.random.choice(df.index, int(len(df.index)/10), replace=False)
test_df = df.loc[test_index]
train_df = df.loc[~df.index.isin(test_index)]
Comment: this is a much better solution
Comment: @Haleemur Ali ---  this is good if i need to just devide it once into 1:9 ------thats randomly selecting 1/10th as test set but, I am trying to implement k-fold validation , where as far as I understand :you break the data into K-blocks. Then, for K = 1 to X, you make the Kth block the test block and the rest of the data becomes the training data. Train, test, record and then update K.
Comment: You can split the dataframe index into chunks and loop through it. See http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python
Answer: You can use the permutation function from numpy.random
import numpy as np
import pandas as pd
import math as mt
l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
df = pd.DataFrame({'a': l, 'b': l})

shuffle the dataframe index
shuffled_idx = np.random.permutation(df.index)

divide the shuffled_index into N equal(ish) parts
for this example, let N = 4
N = 4
n = len(shuffled_idx) / N
parts = []
for j in range(N):
    parts.append(shuffled_idx[mt.ceil(j*n): mt.ceil(j*n+n)])

# to show each shuffled part of the data frame
for k in parts:
    print(df.iloc[k])

Answer: okay I got it working this way :
df = pd.DataFrame(np.random.randn(10, 4), index=list(xrange(10)))

dfList = np.array_split(df, 3)
for x in range(3):
    trainList = []
    for y in range(3):
        if y == x :
            testdf = dfList[y]
        else:
            trainList.append(dfList[y])
    traindf = pd.concat(trainList)
    print testdf
    print traindf
    print "================================================"

But better approach is welcome.
Answer: I wrote a piece of script find / fork it on github for the purpose of splitting a Pandas dataframe randomly. Here's a link to Pandas - Merge, join, and concatenate functionality!
Same code for your reference:
    import pandas as pd
    import numpy as np

    from xlwings import Sheet, Range, Workbook

    #path to file
    df = pd.read_excel(r"//PATH TO FILE//")

    df.columns = [c.replace(' ',"_") for c in df.columns]
    x = df.columns[0].encode("utf-8")

#number of parts the data frame or the list needs to be split into
    n = 7
    seq = list(df[x])
    np.random.shuffle(seq)
    lists1 = [seq[i:i+n] for i  in range(0, len(seq), n)]
    listsdf = pd.DataFrame(lists1).reset_index()

    dataframesDict = dict()

# calling xlwings workbook function

    Workbook()

    for i in range(0,n):

      if Sheet.count() < n:

         Sheet.add()

         doubles[i] =

           df.loc[df.Column_Name.isin(list(listsdf[listsdf.columns[i+1]]))]

         Range(i,"A1").value = doubles[i]

Answer: Looks like you are trying to do a k-fold type thing, rather than a one-off. This code should help. You may also find the SKLearn k-fold functionality works in your case, that's also worth checking out.
# Split dataframe by rows into n roughly equal portions and return list of
# them.
def splitDf(df, n) :
    splitPoints = list(map( lambda x: int(x*len(df)/n), (list(range(1,n)))))
    splits = list(np.split(df.sample(frac=1), splitPoints))
    return splits

# Take splits from splitDf, and return into test set (splits[index]) and training set (the rest)
def makeTrainAndTest(splits, index) :
   # index is zero based, so range 0-9 for 10 fold split
   test = splits[index]

   leftLst = splits[:index]
   rightLst = splits[index+1:]

   train = pd.concat(leftLst+rightLst)

   return train, test

You can then use these functions to make the folds
df = <my_total_data>
n = 10
splits = splitDf(df, n)
trainTest = []
for i in range(0,n) :
     trainTest.append(makeTrainAndTest(splits, i))

 # Get test set 2
 test2 = trainTest[2][1].shape

 # Get training set zero
 train0 = trainTest[0][0]


How to detect current gnome-terminal character encoding?

Question: I am trying to detect the current gnome-terminal character encoding from the command line. I have tried using gconftool :
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
current
$ gconftool-2 --type string --set /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8

But if I now go to the gnome-terminal menu and choose Terminal->Set Character Encoding->ISO-8859-10 and then run again
$ gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding
en_US.UTF-8

so the encoding in /apps/gnome-terminal/profiles/Default/encoding has not changed to ISO-8859-10 even though the terminal is using that encoding. So it seems gconftool cannot be used to determine the current encoding.
Comment: What is it you actually want to do? I'm asking because this sounds like an [XY problem](http://meta.stackexchange.com/q/66377/203101) and if you explain what your final objective is, there might be a better way.
Comment: @terdon Basically I have an application that should be run from gnome-terminal, but the application will only output UTF-8 encoded unicode to the terminal, therefore the application should warn the user if the terminal is not currently using UTF-8 encoding..
Comment: Ah, OK. Please [edit] your question and add that information. In that case, forget about `gnome-terminal`, you have no way of knowing if your user happens to be using it and that is only one of the many terminals available.
Comment: @terdon Actually the application only works in gnome-terminal.. It should not be used in any other terminals..
Comment: Um, OK. What a strange limitation. I guess your program's objective is to somehow modify gnome-terminal then, otherwise you are ignoring a huge subset of users. I doubt you'll find a way to detect the terminal's encoding. I would instead check for the user's language settings, something like `echo $LANG | grep utf8 || echo "problem!"`
Answer: I recommend checking locale charmap's output (which reports the values set by $LANG, $LC_CTYPE, $LC_ALL). This one does not directly query the terminal, but it's essential for most of the applications that the locale is set up correctly, consistently with the terminal. If it reports anything else than the actual behavior, not only your app but pretty much every other app will misbehave in the terminal, and it's not your fault. Of course the user can change the encoding from the menu, but if they decide to shoot themselves in the foot, there's not much you can/should do against. It's not your task to detect a faulty system-wide setting. Also there's no way for you to notice if the user switches encoding while your app is running, so I don't think there's much point in verifying it at startup.
If you really really need to check the runtime behavior, you can emit escape sequences that query the cursor position (and report it back in a certain format as if it's been typed from the keyboard), then emit some bytes that e.g. form a single character in UTF-8 while multiple characters in any other encoding (disabling local echo in the mean time, so keypresses by the user don't advance the cursor), and query the cursor position again. It's perhaps too much trouble and really not worth the effort.
Comment: What do you mean by `"checking locale charmap's output"`? Running `locale -m` displays all available charmaps..
Comment: Run the command `locale charmap` exactly as I've typed it, rather than `locale -m`. This prints you the locale your apps running inside the terminal will assume. If it's not set consistently with the charset chosen in the terminal, you're screwed anyways. (By the way this should be identical to that complicated perl one-liner.)
Comment: Yes this seems to work. Where are the locale keywords (like charmap, date_fmt, ..) defined?  I tried the man page and googling but no luck so far :)
Comment: Where have you found date_fmt then? :) I don't know where the keywords are _defined_, but it seems the ones recognized are the ones used in the definition files under /usr/share/i18n/locales (which are compiled into binary format to /usr/share/locale or /usr/share/locale-archive).
Answer: Here is a half-solution, addressing the problem of determining the encoding when  /apps/gnome-terminal/profiles/Default/encoding is equal to the string current. Assuming that the string current means that gnome-terminal should use the current locale.
It is tempting to check the LANG variable to determine the encoding, but according to this question, that is not reliable. Instead the Perl module I18N::Langinfo should be used:
temp=$(gconftool-2 --get /apps/gnome-terminal/profiles/Default/encoding)

if [[ $temp == "current" ]] ; then
    perl -MI18N::Langinfo=langinfo,CODESET -E 'say langinfo(CODESET())'
else
    echo $temp
fi

Note that this answer does not address the problem of determining the gnome-terminal encoding when the user manually changes the encoding from the gnome-terminal menu.
Comment: This solution also silently assumes that the user uses the Default profile.