How do I remove pooled paint on walls?

Question: I am renovating my first home and noticed in several rooms there are areas of what appear to be pooled paint. To me, it looks like someone applied too much paint and did not smooth it out before it dried. Here are some pictures:

I mainly noticed these closer to the ceiling.
Is this really just paint, or is it something else? What should I do before I repaint the walls to ensure this isn't visible and the wall is smooth? Is it enough to just sand down the "pooled" areas?
Comment: There's a word for those.  That is called a **"run"**.  If you talk to any paint person and say your paint has runs, they'll grok. It's from painting the paint too thick, probably from letting it get too thick in the roller tray or not following the instructions on your paint sprayer.
Comment: Thanks! Is there anything specific I should do to remove the runs before repainting? Do I just need to sand it down?
Comment: ligthly sanding it would be great - if it is very thick i would lightly scrape it. The important thing is to et a more even transition which is small enough for the new paint to cover it
Answer: I would suggest you gently sand it down and feather it out. Then you need to paint it. Do not oversand it as it will then show through the new paint.
Comment: Depending how thick the paint is, a light skim coat may help too.

How do I remove pooled paint on walls?


React: How to pass down context to a component generated on runtime

Question: I am trying to use the Modal for Android from mkonicek's gist https://gist.github.com/mkonicek/1a8bd7253e3257687228, it seems to show the modal properly, however it seems to crash when the child component accepts a context.
I'm assuming the reason is that the displayed component from the modal is not rendered using the render method so it does not pass the context information down.
Anyone knows how to pass down a context down to the rendered component inside the _createModal https://gist.github.com/mkonicek/1a8bd7253e3257687228#file-modal-js-L90 function ?
Thanks for the help!
Answer: Nevermind found a way to do it using a ContextWrapper found the solution with the ReactRouter https://github.com/rackt/react-router/issues/982


Recurrence $A(n,x)=p(x)A(n-1,x-1)+q(x)A(n-1,x)$

Question: What is the general approach to solving this recurrent equation given that $p(x)$ and $q(x)$ are not constant and do not depend on $n$ and $p(x)+q(x) \neq 1$. Please just give me some hints, don't solve it for me. I know this is similar to Binomial probability of $x$ successes in $n$ trials with a changing probability of success and solved using generating functions or z-transforms.
$p(x)$ can be seen as a probability of success after $n-1$ trials and $x-1$ successes and $q(x)$ as a probability of failure after $n-1$ trials and $x$ successes.
Comment: I think this may be a hard problem for general $p$ and $q$.  If $p$ and $q$ were to depend on $n$ as well as $x$ then the problem is open, even in the case of a linear dependency on $n$ and $x$; that case is research problem 6.94 in *Concrete Mathematics*.  If you give some more information about the specific $p$ and $q$ you're interested in you might have a better chance at a good answer.
Comment: OK< I looked it up in Woodbury(1949), Rutherford(1954) and Gani(2006), but still at loss. I think for constnt $p,q$ this is called Kolmogorov backward-forward equation
Comment: I mean yes, I can bound both $p$ and $q$, but this would be less interesting
Comment: $Mike: shouldn't it be some determinant of eigenmatrix or something?
Answer: Here is a probabilistic interpretation.
Let $r(x)=p(x)+q(x)$. Consider the random walk $(X_n)_{n\geqslant0}$ on the integer line which, when at $x$, stays at $x$ with probability $p(x)/r(x)$ and moves to $x-1$ with probability $q(x)/r(x)$. Then, writing $\mathbb E_x$ for the expectation when $X_0=x$, one has, for every $n\geqslant0$ and every $x$,
$$
\color{blue}{A(n,x)=\mathbb E_x\left(A(0,X_n)\cdot\prod\limits_{k=0}^{n-1}r(X_k)\right)}.
$$
Proof: If $X_0=x$ almost surely, the Markov chain $(X_{k+1})_{k\geqslant0}$ is distributed like  $(X_{k})_{k\geqslant0}$ for a random $X_0$ with distribution $r(x)^{-1}(p(x)\delta_x+q(x)\delta_{x-1})$. $\ \Box$
To go further, one could want to specify the initial condition $(A(0,x))_x$.
Answer: You didn't specify the initial conditions which is a big problem.  (And $x$ for an integer index is not a variable choice that makes me happy.) I will assume that $A(n,k)$ is zero if $k$ is negative or bigger than $n$. I will assume that the recurrence holds for all $n\ge1$ and all $x$.
Under this assumptions, let $A_k(z)=\sum\limits_{n=0}^{\infty}A(n,k)t^n$, convert the recurrence to a functional equation and this gives you a product formula for the generating function.
If you sum the recurrence, you get
$$A_k(t)=p(k)A_{k-1}(t)t+q(k)A_k(t)t,$$
so
$$A_k(t)=\frac{p(k)t}{1-q(k)t}A_{k-1}(t).$$
In particular, this works for binomial coefficients and Stirling numbers.
Comment: this sounds reasonable, but could you give a little bit more details on how to do this conversion. In Migdal(2010) the solution is in the form of the product of diagonal entries of the eigenmatrix


Xfce4 keybinding and logout randomly not working since Ubuntu 14.04

Question: I upgraded my ubuntu installation from 12.04 LTS to 14.04 LTS a few weeks ago.
Everything works fine except Xfce4.
Since the update, I'm sometimes unable to use my custom keybindings (like alt-F1 in order to open a terminal). It only happens after a reboot, not during a session.
When it happens, I have to force-reboot the whole computer, since I can't logout either. When I try to logout one time, nothing happens. When I try to logout another time, the message "Session manager must be in idle state when requesting a shutdown" appears.
I think some process is preventing xfce4 from login in/out. However, I tried to disable every autostart process (~/.config/autostart) and beside the fact it's faster, it doesn't solve anything.
Do you happen to have any information about that problem?
Thanks !

Configuration:

Ubuntu 14.04 LTS
Xfce4 4.10
Comment: Sounds like this http://askubuntu.com/questions/461203/keyboard-shortcuts-not-working-anymore-in-xfce
Comment: Looks similar, however I don't have a `.Xmodmap` file and the default keyboard shortcuts like `Alt+F4` are working fine.
Comment: I'm having exact same issue here. Looks like the whole "Logout" system is bugged in Ubuntu 14.04, as LXDE also randomly fails to logout.
Answer: I have the same problem, logout fails and loads of user gui processes still running after each failed logout.
I wouldn't normally use Xfce4, but rdp access is required and unity over rdp is currently broken in 14.04.
Looking forward to either of these issues getting fixed by the point release.  If I can be of any help or provide any more information please let me know.
Comment: Actually this may not be too much of an issue.  This is the 32bit version of 14.04 that was installed on a kvm virtual machine to provide support for legacy 32 bit gui apps that have difficulty running even when ia32-libs is installed.  I don't know if these issues occur on the 64 bit version.  I could therefore just run 12.04.4 32 bit instead as it is good until 2017.  By this time I would hope not to be running any 32 bit gui apps.  However the machine is not heavily used, so I will probably just continue to use Xfce4 and schedule a weekly reboot to clear the unwanted processes.
Comment: The only annoying thing is the UK keyboard mapping not working in Xfce4 on 14.04 32 bit, so need to type from memory of a US keyboard layout.  This is documented as a bug elsewhere.


How could I use my second laptop to extend my laptop's screen?

Question: I was wondering how I could create a dummy or fake monitor that I could use to extend my display. Then I wanted to use vnc to connect to the dummy screen with my other laptop. If someone has something easier or better please suggest it. I'm using normal unity Ubuntu 16.10 on both.
It's been done on windows as see here.
- https://youtu.be/W9gAlqCX5Lw
I've also tried xdmx but it didn't work for me. It would give me a "(Fatal Error) dmx: InitOutput: no back-end displays found" error after I ran xdmx :1
Comment: It can't be done would be my hypotheses.
Comment: why? It's been done with windows.
Comment: Interesting. *How* is it done with Windows? Can you please point to a link?
Comment: https://youtu.be/W9gAlqCX5Lw It's from 2015 and the guy used fedora to vnc into the windows pc.
Comment: I suggest you edit and add that to your question. And wait for answers.
Comment: It should be possible for you to use 'VNC' like in the youtube video clip, but between two Ubuntu computers. Once you have set it up, it would be rather convenient. - There is a rather old but I think good help page for Ubuntu with many links, https://help.ubuntu.com/community/VNC - There are also wikipedia pages, that can help you find alternatives or forks, for example 'TightVNC'. I used VNC very long ago, and I don't know which alternative is the best nowadays, but I think most of them work.
Answer: Check the laptop manufacturer information online. Most laptops only have their video card sources (HDMI, DVI, VGA, etc.) set to output only, but that is not always the case.
For the case of Ubuntu, if you can't use your laptop using those cables, a networked connection is possible. It seems that XDMX is the best possible route but it seems difficult to set up.
There is also Synergy, but that's not exactly the same thing. Synergy works by allowing use of one keyboard and mouse across multiple computers.
Comment: I got synergy working but that's not exactly what I wanted. I tried xdmx but it didn't work for me. It would give me a "(Fatal Error) dmx: InitOutput: no back-end displays found" error.
Comment: I don't have enough experience with xdmx to help. It just seemed like a worthwhile option.


How to understand this informal description of the levels of the arithmetical hierarchy?

Question: In my class notes I do not understand why the following statement is true, nor what it means:

Informally, the lowest level in the Arithmetical Hierarchy in which $n$-ary relation $R$ is definable determines how often we have to go through the natural numbers in their totality in order that we are guaranteed to have an answer to the questions: is $n$-tuple $n_0,\cdots,n_k$, in the relation $R$?

I would be most grateful if someone could explain what is meant here.
Comment: I tried to improve the title, but I feel that it can be improved a bit more. I'd be happy for a second opinion.
Answer: The "obvious" way to check whether a formula of the form $(\forall x)\,\phi(n,x)$ is true in the natural numbers, for specified $n$, is to check all the possible values of $x$, one after the other, and see whether they make $\phi(n,x)$ true.  Similarly for $(\exists x)\,\phi(n,x)$.  [I'm intentionally ignoring the simplification that, when checking $(\forall x)\,\phi(n,x)$, you can quit as soon as one value of $x$ makes $\phi(n,x)$ false, and when checking $(\exists x)\,\phi(n,x)$, you can quit as soon as one value of $x$ makes $\phi(n,x)$ true.]
If you wanted to check a formula of the form $(\forall x)(\exists y)\,\phi(n,x,y)$, this approach would involve running through all values of $x$ and, for each of those values, running through all values of $y$.  So you'd actually be running through the $y$-values infinitely often, once for each $x$-value.  Similarly, if your formula begins with $k$ quantifiers, you'd do a $k$-deep nesting of infinite searches.  As far as I can see, it is this depth of nesting that is, in your notes, called "how often we have to go through the natural numbers".
If two consecutive quantifiers are of the same sort, i.e., both universal or both existential, then a simplification becomes possible.  For example, in checking $(\forall x)(\forall y)\,\phi(n,x,y)$, instead of nesting the searches as above, you could do a single search, going through all pairs of natural numbers as values for $(x,y)$.  Because of this simplification, the nesting depth is given not by the total number of quantifiers but by the number of blocks of same-sort quantifiers.  That number is the rank of your formula in the arithmetical hierarchy.
Answer: Recall the definition of the hierarchy.
$\Sigma_0^0$ are those relations which are defined by bounded formulas. Given an assignment, we only need to verify the bounded quantifiers to check the truth value of a bounded formula. So there is no need to go over all the natural numbers.
Then come $\Sigma^0_1$ and $\Pi^0_1$, which are defined by one unbounded quantifier. To check that $\exists x\varphi(x)$ holds we need to look for a witness, and potentially we need to go over all the natural numbers; similarly for $\forall x\varphi(x)$ we need to check for all the natural numbers.
Now we proceed by induction, $\Sigma^0_{n+1}$ and $\Pi^0_{n+1}$ are defined as additional quantifier over a lower-level formula. So we need to go over the natural numbers to verify that, and then by induction $n$ more times to verify the inner formula.


How to remove old A/C piping in my house?

Question: When I had my new A/C installed I moved it to the other side of my house (right next to the furnace), so now I have a bunch of old copper piping running about 30 feet from one corner of my house to the other.
My question - is this trivial to remove? Do I just need pipe cutters or is there a better way to do it?  Here is a photo:

I mainly want to do this as my basement is small and there are quite large drop ceilings ONLY because of this pipe, I want to remove the drop ceiling entirely. See here:

And are there any risks? I assume nothing is in either pipe and I could just cut/remove them.
Answer: If the refrigerant has been removed, this is an easy task.  I'd assume the refrigerant was recovered when the old condensing unit was removed, but I only know what you've told us.
If there's no refrigerant in the lines, simply cut them out any way you like. Take the copper to the local scrap yard, and you can pay yourself for the work.
If the refrigerant is still in the lines, you'll have to have it recovered by an HVAC technician.
Comment: I suspect it is removed, but i could open one end and look. Do I just use pipe cutters? Or a hack saw? Or a reciprocating saw?


How to get cable staples to stick in the wall

Question: In my family room, I've used cable staples (like the ones pictured below) to fasten speaker wire along the wall at the top of the baseboards. There are hardwood floors in this room.

Not all of them fastened so securely, which wasn't a problem at first… and then we got a puppy, who bumps into them, and then tries to eat them once they fall out. How can I get them to stay in the wall better, without limiting myself to inserting them over studs (as I sometimes need them more closely spaced than that) or inserting them into the baseboards, which I'd rather not poke so many holes into.
Comment: If you have carpet, speaker wire normally fits well _under_ the baseboards - just watch out for tack strips.
Comment: Anyway, MDF sucks up moisture, and a bathroom is very likely to have a lot of water on the floor for one reason or another.  One bad spill and any unsealed MDF can swell up and be permanently damaged.
Comment: @JPhi1618 thanks, but the room does have hardwoods. I just updated the question.
Comment: Sure, a hardwood floor.  But there are still baseboards (at the foot of the walls), right?
Comment: @wallyk yes, but the baseboards don't have enough room under them to accomodate any speaker wire.
Comment: The wires don't go below the baseboards.  The wires go on the back of the baseboard which often has a gap.  If the baseboard does not have a gap, you could create one in a manner like [this baseboard fascia idea](http://www.thejoyofmoldings.com/half-bathroom-renovation-installing-the-baseboard-fascia/).
Comment: @wallyk That's an interesting idea, but I'd rather not remove the baseboards for this project.
Comment: @wallyk, Getting a little off topic, I know, but I kinda cringe at the idea of MDF trim on a bathroom floor.  Otherwise, interesting idea.
Comment: @JPhi1618 Let me join you off in the weeds. What's wrong with MDF on a bathroom floor? I installed some MDF wainscoting that meets the floor of our half bath, with the wooden baseboards over it.
Comment: How about coming over to [chat](http://chat.stackexchange.com/rooms/111/home-improvement) ?
Answer: Nail in clips just will not hold in drywall.  Even over studs, the nails are typically too short to get good penetration.  Nail clips and stapes can still work (barely) in drywall if they are used up high where they will not be touched.
I would instead recommend and adhesive clip option.

The Command Clips linked also have the advantage of coming off the wall cleanly if you ever need them to.
Another good option is adhesive wire mold that covers the entire length of the cord.  It's a little more expensive, but with no exposed wire, it becomes very puppy-proof.
Comment: I'm pretty sure that last photo (where cords are routed through the wiremold), is a code violation and may or may not go against the installation instructions of the wiremold. No problem using it for speaker wires though.
Comment: @Tester101, Interesting.  I thought any code stopped at the receptacle.
Comment: Does not apply to this post for speaker wire, but there are codes about line voltage wires, including power cords from devices.  For example, it's against NEC code to route a device's line-voltage power cord through a wall (for example a TV mounted on  a wall should not have its power wire run through the wall to an outlet down below).
Answer: The routine I found works best when a customer insisted that I use this particular wire clip, is to replace the nail with one of the same gauge, but a longer length. I only replaced the clips that fell on a stud. I also found if I sunk the nail partly so the clip could be swiveled and then re-positioned over the wire, I didn't fumble the clip. Also, if you hold the clip with needle-nose pliers the clip nail will be hammered more than your finger nail.
Answer: As was suggested above, you can put the speaker wire under the baseboards, or if you are really feeling like a project, you could try running the speaker inside of the wall (if it is an interior wall). It involves a trip to the attic and some fish tape, but is the neatest/most secure way.
If you do not have room under the baseboards, you will need to remove them first, put down the speaker wire and then nail the baseboards back on.


Trigger to Create User in PostgreSQL

Question: Well, after insert a user in systemuser, i like to create a ROLE for PostgreSQL, using the password of new user. But when i try create the user, this error appears:

Blockquote
  ERROR:  syntax error at or near "NEW"
  LINE 24:   ALTER USER NEW.login ENCRYPTED PASSWORD NEW.password...

CREATE OR REPLACE FUNCTION trg_insertuser()
RETURNS TRIGGER AS $trg_insertuser$
DECLARE
BEGIN
    IF (TG_OP = 'DELETE') THEN
        DROP USER OLD.login;
    ELSIF (TG_OP = 'UPDATE') THEN
        ALTER USER OLD.login ENCRYPTED PASSWORD NEW.password;
    ELSIF (TG_OP = 'INSERT') THEN
        CREATE USER NEW.login ENCRYPTED PASSWORD NEW.password CREATEDB IN GROUP group_user;
    END IF;
    RETURN NULL;
END;
$trg_insertuser$ LANGUAGE plpgsql;

What's happend?
Answer: use execute.
execute 'drop user ' || quote_ident(OLD.login);

etc...

Trigger to Create User in PostgreSQL


Will installing ATIs drivers fix the choppiness of my ATi Mobility Radeon HD 4250?

Question: I have some questions about the drivers for ATi video cards.  I recently downloaded and installed the drivers for my machine, and the experience became very choppy and laggy, though it did fix the lag that I had when the Dash was opened.  Anyway, I got another update for the same drivers, except these are "post-release updates" for the drivers.
Should I install those, and would they fix the choppiness of my desktop?  Or should I just uninstall the proprietary drivers and go with the open source drivers, and where would I have to go to download and install those drivers if they aren't already installed?  Also how would I go about removing the proprietary drivers since I already have them installed?  Thanks! :)
Comment: Can you ask a clear concise question or split your question - these are a lot of questions in one.
Comment: And if you want a good answer, at least say which graphics card you have.
Comment: Ok, would installing the newer post-release drivers fix the graphic lag on my desktop?

Are the open source drivers better than the propietary drivers?

How would I be able to remove the propietary drivers if I were to revert back to the open source drivers?

Are the open source drivers included with Ubuntu or do I have to download them?
Comment: I have ATi Mobility Radeon HD 4250.
Comment: What about the "post-release updates"? Can those improve the proprietary drivers? Nobody has mentioned them yet.
Comment: @Jordan We haven't had any driver-related SRU (stable release updates) for Oneiric yet.
Comment: Alright, so are those just a gimmick?
Comment: They are the same as you installing the latest drivers from the ATI site, it wont fix the choppiness. I know of no version from ATI drivers that works good with 3 effects enabled desktop
Answer: You can remove the proprietary drivers on the same screen that you have installed them (under "Additional Drivers), just select the ones you are using now and click on 'deactivate' if you installed them using the "Aditional Drivers" application.
If you used the drivers downloaded from the ATI website there should be a /usr/share/fglrx/ati-uninstall.sh file, run it with sudo sh /usr/share/fglrx/ati-uninstall.sh and that should remove the ATI downloaded drivers.
About what driver to use, well, any of those will have the same effects, the choppiness comes from using compiz with 3d effects, that's not well handled either by Nvidia or ATI drivers (in most cases that is).
My advise is to use the fglrx driver but instead of the unity3d desktop use the unity2d desktop as default. After all do you really need to have special effects when your watching a movie? Does the 3d desktop make you feel better about yourself? Is it worth the choppiness? No, not really... Use the unity2d, its faster, does the same things, looks as good and its not choppy at all!
Comment: I'll try using Unity 2D later on, but what if I wanted to use Gnome Shell?  I thought that needed 3D driver support.
Comment: It does, nothing you can do about it, there are lots of half breed solutions for choppiness that can work, but unity2d is the fastest and simpler one. Try it and if you are happy with it keep using it. If you want to switch to Gnome3 later on you can always try the open source drivers, I hear they work ok also.
Comment: Oh and I used the Addition Drivers application, but I also tried to download the drivers doing sudo apt-get install fglrx' It said that the drivers were already installed and up to dateso nothing happened. But technically can I just sudo apt-get remove fglrx ?
Comment: Use the additional drivers panel, its safer, I think the apt thing will do the same and remove them from your system but the other one is made for this kind of things ;)
Comment: Both the open source and proprietary drivers have 3D support for the HD 4250:
Comment: Yeah, but the open source support for things like wine is really bad.
Comment: I don't use Wine so that's not a problem.
Comment: I cannot recommend the open source drivers since I never used them, give them a go if you want and if that solves all your problems let me know, maybe I can try them on also ;)
Comment: So should I remove the drivers, or try Unity 2D with them?
Comment: Try unity2D, I have no issues playing videos, wine or whatever if I use the fglrx drivers and unity2D.
Comment: Alright I'll give it a try.
Answer: The lag/choppiness can be fixed easily from instructions found here
All you have to do is disable sync to vblank in compiz oprngl plugin.
Comment: I have done that already.  Its still a bit too choppy for my tastes.


How to implement events in Python?

Question: Can't figure out how to implement event system.
I am doing project with tkinter.
And I need to use events.
How to have events like Java or C# events?
I searched a lot but can't figure out the right way.
Here is the event class I am trying to implement.
class Event(object):

    def __init__(self):
        self.handlers = []

    def add(self, handler):
        self.handlers.append(handler)
        return self

    def remove(self, handler):
        self.handlers.remove(handler)
        return self

    def fire(self, sender, earg=None):
        for handler in self.handlers:
            value = handler()
            self.remove(handler)
            return value

    __iadd__ = add
    __isub__ = remove
    __call__ = fire

Here is Car class
class Car:
    _speed = 0
    events = Event()

    def speed_up(self):
        self._speed += 10

    def speed_down(self):
        self._speed -= 10

    def get_speed(self):
        return self._speed

And for last there is Window class (tkinter window)
class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.car = Car()
        tk.Button(self, text="Speed Up", command=self.increase_speed).grid(sticky="nsew")
        tk.Button(self, text="Speed Down", command=self.decrease_speed).grid(sticky="nsew")
        self.speed_label = tk.Label(self, text="0")
        self.speed_label.grid(sticky="nsew")
        self.mainloop()

    def increase_speed(self):
        self.car

    def decrease_speed(self):
        pass

Here is tkinter window:

I want to accomplish:
    1) On Speed Up button click "speed_up" should be added to events.
    2) It should change value of self.speed_label.
    3) It should be something like c# / Java events or c# delagetes.
Trying to learn this new concept to me. But having difficult time implementing this...
UPDATED!
I was searching / editing and came up with a solution.
Don't know if this solution is good.
I will ask my teacher if this is a good way for implementing events.
But for now the code look like this:
import tkinter as tk

class Observer():
    _observers = []
    def __init__(self):
        self._observers.append(self)
        self._observed_events = []
    def observe(self, event_name, callback_fn):
        self._observed_events.append({'event_name' : event_name, 'callback_fn' : callback_fn})

class Event():
    def send(self, event_name, *callback_args):
        for observer in Observer._observers:
            for observable in observer._observed_events:
                if observable['event_name'] == event_name:
                    observable['callback_fn'](*callback_args)

    def receive(self, event_name, *callback_args):
        for observer in Observer._observers:
            for observable in observer._observed_events:
                if observable['event_name'] == event_name:
                    response = observable['callback_fn'](*callback_args)
                    return response

class Car(Observer):
    def __init__(self):
        Observer.__init__(self)
        self._current_speed = 0

    def speed(self):
        self._current_speed += 10

    def slow(self):
        self._current_speed -= 10

    def current(self):
        return self._current_speed

class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self._car = Car()
        self.store()
        self.events = Event()
        tk.Button(self, text="Speed Up", command=lambda:self.change_speed("speed")).grid(sticky="nsew")
        tk.Button(self, text="Slow Down", command=lambda:self.change_speed("slow")).grid(sticky="nsew")
        self.label = tk.Label(self, text=0)
        self.label.grid()
        self.settings()

    def store(self):
        self._car.observe("speed", self._car.speed)
        self._car.observe("slow", self._car.slow)
        self._car.observe("current", self._car.current)

    def settings(self):
        self.mainloop()

    def change_speed(self, event):
        self.events.send(event)
        self.label.config(text=self.events.receive("current"))

Window()

Comment: Have you checked [the tkinter documentation on "Events and Bindings"](http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm)? Unless your aim is to create your own events system reusing tkinter's will prove much easier.
Comment: I know that, but the thing is, this is a side project. I am building bigger project. This project is for me to understand how the events work at the first place. :) I must implement Event class. I think I am not allowed can't achieve that with tkinter events and bindings.
Answer: Without fully analyzing the code in the question, I'd say you're in the right direction by using function callbacks. That's because Python, as far as I know, does not have a native implementation of events.
Some useful libraries or examples that build on this can be seen in articles such as the observer pattern, mimicking events or in answers to a related question.
This is the simplest code I can think of that illustrates the callback concept, without arguments:
   def on_notify():
       print("OK, I'm up-to-date")

   def do_something(update):
       # do whatever I need to do
       print("I've changed\n")
       update()

   do_something(on_notify)

Which outputs:

I've changed
OK, I'm up-to-date

Our "worker" function takes a function parameter to be called when an event happens. In this case it's only one, but a list could be used, so that we have many watchers, which is what the other more complete examples do.
Also relevant are event objects, a mechanism for objects to communicate between threads, which is something worth considering for user interfaces. My guess is that most libraries and frameworks out there which implement the "missing events" functionality are based on either or both of these core methods.
Answer: You can find a good explanation on how to implement observers and events in a language that doesn't have them by default in here (Game Programming Patterns, Observer pattern), it is written in c++, but the implementation is almost the same in python.
I would probably have used a list of observers for each event, so instead of the event having to search for its observers in the observers' list it just has to cycle through its personal list of observers to notify them. If the event has specific parameters that are important like the id of the entity who activated it you could include it on the notification, each observer decides what to do with that, they can simply do nothing if that information isn't relevant to them.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).

How to implement events in Python?


Must the product of a nil ideal with a minimal right ideal be 0?

Question: Let $R$ be a ring (not necessarily with identity or commutative). Suppose that $K$ is a a nil ideal, and let $M$ be a minimal right ideal of $R$. Must it then follow that $MK = 0$?
As $M$ is minimal we must have either $MK = 0$ or $MK = M$, but I can't see any reason why this second case cannot occur. If it did we must necessarily have that $K \supset M$, as $MK \subset M$, $MK \subset K$, so $MK \subset M \cap K \subset M$. So $M$ is nil too. But I can't see how to go from here. I also can't find a counterexample.
The context in which I need this uses this to conclude that $l(K) \neq 0$ (the left annihilator). Even if what I wrote above is false, does this still hold?
Thanks in advance!
Comment: I have to ask: are you *sure* you have to even bother considering the case without identity? It is exceedingly rare to ask a question like this in the absence of identity. And it makes it a lot harder. The answer using identity is relatively simple.
Comment: @rschwieb I agree it's pretty horrible, but in my course we don't assume the identity, instead we prove that it must exist under assumptions such as semiprime and DCC on right ideals. In this case it is important that the identity is *not* assumed. In fact I think it is only assumed that $A$ is a *right* nil ideal
Comment: @rschwieb semi-amusingly our lecturer left this as an easy exercise...
Comment: You need something like a Nakayama Lemma for rings without identity.  Maybe it is simpler since $M$ is cyclic, but then again even cyclic modules over rings without identity are more complicated.  Maybe if you check the steps to prove Nakayama it works out: I've never actually internalized that proof.  It is true, however, that $K$ is in the Jacobson radical, even without identity.  The thing is that I don't know if it annihilates minimal right ideals necessarily, without identity.  Maybe you proved that? Because that's why it's easy with identity.
Answer: After asking around, I have the following elementary solution.
Suppose that $MK = M$. Then for some $m \in M$, $mK \neq 0$, and being a right ideal must then be equal to $M$ as $M$ is minimal. But then for some $k \in K$, $mk = m$. $K$ being nil means that $k^n = 0$ for some $n \in \mathbb{N}$. But then $m = mk = mk^2 = ... = mk^n = 0$, and $mK = 0$. Thus we must have that $MK = 0$.
Comment: The argument is very reminiscent of the way one proves that nilpotent ideals annihilate simple modules, and nilpotent elements of a commutative ring annihilate simple modules.
Comment: +1 Ah yes, even though $mK$ doesn't necessarily contain $m$, it's still a right submodule, so you don't have to worry about the usual ring-without-identity problem.  So you get $m\in mK$ anyway!  I should have noticed that... well done. and thanks for letting me know.
Answer: It looks like the Dorroh extension allows you to lasso this problem into the realm of rings with identity to solve, after all.
The Dorroh extension of $R$, if you don't already know, is the ring $R^1=\mathbb Z\times R$ with pointwise addition and multiplication given by $(n, a)(m,b)=(nm, nb+ma+ab)$.  It is easy to check that a right ideal of $R$ is a right ideal of $R^1$, and so on with left ideals and ideals.
Also importantly, $K$ remains a nil ideal in $R^1$. It's a basic fact (an easy exercise) to show that $K$ is contained in the Jacobson radical of $R^1$.
The last question is whether or not $M$ remains simple as an $R^1$ module. In principle, it could have picked up submodules since $R^1$ is bigger than $R$. Now since it is simple as a right $R$ module, given any nonzero $x,y\in M$, there exists $r\in R$ and $n\in \mathbb Z$ such that $xn+xr=y$ (this says that every nonzero element of $M$ generates $M$, equivalent to simplicity.)
But if you check the multiplication rules, $(n, r)(0,x)=(0,y)$, so it turns out elements of $M$ generate $M$ with $R^1$ just like they do with $R$, so it is minimal as a right $R^1$ ideal too.
A basic characterization of the Jacobson radical is that it annihilates simple modules, so we'd have that $MK=\{0\}$.

This could perhaps be significantly reduced if you had a proof on hand that the Jacobson radical in a ring without identity always annihilates minimal right ideals. I'm simply not positive about this fact, since the situation is a little more complicated than in rings with identity. The only thing I'm pretty sure about is that a nil ideal is still contained in the Jacobson radical of a ring without identity.
Another useful thing would be a Nakayama lemma for rings without identity, which I'm not sure is available and I couldn't find in the sea of references to the ordinary Nakayama lemma.  If such a lemma exists, it would look like $MK=M \implies M=\{0\}$, eliminating the case for you.
Comment: And I've learnt about Dorroh extensions so it was still useful!
Comment: Thanks for the help! It turns out that this can be seen more simply - I've added how as an answer below.
Comment: Yes, that's an improvement! Although I was pretty happy to dicover minimal ideals were preserved in the Dorroh extension...


Adding code-completion to Jetbrain's CLion IDE?

Question: I'm writing a CPython extension using Jetbrain's CLion IDE and I was hoping to get code-completion working for functions and variables inside of Python.h.
I looked through the preferences and I can't find anything relevant.  How do I add code completion and inspection for included libraries?
Answer: CLion uses the CMakeLists.txt in your project to control the lookup paths for code completion and other features -- because your library includes are build specific, it makes sense in a way to put this here.
To the specific question of how to get the Python.h library signatures into autocomplete, your CMakeList file should have something like the following:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/local/Cellar/python3/3.4.3/Frameworks/Python.framework/Versions/3.4/include/python3.4m")

Where -I/path/to/file.h is the local path to the directory that contains the header files that you want to include in your build (and by proxy, your autocomplete lookup for the project).


Resource Folder In Cmake

Question: I have a project like this:
- root/
    - main/
        - include/
            - *.h
        - res/
            - *.txt
        - src/
            - *.c
        CMakeListst.txt
    - CMakeLists.txt

The res folder is the folder with a bunch of text files which my application reads.
This is how my root/CMakeLists.txt looks like:
// Configuration stuff

add_subdirectory(main)

Then root/main/CMakeLists.txt looks like:
include_directories(include)

file(GLOB_RECURSE SOURCES *.c)
file(GLOB_RECURSE RESOURCES *.txt)
add_executable(${PROJECT_NAME} ${RESOURCES} ${SOURCES})

I thought I could add all the resources to the add_executable statement, but then I debugged my program and I found out it crashed when I tried to open the file. Lets say I have a file called foo.txt in the res/ folder, then when I do fopen("foo.txt", "r"); it returns null. How can I add custom resources?
Comment: fopen does not anything in common with Cmake. What do you want to archive?
Answer: I believe you misunderstand what add_executable does. It will generally just pass the files specified in it to the compiler.
As the compiler presumably doesn't know how to process your foo.txt, it ignores it (i'm actually surprised that it does not complain). What happens in your CMakeLists file is roughly equivalent to something like
gcc src/*.c res/*.txt

... which might make clear why it didn't do what you wanted it to (if you're familiar with gcc, not sure about your platform).
So, how can you "add" resources? Well, there are multiple ways:

If you run your executable from the root/main directory, you can just open it like:

FILE* my_file = fopen("res/foo.txt", "r");

or otherwise provide a relative or full path to your file. This is probably the best way.

You can make cmake copy your "foo.txt" to the build directory (and then do what I said in the previous point). That way it's always in the same spot relative to your executable. Here's a link I found that explains this fairly well

You can embed the resources in your binary directly. I personally wouldn't do this unless there was a very good reason why the others can't be used. Generally this should also only be done for very small resources. I'm just putting this here for completeness. A library that can do this is hexembed.
Comment: Thanks for the detailed answer! The only thing is if I give a full path then on another machine it might now work. How do make one standard path that will work anywhere?
Comment: Do what I said in the second bulletpoint then, where you make cmake copy the files to the executable directory. You can then ship your program together with the res folder :)

Resource Folder In Cmake


GET request with headers using cURL PHP

Question: I m trying to make a GET request with headers using cURL PHP.  I am getting an empty response form the server.  I would like to know if I have made this request correctly using cURL PHP.
 // curl GET request with headers
 $url = $sendMailURL;
 $requestHeaders = array(
     $hConLength_.':'.$conLengthValue,
     $hConType_.':'.$conTypeValue,
     $hHost_.':'.$conHostValue,
     $hDate_.':'.$conAmzDateValue);

 $ch = curl_init($url);
 curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 $output = curl_exec($ch);

if(curl_error($ch)){
echo 'curl error: '.curl_error($ch);
}else{
   print_r($output);
}

print_r($requestHeaders):

Array ( [0] => Content-Length:207
        [1] => Content-Type:application/x-www-form-urlencoded
        [2] => Host:email.eu-west-1.amazonaws.com
        [3] => X-amz-date:20180115T224433Z )

Comment: Why you setting `Host` or `Content-Length`? Try without the headers and see if it works.
Comment: That's wrong. `Content-Length:` in the request implies a body, and you don't provide one, making the request rather broken...
Comment: Were do you get `$conLengthValue` from? is that a `strlen` or similar measurement?
Comment: @jamesMcKey you don't. GET requests do not have a request body
Comment: Do `if(curl_error($ch))` not `if($output == false){`. Please show what `print_r($requestHeaders)` looks like, it makes no sense to do it like that.
Comment: @LawrenceCherone please see edit
Comment: I am simply trying to follow the instructions on how to create Signature Version 4 for AWS Simple Email Service.  The GEt request needs headers so that AWS can use it along with my private key to authenticate my request (see link: https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html?shortFooter=true)
Comment: @DanielStenberg good point. how do you add a body to a GET request cURL PHP?
Comment: GET requests *can* have a body but that's really rare so unlikely something an API requires.
Answer: I'm positive that you have found your answer, but in case there are others who will probably want to figure out how to check the headers or want to go down the rabbit hole trying to figure out how SignatureV4 works.
You need to set curl_option  CURLINFO_HEADER_OUT
I used following to set all the options in one go, but I don't see why you can't set them one by one.
$conf = [
    \CURLOPT_CUSTOMREQUEST  => $method,               // method
    \CURLOPT_URL            => $url,                  // url
    \CURLOPT_HTTPHEADER     => $requestHeaders,       // headers
    \CURLOPT_RETURNTRANSFER => true,
    \CURLOPT_HEADER         => true,
    \CURLOPT_CONNECTTIMEOUT => $timeout,              // set to anything that fits
    \CURLOPT_PROTOCOLS      => CURLPROTO_HTTPS,       // whatever is your protocol
    \CURLOPT_HTTP_VERSION   => CURL_HTTP_VERSION_1_1, // normally 1.1
    \CURLINFO_HEADER_OUT    => 1,                     // this will cause request headers to show up
];

curl_setopt_array($this->curl, $conf);

After running your request and before closing curl you can check for your headers and response headers all together.
$result = curl_exec($this->curl);

$info = curl_getinfo($this->curl, CURLINFO_HEADER_OUT); // run after exec before close
var_dump($info);

curl_close($this->curl);

you don't have to specify CURLINFO_HEADER_OUT  when calling curl_getinfo but it will show a lot more info which makes it a little harder to find what you are looking for.
Since you mentioned in comments that you are trying to make SignatureV4 for AWS and  I had the same issue, a few notes:

Although http headers are not case sensitive, when calculating hash they should be in lowercase and also specified in authorization token in lower case too. to make it easier, I just included headers in both request and hash as lowercase
You don't need to hash all the headers, since you will need to mention which headers are included in hash, in the authorization token.
Someone at AWS thought it is cool to sort querystring items alphabetically before calculating hash, so if you are sending querystring, make sure tokens are sorted before hashing it e.g.

Engine=standard&LanguageCode=en-US  // will work
LanguageCode=en-US&Engine=standard  // will not work

The only two headers that need to be in hash are x-amz-date and host. (at least that was the case for Polly) and they need to look like this

host:service.region.amazonaws.com
x-amz-date:20210920T180242Z
authorization:AWS4-HMAC-SHA256 Credential=xxxxxxxxxxxxxxxxxxxx/20210920/region/service/aws4_request, SignedHeaders=host;x-amz-date, Signature=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

GET request with headers using cURL PHP


Translating url regular expressions into path in django 2.1

Question: url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
        views.activate, name='activate'),

I've been doing tutorial but in django 2.1 you have to use path, how do I translate to 2.1 django compatibile path function?
Does the
path('activate/<str:uidb64>/<uuid:token>/', views.activate, name='activate')

do the same?
Comment: No you do not have to use `path`, but it is advisable to use `re_path`: https://docs.djangoproject.com/en/2.1/ref/urls/#django.urls.re_path
Answer:
I've been doing tutorial but in django 2.1 you have to use path, how do I translate to 2.1 django compatibile path function?

No, in django-2.x, you can use path [Django-doc] or re_path [Django-doc]. Furthermore as of today, url [Django-doc] is still supported, but will likely dissapear in the future.
re_path is in fact equivalent to the old url, so you can write this as:
re_path(
    r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
    views.activate,
    name='activate'
),
It is not easy to construct a completely equivalent URL, since Django only supports five path conversions by default:

Path converters
The following path converters are available by default:

str - Matches any non-empty string, excluding the path separator, '/'. This is the default if a converter isn't included in the expression.
int - Matches zero or any positive integer. Returns an int.
slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example,
  building-your-1st-django-site.
uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be
  lowercase. For example, 075194d3-6885-417e-a8a8-6c931e272f00. Returns
  a UUID instance.
path - Matches any non-empty string, including the path separator, '/'. This allows you to match against a complete URL
  path rather than just a segment of a URL path as with str.

We can use slug here, but this will match more than the given URL:
path(
    r'^activate/(<slug:uidb64>/<slug:token>/$',
    views.activate,
    name='activate'
),
The slug pattern takes as regex equivalent:

class SlugConverter(StringConverter):
    regex = '[-a-zA-Z0-9_]+'

Comment: Great answer, that's what I've been looking for - thanks.


Pandas: get the unique value with the biggest index

Question: I have a df like this
    Name    Data
0   Mike    123
1   Mike    456
2   Mike    789
3   Fred    345
4   Fred    123
5   Ted     333

I need to get unique Name with the max index value
output:
    Name    Data
0   Mike    789
1   Fred    123
2   Ted     333

Comment: From the duplicate `df.groupby('Name').tail(1)`
Answer: Step 1st: Import pandas.
import pandas as pd

Step 2nd: Copy OP's df values.
Step 3rd: Now run following command to create data frame from OP's samples.
df=pd.read_clipboard()

Step 4th: Run following code to remove duplicates and keep last value of Name column.
df.drop_duplicates(subset='Name',keep='last')

Output will be as follows.
   Name   Data
2   Mike   789
4   Fred   123
5   Ted    333

Comment: wow. Amazingly simple. Thanks. This answer is so much better than the groupby solutions. So easy to understand and readable. ... Also.. +1 for the `read_clipboard()`... didn't know you could do that... that's also amazing!


What are the options to end a mutable borrow in Rust?

Question: I'm strugglin' with the borrow checker - wonder o' wonder.
While I found a solution by adding a block, I am curious if there are other ways to end a mutable borrow so the next statement can access a binding afterwards.
Here's what I did so far:
let mut canvas: Canvas = Canvas {
    width: 5,
    height: 5,
    array: vec!['x'; 5*5],
};

{
    let mut renderer: CanvasRenderer = CanvasRenderer::new(&mut canvas);

    renderer.render_point('x', 3, 3);
}

println!("The Value in the array is: {}", canvas.array[9]);

I wrap a block around the binding of a CanvasRenderer object and after mutating the canvas and the scope ends, the CanvasRenderer dies and my mutable borrowed canvas is available to be read or whatever.
This works - but now I'd like to see other solutions!
I heard about drop(stuff) but it did not work as I thought it should.
Answer: There is no other way; using blocks is the way to do it. Before Rust 2018 (available in Rust 1.31) all borrows are lexical, that is, they always correspond to some lexical scope. The only scope which is larger than a single statement is that of a block, so blocks are your only tool to limit borrow scopes.
drop() would not work for two reasons: first, because it would require non-lexical scope which is not supported before Rust 2018, and second, it cannot be a general-purpose tool for managing borrows: for example, it wouldn't be able to end an immutable borrow simply because immutable references are Copy and can't be "dropped".
See also:

Moved variable still borrowing after calling `drop`?
What are non-lexical lifetimes?
Comment: "because immutable references are Copy"
Are you sure that a immu ref is a copy? So if the value it refers to is changed the receiver of that immu ref wont notice or wouldnt print ie. the new value? Because it has the copied state not the reference to it?

Or am I failing hard with my brain again? ;)
Comment: @xetra11, if you have an immutable reference, **there is no way** to change the data it points to, neither through this reference nor by any other means (except `unsafe`, of course). More concretely, if you have an immutable reference to some variable, you neither can take a mutable reference to the same variable or its internals nor you can modify this variable directly even if it is stored in a `mut` slot. This is one of the cornerstones of Rust ownership/borrowing concept, and this is what makes aliasing of immutable references safe. Also note that mutable references are not copyable.
Comment: Ah yea youre right. It says if there is one mutable borrow around you cannot have an immut ref to that value. In other words there will only exist mut refs or copys of values?! (unless not unsafe)
Comment: @xetra11: Whether a reference is `Copy` is orthogonal to whether the underlying data is `Copy`.

Immutable references don't copy the underlying data, but the reference itself is copyable (`impl Copy for &T`) -- this why you can share immutable references.

`&mut T` references on the other hand are not copyable.
Comment: Ok I think i got it now. A mut ref is never copied because if it would be - two workers could mutate its state. An immu ref will copy the reference to the underlying data so many workers can read them but because of immutability never change them.


How to define a hdf5 file as a function of some dependent variables?

Question: I need your kind suggestion. I have a hdf5 file and I can able to read the file in python. The h5 file contains a large number of data and these are the values of potential (depends on position (x, y, z) ). I am also able to interpolate my 3D regular grid data by using RegularGridInterpolator. Now, my question is: how I can define my h5 file data as a function of x, y, z so that it can able to update my a_1 (x,y,z) , a_2(x,y,z)... values in my code. Here is the link of my h5 file: https://drive.google.com/open?id=1OFIg7pjfpfjq3Vnvqaj2uyCFjiTwZ9QK
My code:
import numpy as np
from numpy import gradient
import h5py
import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolator

f = h5py.File('k.h5', 'r')
list(f.keys())
dset = f[u'data']
dset.shap
dset.value.shape
dset[0:64, 0:64, 0:64]
x = np.linspace(-160, 160, 64)
y = np.linspace(-160, 160, 64)
z = np.linspace(-160, 160, 64)

my_interpolating_function = RegularGridInterpolator((x, y, z), dset.value)
pts = np.array([100, 5, -10])
my_interpolating_function(pts)

# Apply gradient function
gradx, grady, gradz = np.gradient(dset.value)
gradx.shape

# To find the gradient at any point
gradx_interpol = RegularGridInterpolator((x, y, z), gradx)
grady_interpol = RegularGridInterpolator((x, y, z), grady)
gradz_interpol = RegularGridInterpolator((x, y, z), gradz)

def get_val_and_grads(pts):
    v1, x1, y1, z1 = my_interpolating_function(pts), gradx_interpol(
        pts), grady_interpol(pts), gradz_interpol(pts)
    return v1, x1, y1, z1

##getting_interpolated_values

k1 = my_interpolating_function(pts)
k_dx = gradx_interpol(pts)
k_dy = grady_interpol(pts)
k_dz = gradz_interpol(pts)

def a_1(x,y,z):

    return  -(adot/a**2)*k1

def a_2(x,y,z):

    return (1/a)*k_dx

Comment: This is more about scipy and interpolation than HDF5. Take a look at this topic. It has some guidance for `RegularGridInterpolator` [link](https://stackoverflow.com/questions/53758209)
Comment: @kcw78 Thanks for your kind suggestion with link. I have checked the link and understand that it's helpful for reading and interpolating any hdf5 file. But my concern is that my h5 file contains the values of potential which is depends on position (x, y, z). So, I have to define my interpolating function in such a way so that my potential values depend on x, y, z and update the values of a_1 and a_2 as they are depends on x, y, z. Can you please help me how I can define my interpolating function so that it's depend on x, y, z.
Comment: I will try to help (can't access your file). First, the link is _helpful for reading and interpolating_ **any data on a 3d Mesh**. Data source doesn't matter. Have you done the scipy example without a h5 file? I would expect to find 4 datasets in your sample file: 1 each for the X, Y and Z coordinates to define the grid, and 1 for the potential values at all X/Y/Z values above. In your code, you define the X/Y/Z values with linspace (not retrieved from the H5 file). Next you need a return variable when you call `my_interpolating_function(pts)` if you want to use it later.
Comment: @kcw78 Thanks for your kind feedback. I am sorry as my previous link doesn't work. You can get the file from here: https://drive.google.com/open?id=14lrChd9nn8M3HqH3GQrCT7OXBxVSYuD8 . Can you please help me again how can I define 4 data set from my sample file? Expecting your kind suggestion. Thanks in advance.
Answer: I will try to help. Your question has more to do with scipy RegularGridInterpolator() than with HDF5. HDF5 is just a data source. I suggest you work thru the scipy example before using HDF5. It shows how the grid coordinates and values are defined and used by the interpolation function.
I looked at your HDF5 file (k.h5). It only has one dataset with the potential values at the mesh points. It does not have coordinates at the mesh points (the x,y,z values). You defined the x,y,z coordinates with these lines in your code:
x = np.linspace(-160, 160, 64)
y = np.linspace(-160, 160, 64)
z = np.linspace(-160, 160, 64)

The coordinates and values are usually stored together. The way you are doing it, you could associate ANY x,y,z coordinates to these mesh values. Is that your intent?
I reworked the first part of your code to interpolate a few values. See below. I am not familiar with np.gradient(), so can't help with that part.
The first call to RegularGridInterpolator() (and returned value) is done with the x,y,z value you provided above.
The second call to RegularGridInterpolator() (and returned values) is done for the corner coordinates for your dataset (the first/last values). It confirms the interpolator returns the "right answer".
Updated code to interpolate values:
import numpy as np
from numpy import gradient
import h5py
#import matplotlib.pyplot as plt
from scipy.interpolate import RegularGridInterpolator

f = h5py.File('k.h5', 'r')
list(f.keys())
dset = f[u'data'][:,:,:]
print ('dset.shape=', dset.shape)
print ('dset.first/last=', dset[0,0,0], dset[-1,-1,-1])

x = np.linspace(-160, 160, 64)
y = np.linspace(-160, 160, 64)
z = np.linspace(-160, 160, 64)

my_interpolating_function = RegularGridInterpolator((x, y, z), dset)

pts = np.array([100, 5, -10])
print ('pts=', pts)
vals_at_pts = my_interpolating_function(pts)
print ('vals_at_pts=', vals_at_pts)

pts = np.array([[-160, -160, -160], [160, 160, 160]])
print ('pts=', pts)
vals_at_pts = my_interpolating_function(pts)
print ('vals_at_pts=', vals_at_pts)

Output:
dset.shape= (64, 64, 64)
dset.first/last= -2.386316671021661e-05 -2.966368162003158e-05
pts= [100   5 -10]
vals_at_pts= [-3.0528203e-07]
pts= [[-160 -160 -160]  [ 160  160  160]]
vals_at_pts= [-2.38631667e-05 -2.96636816e-05]


How to update GIMP in Ubuntu 16.04 using snaps?

Question: I know that an application (GIMP) has had a recent update from 2.8.16 to 2.8.18 to fix some security issues. This recent update is not being pushed out by Snappy for Ubuntu 16.04.  I know this because I have a PPA on another machine running Ubuntu 14.04 which keeps GIMP up to date. The PPA keeps the software current on 14.04.  How do I ask Snappy to update GIMP on 16.04?
Comment: The 2.8.18 version of Gimp is in Ubuntu 16.04 repository. What do you mean by "not being pushed out by Snappy"?
Comment: I have GIMP installed in Ubuntu Studio 16.04 which uses the XFCE interface.  When I go to Software, it shows GIMP as being installed and that the current version installed is 2.8.16.  I verify that by opening GIMP and going to About.  There it shows 2.8.16.    Software says all apps are up-to-date.   I get regular OS updates which I install.
Comment: I ran Synaptic and it shows the latest version being 2.8.16.
Comment: See the answer.
Answer: The latest version of the gimp package in the 16.04 repositories (which is 2.8.16-1ubuntu1.1) includes a fix for the XCF vulnerability (CVE-2016-4994). From the Ubuntu changelog:
gimp (2.8.16-1ubuntu1.1) xenial-security; urgency=medium

  * SECURITY UPDATE: multiple issues in XCF channel and layer properties
    - debian/patches/CVE-2016-4994.patch: properly clear pointers in
      app/xcf/xcf-load.c.
    - CVE-2016-4994

 -- Marc Deslauriers <email@example.com>  Thu, 30 Jun 2016 12:40:34 -0400

Thus if you are only interested in this bug fix, and not in any other thing which was introduced in 2.8.18, there is no need to update your gimp package through other means.
Comment: That makes sense.
Answer: GIMP 2.8.18 has not reached Ubuntu repositories yet.
If you need 2.8.18 now so badly, you can install it from PPA this way
sudo add-apt-repository ppa:otto-kesselgulasch/gimp
sudo apt update
sudo apt install gimp

At the moment of writing this, Gimp will be upgraded to 2.8.18.
Comment: GIMP 2.8.18 will most likely never be in the 16.04 repositories; instead, the bug fixes are backported to 2.8.16.
Comment: Thanks that clarifies the question.   I was led to believe it had reached the repositories and was trying to figure out why the software updates hadn't picked it up.   I was told there was a security vulnerability with XCF files and was just trying to keep my system patched.
Comment: @fkraiem Who told you that? I've never seen that Gimp had any backports in Ubuntu.
Comment: @jerrysvoice That PPA has alway the latest Gimp for all Ubuntu supproted versions.
Comment: Security-related fixes are backported, and have been in this case. You just won't get 2.8.18.
Comment: Thanks. I just added the PPA as I had on 14.04.   Everything is up-to-date now.  Thanks.
Comment: You can accept the correct answer by clicking the check sign at the left. I got 2 downvotes already ;-) @jerrysvoice
Comment: This issue is solved with PPA from Otto Kessel.


Export to CSV using PowerShell 2.0?

Question: I have the following code that prints the file system rights of each account enabled on the folder with path "C:\Temp\CSM\*" & "C:\Temp\CSM\*\*" . How do I write the output in a comma-separated CSV? As this is for PowerShell 2.0 Export-Csv -Append parameter cannot be used.
$FolderPath = dir -Directory -Path "C:\Temp\CSM\*", "C:\Temp\CSM\*\*" -Force

foreach ($Folder in $FolderPath) {
    $Acl = Get-Acl -Path $Folder.FullName
    foreach ($Access in $acl.Access) {
        Write-Host $Folder.FullName "," $Access.IdentityReference "," $Access.FileSystemRights
    }
}

Answer: Prior to PowerShell v3 if you wanted to append to an existing CSV you need something like this:
... | ConvertTo-Csv -NoType | Select-Object -Skip 1 | Add-Content

However, in your scenario that probably isn't necessary. If you replace your foreach loops with a pipeline you can write the CSV in one go without having to append to it in a loop (which isn't recommended anyway).
$folders = "C:\Temp\CSM\*", "C:\Temp\CSM\*\*"

Get-ChildItem -Path $folders -Directory -Force | ForEach-Object {
    $path = $_.FullName
    Get-Acl -Path $path |
        Select-Object -Expand Access |
        Select-Object @{n='Path';e={$path}}, IdentityReference, FileSystemRights
} | Export-Csv 'C:\output.csv' -NoType

Export to CSV using PowerShell 2.0?


More than one enum declaration

Question: There is the quote from the sec. 3.3.1/4 of N3797 working draft:

Given a set of declarations in a single declarative region, each of
  which specifies the same unqualified name,
— exactly one declaration shall declare a class name or enumeration
  name that is not a typedef name and the other declarations shall all
  refer to the same variable or enumerator, or all refer to functions
  and function templates;

We can declare enum type name several times in a single declarative region:
enum A; // declared first time, the other declaration with the same
        // unqualified name shall all refer to the same variable or enumeration.
enum A; // This and the other declarations shall all refer to the that enumeration
extern int A; // Fail, now enum A is hidden and we can access it
              // via elaborated-type-specifier only

I'm confused. Can you explain this behavior? I would like to find corresponding references to the current working draft.
Comment: No [we cannot](http://ideone.com/9foG8J) declare `enum` type name several times. In fact, [we cannot](http://ideone.com/Zh4rI7) even declare it once, the way you show.
Comment: Yours is not it. **7.2/2** An *opaque-enum-declaration* declaring an unscoped enumeration shall not omit the *enum-base*.
Comment: @IgorTandetnik But what about _opaque-enum-declaration_ which defined as `enum-key attribute-specifier-seq_opt identifier enum-base_opt`.
Comment: @IgorTandetnik Are you sure that you are looking at the same working draft that I specified in my post (N3797 C++14 working draft)?
Answer: The full quote n3797 3.3.1/4 is:

Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,
— they shall all refer to the same entity, or all refer to functions and function templates; or
— exactly one declaration shall declare a class name or enumeration name that is not a typedef name
  and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden.

The code you wrote is wrong. See S7.2 for the required syntax, which may be any of these:
enum A : int; // declaration (and it is an enumeration name)
enum A : int; // refers to the same entity

enum struct A; // declaration (and it is an enumeration name)
enum struct A; // refers to the same entity

enum A {}; // declaration (and it is an enumeration name)
enum A {}; // refers to the same entity

Then the following may occur later in the translation unit.
extern int A; // declaration hides enumeration name

void f() {
  A j = A.a; // illegal. A is hidden
  int k = A; // legal
}

See n3797 3.3.10/2:

A class name (9.1) or enumeration name (7.2) can be hidden by the name of a variable, data member,
  function, or enumerator declared in the same scope. If a class or enumeration name and a variable, data member, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the variable, data member, function, or enumerator name is visible.

So the last A hides the earlier ones. Is that what you were asking?

Re the question: is the program well-formed? Obviously these are just fragments, and no complete program has been presented, but would it be legal if these were the only references to A? My answer is yes. S7.2/6 says:

An enumeration whose underlying type is fixed is an incomplete type from its point of declaration (3.3.2) to immediately after its enum-base (if any), at which point it becomes a complete type. An enumeration whose underlying type is not fixed is an incomplete type from its point of declaration to immediately after the closing } of its enum-specifier, at which point it becomes a complete type.

So in each of the examples given A is a complete type as shown. The 7.2/3 says:

An opaque-enum-declaration is either a redeclaration of an enumeration in the current scope or a declaration of a new enumeration. [ Note: An enumeration declared by an opaque-enum-declaration has fixed underlying type and is a complete type. The list of enumerators can be provided in a later redeclaration with an enumspecifier. —end note ] A scoped enumeration shall not be later redeclared as unscoped or with a different underlying type. An unscoped enumeration shall not be later redeclared as scoped and each redeclaration shall include an enum-base specifying the same underlying type as in the original declaration.

So it seems that these declarations can be repeated as long as the attributes and base are the same, but perhaps not once the list of enumerators has been provided.
For the first two it would seem the program is well-formed, but perhaps not for the last.
Comment: Let's assume those `enum`-declarations were actually legal, like `enum class A; enum class A;` or `enum A : int; enum A : int;`. Is the program well-formed then, despite having *not just one* declaration that declares an enumeration name?
Comment: The program is legal as it stands (excluding the illegal assignment). Setting the base type or scope doesn't change that (as long as they refer to the same entity). If you have something more complicated in mind, you probably need to ask a new question.
Comment: `enum A;` is certainly not legal as [Igor Tandetnik](http://stackoverflow.com/users/1670129/igor-tandetnik) also pointed out in comments to the OP. You cannot leave out the enum-base for forward-declarations of unscoped enums. The actual question I have is about the two declarations of an enumeration. 3.3.1/4 says "exactly one declaration shall declare a [...] enumeration name" and here we have two declarations declaring an enumeration name. So the requirement for hiding does not hold as far as I can see.
Comment: @dyp: I disagree. `enum A;` is legal on my reading of n3797 s7.2 _opaque-enum-declaration_. Please show otherwise.
Comment: @dyp: see edit. Better now? To your original question, by my reading the program is well-formed (7.2/3: `is a complete type`) In any case there was no presumption that these code fragments constituted an entire translation unit, let alone a whole program.
Comment: *"by my reading the program is well-formed (7.2/3: is a complete type)"* Hmm I don't quite understand how that quotes relates to the rest.. -- `enum A : int; enum A : int;` are two declarations that declare the same thing. So my question was whether those two declarations count as one for the requirement *exactly one declaration shall declare a class name or enumeration name*.
Answer: I think you are doing it wrong. Enumerator (enum) is a type, if you write
enum A;
 You are giving a name to this type, but still you don't have any variables. There are two possible ways for declaration.
1. You can write:
enum A { a, b, c };
, now you have 3 variables { a, b, c }, their type is enum and the name of the type is A. The second way is:
enum NAME;
NAME var1;
NAME var2;
You also can have unnamed variables:
enum { a, b, c };
This is used when you want names for constants but don't plan to use the type to declare variables, function arguments, etc.
Comment: Seems, you don'r understand me. I would to understand formal c++ language rules. I don't interesting of usability in this question.

More than one enum declaration


compute $\left|<\tau^2>\right|$ for the given permutation

Question: $\tau = \left( \begin{array}{cc}1&2&3&4&5&6\\2&4&1&3&6&5\end{array}\right)$
I need to compute $|\langle  \tau^2\rangle|$
I know $\tau^2 = \left( \begin{array}{cc}1&2&3&4&5&6\\4&3&2&1&5&6\end{array}\right)$
but know how do I do $\Bigg|\Bigg\langle\left( \begin{array}{cc}1&2&3&4&5&6\\4&3&2&1&5&6\end{array}\right) \Bigg\rangle\Bigg|$ ?
Its the size of the group generated by $\tau^2$?
Comment: Note that : $(\tau^2)^n$ always fix $5$ and $6$, now you can work with a shorter permutation, for every $n$
Comment: I think I found something similar,  the order will be
$lcm((1 \, 2 \, 3 \, 4)(5 \, 6)) = 4$
Comment: I meant:
  the order will be
$lcm((1 \, 2)( 3 \, 4)(5 \, 6)) = 2$
Answer: Let $\sigma = \tau^2$; then we are interested in $|\langle\sigma\rangle|$. What is $\langle\sigma\rangle$? Notice that $\sigma^2 = e$. Therefore the group generated by $\sigma$ (the set of powers and inverse powers of $\sigma$) is simply $\{e,\sigma\}$. So your answer is $2$.
Comment: The idea is correct, but your cycle decomposition is incorrect. The correct decomposition is $\tau = (1243)(56)$. And the decomposition of $\tau$ isn't really important; what is important is the decomposition of $\tau^2 = (14)(23)$. With this, your idea work,s
Comment: okay, this is similar to my comment correct? not the first one, the second one (couldn't edit the first after 5 minutes). theres 3 disjoint cycles, each with 2 elements and so the lcm is 2


azure u-sql table - how to read from python

Question: I have created U-SQL Table in Azure Data Lake Analytics, I need to extract specific rows from that table using Python, any help please?
Comment: Hi, welcome to SO. We do require you to show that you did put in some effort before asking a question. This question is therefore off-topic. Have you tried google yet, there are python example available, see https://github.com/Azure/usql/blob/master/Examples/PythonExamples/PythonExamples/TweetExtract.usql for example
Comment: Thanks, yes this code I got multiple times in my search, BUT I want data in Python directly, not as output in DataLake, trying avoid that step of reading the output again. Any help.
Comment: At the moment that is not possible, there is a request for it though: https://feedback.azure.com/forums/327234-data-lake/suggestions/11266677-support-interactive-workloads-within-adl-analytics
Answer: To lift Peter Bons' reply into an answer:
You currently do not have an interactive, direct to client, mode for U-SQL in Azure DataLake Analytics.
As a work-around, you could write a shim that does model it by writing the resulting file behind the scenes and downloading it.
Please make sure to register your request (and indicate that you want it for U-SQL specifically :)) at http://aka.ms/adlfeedback.


nested attributes and adding attributes through the controller?

Question: As this question is hard to describe, that's the best title i could come up with, so here is some code.
Given three Models Parent, Child && Grandchild.
Parent <  ActiveRecord::Base
  has_many :children
  has_many :grandchildren
  accepts_nested_attributes_for :child
end

Child <  ActiveRecord::Base
  belongs_to :parent
  has_many :kids, :as => :grandchildren #this is just an example
  accepts_nested_attributes_for :grandchild
end

Grandchild <  ActiveRecord::Base
  belongs_to :parent
  belongs_to :child
end

I'd like to add the current_user.id to both the child record and Grandchild record that gets created in during Parent#new.  I've used hidden fields for now, because i couldn't find a good way to add them.
Maybe someone can help by creating a callback to add the current_user.id on create?  I've never had much luck getting that into a model anyways, but you are smart.
Thoughts?
Comment: Can anyone update the response for rails 3?
Answer: Well, for one thing, I'd recommend a has_many :through relationship from parent to grandchild (through child), and vice versa.  See the "Association Join Models" section in the ActiveRecord Association Class Methods API for more details.
As to your main question, like you say, a callback is probably what you want.  I think something like this should do it (though this is untested code):
class Parent
  # ...somewhere at the top...
  before_create :set_current_user_on_descendants

  # ...somewhere in the main class body...
  # (I assume parent['current_user'] is passed in as a typical
  # parameter, and thus self.current_user is already set.)
  def set_current_user_on_descendants
    children.each { |c| c.current_user = self.current_user }
    grandchildren.each { |gc| gc.current_user = self.current_user }
  end
end

There are a few stylistic points that could be done differently.  You could define a "descendants" method that returned children + grandchildren and iterate over that, for example, or you could implement the callback on the child and grandchild classes (in which case you might want to pull it out in to a module for maximum DRYness, though for a one-line method in only two classes that might be overkill).  Depending on exactly when you want to update current_user, you might want to use before_save or some other callback instead of before_create - you can find a complete list of the available callbacks in the ActiveRecord callbacks API.
Comment: i'll check this out for sure. thanks for being thorough, although i am familiar with the callbacks and my example was off the top of my head, this information will help others down the road.  when i test i'll mark as complete cause it looks like it should work.
Comment: well passing the @current_user didn't do anything, however i just stole the user_id column from `self.user_id` for each of the descendants. I'd like to mark your answer as complete if you want to add that to it.
Answer: I suppose its also possible to override the default save! method
class Parent < ActiveRecord::Base
   def save!
      children.each { |c| c.current_user = @current_user }
      grandchildren.each { |gc| gc.current_user = @current_user }

      super
   end
end

Untested as well. Not really sure this would work...


No properties in Submiting a Form to Ajax

Question: So I'm trying to submit a form to an Ajax, but looks like this Ajax does't send nothing to my Json, I tested the result of this Ajax and this is the message I've found in the console "No properties".
This is the form:
<form id="formPrueba" method="POST">
        <input type="text" id="film_id">
        <input type="text" id="title">
        <input type="submit" name="sub">
        <button form="formPrueba" onclick="editar()"></button>
</form>

Ajax function:
function editar(){
    event.preventDefault();
    $.ajax({
        method: "POST",
        url: "prueba.php",
        data: $("#formPrueba").serialize(),
        dataType: "json"
    })
        // en caso de éxito
        .done(function (response) {
            // Escribe el mensaje recibido en el JSON descartando el contenido anterior
            console.log("Response de Edit".response);

        })
        // En caso de fallo
        .fail(function (jqXHR, textStatus, errorThrown) {
            alert("Error: " + textStatus);
        });
}

Json (test):
<?php
echo ("Esto es prueba");
echo json_encode($_POST);

Json:
<?php
include "class/Film.php";
require_once "class/DBSingleton.php";
//Json
$film_id = (isset($_POST['film_id'])? $_POST['film_id'] : null);
$title = (isset($_POST['title'])? $_POST['title'] : null);
$description = (isset($_POST['description'])? $_POST['description'] : null);
$release_year = (isset($_POST['release_year'])? $_POST['release_year'] : null);
$language_id = (isset($_POST['language_id'])? $_POST['language_id'] : null);
$original_language_id = (isset($_POST['original_language_id'])? $_POST['original_language_id'] : null);
$rental_duration = (isset($_POST['rental_duration'])? $_POST['rental_duration'] : null);
$rental_rate = (isset($_POST['rental_rate'])? $_POST['rental_rate'] : null);
$length = (isset($_POST['length'])? $_POST['length'] : null);
$replacement_cost = (isset($_POST['replacement_cost'])? $_POST['replacement_cost'] : null);
$rating = (isset($_POST['rating'])? $_POST['rating'] : null);
$special_features = (isset($_POST['special_features'])? $_POST['special_features'] : null);
$image = (isset($_POST['image'])? $_POST['image'] : null);
$last_update = (isset($_POST['last_update'])? $_POST['last_update'] : null);

switch ($_POST["action"]) {
    case 'listado':
        try {
            $response["msg"]="Listado de las Peliculas.";
            $response["success"]=true;
            $response["data"]=Film::list();
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    case 'insert':
        try {
            $response["msg"]="Insertar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id,$title,$description,$release_year,$language_id,$original_language_id,$rental_duration,$rental_rate,$length,$replacement_cost,$rating,$special_features,$image,$last_update);
            $instanciaPelicula->insert();
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    case 'delete':
        try {
            $response["msg"]="Eliminar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id);
            $instanciaPelicula->delete();
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    case 'update':
        try {
            $response["msg"]="Actualizar.";
            $response["success"]=true;
            $instanciaPelicula=new Film($film_id,$title,$description,$release_year,$language_id,$original_language_id,$rental_duration,$rental_rate,$length,$replacement_cost,$rating,$special_features,$image,$last_update);
            $instanciaPelicula->update();
            echo ($film_id.$title);
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    case 'paginacion':
        try {
            $response["msg"]="Paginar.";
            $response["success"]=true;
            $peliculas=Film::paginacion();
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    case 'select':
        try {
            $response["msg"]="Seleccionar.";
            $response["success"]=true;
            $response["data"]=Film::select($film_id);
        } catch (Exception $e) {
            $response["success"]=false;
        }
        echo json_encode($response);
    break;
    default:
        # code...
    break;
}

This Ajax belongs to Update part, there I have a function to update the object from a database.
Answer: In your update case's try block, you are spoiling the echo'ed json format because you are echoing ($film_id.$title).
Whenever you want to deliver valid json to your ajax technique, there must be no other text to interfere.
If you want to pass additional data, it needs to be built into your json string (not simply appended before it).
If you open your browser's dev tools and inspect the XHR tab's details, you should see how the json string is corrupted which causes your process to fail.
From https://api.jquery.com/serialize/ :

Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.

So you need to add a couple of name attributes to your form fields.
Comment: Hi mick, the problem is when I try to inspect the XHR tab's details, I see only that message "No properties" in the "prueba.php" (test) json... Another thing, when I submit the parameters I get a Parse Error.
Comment: This test is bad for the same reason that I explainED in my answer.  `echo ("Esto es prueba"); echo json_encode($_POST);` should be `echo json_encode(["Esto es prueba", $_POST]);` so that all data is inside the json formatted string.
Answer: You've already got a correct answer here, but I wanted to make some comment on your code.
First point, since PHP 7.0 (released 4 years ago) we have had the null coalesce operator, to make your variable assignments from POST much shorter. Second, the idea of DRY means not repeating code over and over again, like you are doing with your calls to json_encode(). Third, whitespace and formatting make a huge difference to how easy your code is to read, and work with. Here's how I would improve your code:
<?php
include "class/Film.php";
require_once "class/DBSingleton.php";
//Json
$film_id              = $_POST['film_id'] ?? null;
$title                = $_POST['title'] ?? null;
$description          = $_POST['description'] ?? null;
$release_year         = $_POST['release_year'] ?? null;
$language_id          = $_POST['language_id'] ?? null;
$original_language_id = $_POST['original_language_id'] ?? null;
$rental_duration      = $_POST['rental_duration'] ?? null;
$rental_rate          = $_POST['rental_rate'] ?? null;
$length               = $_POST['length'] ?? null;
$replacement_cost     = $_POST['replacement_cost'] ?? null;
$rating               = $_POST['rating'] ?? null;
$special_features     = $_POST['special_features'] ?? null;
$image                = $_POST['image'] ?? null;
$last_update          = $_POST['last_update'] ?? null;

// assume true, so you don't have to type it every time
$response = ["success" => true];

// since we are checking for exceptions in every block, just wrap it all in one try block
try {

    switch ($_POST["action"]) {
        case 'listado':
            $response["msg"] = "Listado de las Peliculas.";
            $response["data"] = Film::list();
        break;

        case 'insert':
            $response["msg"] = "Insertar.";
            // you can't read lines that are 300 characters long
            $instanciaPelicula = new Film(
                $film_id, $title, $description, $release_year, $language_id,
                $original_language_id, $rental_duration, $rental_rate, $length,
                $replacement_cost, $rating, $special_features, $image, $last_update
            );
            $instanciaPelicula->insert();
        break;

        case 'delete':
            $response["msg"] = "Eliminar.";
            $instanciaPelicula = new Film($film_id);
            $instanciaPelicula->delete();
        break;

        case 'update':
            $response["msg"] = "Actualizar.";
            $instanciaPelicula = new Film(
                $film_id, $title, $description, $release_year, $language_id,
                $original_language_id, $rental_duration, $rental_rate, $length,
                $replacement_cost, $rating, $special_features, $image, $last_update
            );
            $instanciaPelicula->update();
        break;

        case 'paginacion':
            $response["msg"] = "Paginar.";
            $peliculas=Film::paginacion();
        break;

        case 'select':
                $response["msg"] = "Seleccionar.";
                $response["data"] = Film::select($film_id);
        break;

        default:
            # code...
        break;
    }

} catch (Exception $e) {
    $response["success"] = false;
    // you may not want to use the message directly, but you should
    // have some indication from the server of what the error was
    $response["error"] = $e->getMessage();
}

// set the correct header for the data you're sending
header("Content-Type: application/json");
echo json_encode($response);

Comment: Thank you Miken, I'm a student so this is pretty useful for me.


Home electric panel: Two different electric cirtcuits on the same thermostat

Question: Trying to figure out if the electric installation is up to code at my place.
There are two electric circuits :

The first one feeds the electric heaters in the living room
The second one feeds the electric heaters in the bedrooms AND allows the thermostat to work

The thermostat controls all the heaters. Either everything heats, or nothing does (unless I switch the 1. on the electric panel). It's an older model which doesn't seem smart at all, just a knob. I doubt it "controls" another switch on the first circuit.
It feels like this thermostat controls both circuits, which isn't up to code if I understand correctly?
Does it sound like a legit installation?
Would it be easy to update a more advanced/smart thermostat that would allow us to control the two areas separately, or even better, each room separately ?
Comment: There are multiple types of thermostats and controls and at this point all guesses. Model #s, picture of thermostat, picture of wiring going to thermostat (if you can safely get a picture - be very careful if there is any chance of 120V or 240V wiring at the thermostat) would all help to figure this out.
Comment: What make and model is your thermostat? Can you turn both breakers off, then post photos showing how the thermostat is wired?
Comment: Relays could accomplish that, it would be odd and barring some unknown reasons it would be unnecessarily complicated. I would be very careful troubleshooting this, there is potential that somebody has replaced 240v heaters with 120v heaters, and used some series connection, ground wire as a neutral, or other chicanery. Also 2 single- pole (120v) or 2 two-pole (240v) breakers?
Answer: Sure. Relays allow that sort of thing to happen, utterly legit to code. Most likely (but not guaranteed) how yours are run. The transformer for the thermostat would appear to be on circuit 2 based on the described behavior. It could also be (but is less likely to be) a line voltage coil relay, rather than a low-voltage coil relay.
While most people assume that all electric-resistance heat is controlled by line voltage thermostats (and a lot is) it's entirely possible to have a 24VAC (typical) thermostat that controls relays that control the heater circuits. I've lived in a place that had at least 3 circuits dedicated to one thermostat.
You can change that arrangement easily enough if you want to, though what you really should consider is changing from expensive to operate "toaster" heat to inexpensive to operate mini-split heat pump in a version suitably cold-climate for your location (or up the purchase price even more for ground-source...with even lower running cost, but it will take a long time to pay back the difference in installation cost.)
Answer: Sounds fine to me.
I mean, I am a bit surprised to hear of an electric resistance heater being controlled by a thermostat on a different circuit. Generally to keep things simple/cheap, resistance heater thermostats directly switch the 240V, which is a little nuts, and tends to throw the thermostat out of calibration from all that current heating up the internal wires within the thermostat.
Having a 240V "direct" thermostat switch a second circuit could be done (rather badly) by using a 2-pole thermostat, however the vast majority of 2-pole thermostats don't thermally switch both poles; only one switches at temperature and the other is simply an on/off switch.  So that usually will not work.
The more sensible way would be by using relays.
This could be a 240V-coil relay simply in parallel with the heater on circuit 2, so it closes (activates) circuit 1 when circuit 2's thermostat calls for heat.  You would hear a "click" when the relay comes on.
This could also be a mildly more sophisticated but much more versatile 24 volt system.  Here, a common 24 volt thermostat transformer feeds the thermostat.  Then, 24V-coil relays are used on both the heaters on circuit 1 and circuit 2 to switch those heaters on/off.
This last system is quite lovely if you have it, because it allows use of the huge variety of 24V thermostats intended for gas furnaces, from a $15 Honeywell clear up to the Nest.


Searching for -> on Github

Question: How do I escape the > so I can search for all instances of -> in a github repository?
I have attempted using "->" but that still sees the > as an operator. Is there an escape character I can add so that the search will work?
Comment: Has anyone figured this one out?
Answer: GitHub search is based on elasticsearch, which has reserved characters than you can escape.
'>' and '<' are optional operators used for intervals, and it doesn't seem for that character to be escaped (in the way GitHub is using or has configured ealasticsearch).

Searching for -> on Github


The contactor doesn't switch ON during the Off-peak hours (French installation)

Question: My water heater works well in when I set the contactor to "forced mode".  But it doesn't work in "auto mode" (it should switched ON during off-peak period, but it doesn't). (It's in an french house)

In forced mode, there are 230V between terminals 1 and 3 which are connected to the hot water tank
In auto mode and during off-peak hours, there is no tension between terminals 1 and 3, nor between terminals A1 and A2  which should switch one the contactor during the off-peak period.

The contactor connections of my electrical circuit are different from all those I found online :
● The A2 terminal has two red wires:

"A2 left" which is connected to terminal 1 of a "Consumption Indicator" marked "OP" (at the top left)
"A2 right" which is connected to C1 of the main electricity meter counter (and the two terminal C1 and C2 of this electricity meter are in continuity : in the photo the red line indicates this continuity)
The A1 terminal has a blue wire: it goes directly behind the link counter without being connected to C1 or C2

On the divisional counter ( Tywatt30) I have this (it doesn't change during off-peak hours):

Any advice is warmly welcome!
Comment: What is providing the time of day? Since the force works it would be related to a programming of what is peak hours or when it is supposed to turn on.  My mom has off peak metering and she had me install timers on several things that really did not to run during the day. The battery in that unit died but it was still displaying time, could this be the issue?
Comment: The main electricity "smart" meter counter is programmed to send the signal at the right time. (It's on the right part of the pictures. The signal comes from the 2 screws/contactors which are, I dont know why, connected with each other)
Answer: I solved the problem.
The important information is that C2 should beconnected to a live (red) wire (always: during off-peak "HC" and "HP"). So you should aways find 230V between C2 and the blue wire ("phase"). It wasn't the case so I just followed the (black) wire.
The circuit was divided into 2 power switchboard, one a circuit breaker without label was turned OFF. It disconnected the black wire from the live wire.


error creating Fabric environment in VS code with IBM Blockchain Platform

Question: I'm following Hyperledger's tutorial 1 and setting up an Fabric environment. I have all the right dependencies installed with the right versions. My docker is version 19.03.1 and docker-compose is 1.8.0. Using IBM Blockchain Platform in VS code, when I click Local Fabric (Click to Start it can't spin up the docker images. Instead it gives me an error Failed to start Local Fabric: Error: Failed to execute command "/bin/sh" with  arguments "generate.sh" return code 126
I thought at first I needed to setup better permissions so I allowed docker to run without sudo and still get the same error. I've ran the docker images with Hyperledger's First-Network and Fabcar tutorials successfully, but can't get the Blockchain Platform to spin it up. Here is the entire log.
[2019-09-05 12:20:47 a.m.] [INFO] connecting to fabric environment
[2019-09-05 12:20:47 a.m.] [INFO] startFabricRuntime
[2019-09-05 12:20:47 a.m.] [INFO] # don't rewrite paths for Windows Git Bash users
[2019-09-05 12:20:47 a.m.] [INFO] export MSYS_NO_PATHCONV=1
[2019-09-05 12:20:47 a.m.] [INFO] CHANNEL_NAME=mychannel
[2019-09-05 12:20:47 a.m.] [INFO] # teardown any existing network
[2019-09-05 12:20:47 a.m.] [INFO] ./teardown.sh
[2019-09-05 12:20:47 a.m.] [INFO] # Shut down the Docker containers for the system tests.
[2019-09-05 12:20:47 a.m.] [INFO] docker-compose -f docker-compose.yml kill && docker-compose -f docker-compose.yml down -v
[2019-09-05 12:20:47 a.m.] [INFO] Version in "./docker-compose.yml" is unsupported. You might be seeing this error because you're using the wrong Compose file version. Either specify a version of "2" (or "2.0") and place your service definitions under the `services` key, or omit the `version` key and place your service definitions at the root of the file to use version 1.
[2019-09-05 12:20:47 a.m.] [INFO] For more on the Compose file format versions, see https://docs.docker.com/compose/compose-file/
[2019-09-05 12:20:47 a.m.] [INFO] # remove chaincode docker images
[2019-09-05 12:20:47 a.m.] [INFO] (docker ps -aq --filter "name=fabricvscodelocalfabric-*" | xargs docker rm -f) || true
[2019-09-05 12:20:47 a.m.] [INFO] Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json?all=1&filters=%7B%22name%22%3A%7B%22fabricvscodelocalfabric-%2A%22%3Atrue%7D%7D: dial unix /var/run/docker.sock: connect: permission denied
[2019-09-05 12:20:48 a.m.] [INFO] "docker rm" requires at least 1 argument.
[2019-09-05 12:20:48 a.m.] [INFO] See 'docker rm --help'.
[2019-09-05 12:20:48 a.m.] [INFO] Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]
[2019-09-05 12:20:48 a.m.] [INFO] Remove one or more containers
[2019-09-05 12:20:48 a.m.] [INFO] (docker images -aq "fabricvscodelocalfabric-*" | xargs docker rmi -f) || true
[2019-09-05 12:20:48 a.m.] [INFO] Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json?all=1&filters=%7B%22reference%22%3A%7B%22fabricvscodelocalfabric-%2A%22%3Atrue%7D%7D: dial unix /var/run/docker.sock: connect: permission denied
[2019-09-05 12:20:48 a.m.] [INFO] "docker rmi" requires at least 1 argument.
[2019-09-05 12:20:48 a.m.] [INFO] See 'docker rmi --help'.
[2019-09-05 12:20:48 a.m.] [INFO] Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]
[2019-09-05 12:20:48 a.m.] [INFO] Remove one or more images
[2019-09-05 12:20:48 a.m.] [INFO] # remove previous crypto material and config transactions
[2019-09-05 12:20:48 a.m.] [INFO] rm -fr admin-msp/* configtx/* crypto-config/* wallets/local_fabric_wallet/*
[2019-09-05 12:20:48 a.m.] [INFO] # Your system is now clean
[2019-09-05 12:20:48 a.m.] [INFO] rm -f generate.complete
[2019-09-05 12:20:48 a.m.] [INFO] fix_permissions () {
[2019-09-05 12:20:48 a.m.] [INFO]   docker run --rm -v $PWD:/etc/hyperledger/fabric -w /etc/hyperledger/fabric hyperledger/fabric-tools:1.4.2 chown -R $(id -u):$(id -g) ./configtx ./crypto-config ./admin-msp
[2019-09-05 12:20:48 a.m.] [INFO] }
[2019-09-05 12:20:48 a.m.] [INFO] # generate crypto material
[2019-09-05 12:20:48 a.m.] [INFO] docker run --rm -v $PWD:/etc/hyperledger/fabric -w /etc/hyperledger/fabric hyperledger/fabric-tools:1.4.2 cryptogen generate --config=./crypto-config.yaml
[2019-09-05 12:20:48 a.m.] [INFO] docker: Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/create: dial unix /var/run/docker.sock: connect: permission denied.
[2019-09-05 12:20:48 a.m.] [INFO] See 'docker run --help'.
[2019-09-05 12:20:48 a.m.] [ERROR] Failed to start Local Fabric: Error: Failed to execute command "/bin/sh" with  arguments "generate.sh" return code 126

Here is the link to the tutorial, though it shows in VScode https://developer.ibm.com/tutorials/ibm-blockchain-platform-vscode-smart-contract/. I followed it up to the point where you spin up the docker images.
Comment: Did you perform the post install steps by creating the docker group, adding your user to that group and then logging off and logging on again as described here https://docs.docker.com/install/linux/linux-postinstall/  ?
Comment: docker-compose v1.8.0 - that seems like an old version - this VS Code extension requires v1.14.0 or greater.
Comment: @RThatcher yes, that was the issue.
Answer: It's showing permission error, current user can't access the docker engine
Run this command, needs to have $USER defined in your shel
sudo usermod -aG docker $USER

After that give permission to access
sudo chmod 777 /var/run/docker.sock