How to fix this error: cannot find symbol - method setText(java.lang.String)

Question: I am making a seat monitoring system using java PL. I have this method in my ComputerSeats class:
public void occupySeat()
{
    seatOccupied[station-1] = true;
    mtr.showArrayIdVal().setText(stud.showField().getText());
    seat[station-1].setBackground(Color.red);
    occupiedSeatCounter++;
}

the ShowArrayIdVal contains a Jlabel[] object, the value of this label is "Vacant Station", I used setText(stud.showField().getText()) to change "Vacant Station" to the value that I have inputted using JTextField. But then, whenever I compile it, It contains an error which states that it cannot find settext().
Answer: Cant tell exactly without the stacktrace and more code, but my guess is that mtr.showArrayIdVal() doesn't return JLabel instance.
if mtr.showArrayIdVal() returns JLabel[] (array of JLabel objects) you should call it
mtr.showArrayIdVal()[i].setText(stud.showField().getText())

where i is integer and the compilation would pass - of course you must declatre and initialize i.
Answer: If  mtr.showArrayIdVal() is returning a JLabel Object your code should work fine.
I assume that mtr.showarrayidval() is returning array of Jlable objects. so, you should be getting the object on the index and then call setText(...).
   for(JLable jl: mtr.showArrayIdVal()) {
        jl.setText(..)// do what ever you are setting here.
     }

Answer: use mtr.showArrayIdVal()[0].setText(stud.showField().getText());
incase of list
use mtr.showArrayIdVal().get(0).setText(stud.showField().getText());
Comment: does arrays have a get(index) method??, unless you are returning an list of jLabel.. :P
Comment: @subodh.. Still not ok.. I think you should look at some tutorials on using array and ArrayList.. I'll edit the code for you..
Answer:
ShowArrayIdVal contains a Jlabel[] object, the value of this label is
  "Vacant Station"

As you are telling that showArrayIdVal contains JLabel[] array... So, you cannot invoke setText() on an array..
Rather you can iterate over the returnd array, and invoke setText on individual labels..
for(JLabel label: mtr.showArrayIdVal()) {
     label.setText("Your text");
}


Cosets of a subgroup do not overlap

Question: This is a question from the free Harvard online abstract algebra lectures.  I'm posting my solutions here to get some feedback on them.  For a fuller explanation, see this post.
This problem is from assignment $5$.

Prove directly that distinct cosets do not overlap.

Let $H$ be a subgroup of $G$ and let $a$, $b$, and $c$ be elements of $G$ such that $b\not\in aH$ and $c$ is in both $aH$ and $bH$.  Then there are elements $h$ and $h^\prime$ in $H$ such that $c=ah$ and $c=bh^\prime$.  So $ah=bh^\prime$ and $b=ahh^{\prime -1}$.  But $hh^{\prime -1}\in H$ so $b\in aH$.  This contradicts our original assumption. Therefore, there can be no element in more than one distinct coset.
Again, I welcome any critique of my reasoning and/or my style as well as alternative solutions to the problem.
Thanks.
Comment: It looks fine. Another way of viewing this is to place an equivalence relation on $G$: $x \sim y$ if there exists an $h \in H$ such that $x = yh$. The equivalence classes are exactly the left cosets of $H$. You could also view this through [group actions](http://en.wikipedia.org/wiki/Group_action), but it doesn't seem like you're there yet. [I'm not claiming that these are essentially different.]
Comment: Also, maybe it's good to be clearer as to why $b \notin aH$ implies that $aH$ and $bH$ are different. If you worry about that sort of thing then it seems cleaner to prove that $aH \cap bH \neq \varnothing$ implies $aH = bH$.
Comment: I retract my (worthless) seal of approval from earlier. A lot of the right equations are there, but I'm concerned about this $b \notin aH$ thing. Perhaps the argument is: if the cosets are different then without loss of generality assume that $bH \not\subset aH$. So there exists an $h \in H$ such that $bh \notin aH$ and hence $b \notin aH$.
Comment: @jobrien929: I don't like it much; what if you encounter some coset "in the wild", as $bH$, but it's not $b$ that is not in $aH$? If you really want to start that way, it's much cleaner to say: "Let $aH$ and $bH$ be cosets, and assume that $aH\neq bH$; then either there exists $x\in aH-bH$, or $y\in bH-aH$; without loss of generality, assume that $x\in aH-bH$." And go from there. But, really, the **cleanest** way is to say: "Let $aH$ and $bH$ be cosets, and let $x\in aH\cap bH$". Then conclude from this assumption that $aH=bH$ as sets.
Comment: That's the proof. I don't think you'll find an alternative solution, because it's immediate by appealing to the definitions.
Comment: Looks just fine to me.
Comment: On further review, I have to agree that introducing distinct cosets with $b\not\in aH$ is clumsy at best. But is it sufficient to simply say "assume $H$ is a subgroup of $G$ and $aH$ and $bH$ are distinct cosets "?
Comment: The more I go back and read the statement of the problem, the more I wonder what the concept of "distinct cosets" means if you have to start out by assuming they _might_ overlap.. This line of thought is leading me back to the way I originally worded the proof.
Comment: @jobrien929: Since cosets are sets, "distinct" just means that one contains an element the other does not; that said, I think the cleanest way to do this is to proceed not by contradiction, but along the lines suggested by Dylan Moreland.
Comment: @Arturo: Thanks for the shot of clarity.  I was starting to think myself around in circles.  So if I do want to start by saying $b\not\in aH$, then any set that contains $b$ is distinct from $aH$.  Since $b\in bH$, $aH$ and $bH$ are necessarily distinct.  Would that not be a good way to begin the proof?
Comment: @Arturo:  Thanks again.  I was definitely over-complicating things.
Answer: To prove the result at hand, you need to start with two distinct cosets sharing a common element, and prove that the cosets coincide. In saying that, "let $a$, $b$, and $c$ be elements of $G$ such that $b \not\in aH$ and $c$ is in both $aH$ and $bH$", you are assuming that $aH$ and $bH$ are distinct cosets with non-empty intersection and that doesn't mean that $b \not \in aH$ [as of now]. Also, $b \not \in aH$ does not also mean that, $bH \neq aH$ [as of now].
So, I think your proof is faulty here.

I'd fix it this way.
Suppose $c$ belongs to distinct cosets, $aH$ and to $bH$, say
  $$c = ah_1 = bh_2$$
  where $h_1$, $h_2 \in H$. Then $a = bh_2h_1^{-1}$. Any element of $bH$ has the form $bh$ for some $h \in H$ and,
  $$ah = b(h_2h_1^{-1}h) \in bH$$
Since $h$ was arbitrary in $H$, we see $aH\subseteq bH$ .
The reverse inclusion, $bH \subseteq  aH$, follows by a similar argument (using the equation $b = ah_1h_2^{-1}$ instead and arguing similarly).
This proves the claim.

There is a round about way of doing this, which I'll nevertheless mention here: The approach through equivalence relations.
Let $H \subseteq G$ be a subgroup of $G$. Define $\sim$ on $G$ by, $a\sim b$ iff there exists $h \in H$ such that, $a=bh$ for $a,b \in G$. Prove that your notion of cosets coincide with the equivalent classes of $\sim$. Now, you know that distinct equivalence classes are disjoint and hence your result.
Note that this leads you into Lagrange's Theorem in finite groups and in fact, the following is also true.

Let $H \subset G$ such that for all $a,b \in G$, $aH \cap bH=\emptyset$ or $aH=bH$ holds. Then $\exists g \in G$ such that $gH$ is a subgroup of $G$.

In case you have difficulty proving the above result, please let me know.
Hope this helps.
Edited to add @Dylan's viewpoint of this problem from group actions:
Note that the equivalence relation we have defined can be viewed as a group action by looking at the definition of orbits. (i.e.) search for the action whose orbits are the equivalence classes of $\sim$. You'll identify that this action is the left multiplication action.
Comment: @jobrien929 "Distinct" here should mean that you have two sets $aH$ and $bH$ and they are not equal.
Comment: In the comments to the question itself I've started to wonder what "distinct cosets" means if you have to admit the possibility that they might overlap. When I first read Dylan's and your comments, I agreed with you but I think I've come full circle. The only way I can make sense of **distinct** is to have the element that "defines", for lack of a better word, the coset assumed to be outside the coset it's supposed to be distinct from. And I thought this was such a simple problem...

Cosets of a subgroup do not overlap


Is there a safe and compliant way to run consumer UPS power through house wiring to an outlet?

Question: I would like to remove an existing cable from the breaker panel, that feeds a single home run outlet, and wire it to a consumer UPS that I will locate near the panel, through a junction box.
Questions:

To join the power cord from the UPS to the junction box can I put a NEMA 5-15 inlet on the box and use a consumer power cord?
Instead of a NEMA inlet (a) could I do it with an IEC C14 inlet?  (b) could I just insert a consumer power cord into the box with strain relief and splice wires inside the box?  This would all be on the surface near the breaker panel, nothing inside walls but also no conduits.
As a further optional step, if the junction box additionally is fed raw power and I add a switch to bypass the UPS, can I just switch the hot or must the neutrals be switched too?  The grounds?  I assume the UPS input and output grounds are bonded but I don't know about the neutrals.  The inlet hot would never be connected to the raw power hot, but is there still any unacceptable danger in this arrangement?

This question is instructive but the answers focus on the practicality of running new cable from room to room.  My situation is to use existing, to-code, wiring from the basement to the room, and adds the idea of switching to raw power.
Comment: Now I'm wondering what the actual point of this is. Specifically (a) a typical consumer UPS provides automatic transfer with no "gap" - doing all of this means that even if you *anticipate* power loss, you will still end up with a brief power loss when you flip the switch (because it must be break-before-make in a basic setup like this) and (b) a typical consumer UPS provides relatively short-term power (a few minutes to perhaps a couple of hours, depending on power usage).
Comment: Yeah, I was wondering about the Why, as well. All my UPSs do automatic switching when the wall power drops so the computer attached to it never notices that the power goes out. It's that drop in power that causes file damage and, potentially, hardware damage. Having to manually flip a switch defeats the purpose of a UPS. If, OTOH, the goal is to simply have a battery backup for a non-computer system, then by all means, have at! (But I'm still not sure why it needs to be wired into the wall like this)
Comment: Why is a good question but it devolves into why do I want a UPS at all.   I tried to keep that aspect out of my question.  It's more like, if a UPS exists that does all the things I want at a reasonable cost, how might I wire it up.  I'm glad I kept the question narrow and got an answer.
Comment: Why THIS arrangement: I have my modem, router, and other network gear in the basement near the panel, I have a couple of Wireless Access Points elsewhere and my home office in another room (not the basement).   The modem, router, and WAPs won't survive an outage more than about half a second and take minutes to recover.  The office has enough electronics to be worth protecting from dirty power esp from the generator.   Putting aside that I'm not sure how to get all the things I want from a UPS, *if I could get them*, this arrangement provides it to all the desired devices throughout the house.
Answer: Yes.
You can run an isolated electrical line, using normal in-wall wiring methods, from a single inlet to outlets.
The inlet will need to be in the NEMA family.  A C13 inlet won't cut it for at least 2 reasons off the top of my head: first it lacks the necessary ampacity, and second it is voltage-agnostic, and the inlet needs to be keyed to reject a power source of the wrong voltage.
As far as having a built-in switch, same rules apply as for a generator.  You must have exactly one neutral-ground bond in the entire system.  Not zero, not two. ("two" is its own special kind of 'bad').  If the power source bonds neutral and ground, then you must switch neutral.  If it does not, then you must not.
The best bet is to switch neutral, but not bond neutral around the switch - have the isolated circuit draw neutral only from the switch.  These types of switches are expensive, so I'd just do cord-and-plug myself.
You would never have a reason to switch safety ground.
Comment: Should probably clarify (since OP asked, so apparently not obvious, though I think it is once you think about the way a UPS works) that **neutral must be switched** together with hot in a setup such as this one.
Comment: @jay613 I have a hunch you're shopping *on Amazon* because I had the same experience there. Amazon opened its site to third party sellers, and has basically turned into eBay.  Anytime the Chinese make a cheapo or counterfeit thing, 1000 different sellers glut Amazon with listings upranked by fake reviews, and just bury any listings for legitimate product.  I don't have the patience to dig down to page 44 lol.  Best advice: don't buy electrical on Amazon. Better shops will have the junction-box kind.
Comment: @manassehkatz yeah, probably best in most scenarios.
Comment: I accept the advice that neutral must be switched and that doing so is prohibitively expensive ($45 for something off-label that will fit in a standard box, $100 to $200 for anything with "transfer" in its name).   So no switch.  That just means that UPS maintenance requires a brief outage.
Comment: I do not accept however that this is obvious.   On the contrary.  I don't see documentation for any of the mass market consumer UPSs about whether the output is isolated, whether the neutral passes through, or wether the output neutral and ground are bonded.   Some of them have very hazy descriptions about how battery-backed sockets may or may not be fed directly by the input when it is alive.  Because of this lack of information I would keep the output completely isolated.
Comment: @Harper-ReinstateMonica new problem: 5-15P inlets all seem to be designed for mounting directly on the wall of an RV or project, outside any junction box, with their own strain relief.   I'd have to hand-craft a junction box cover.  Closest thing is a cover for a 14-30 outlet, that would require just a little modification, but I know that's not ok.
Comment: Shop harder. Prepend "single-gang" or "double-gang" to "5-15P inlet" and you'll still get a lot of the wrong products, but also some of the right ones. Append -flange -flanged to remove more of the wrong ones.
Comment: @jay613 On the UPS outputs, *that's precisely the problem. You don't know.*  When you don't know, you have to take the more prudent course.  Backfeeding the UPS's neutral output into the panel could do all sorts of interesting things.  And then you have the problem if somebody plugs in a bonded generator, now you have two N-G bonds in the system, and you're one more failure away from a big mess.
Comment: Good answer and good discussion.  I think now I can implement this with an inlet, a reasonably priced DPDT switch from Leviton and an outlet on both sides of the UPS all in a 4-gang box for under $100.   The trick was to find devices and cover plates that match and don't cost a lot.  I'll work on an answer describing the details.
Answer: Here I'm planning a nice implementation of the advice in the accepted answer.  This plan provides raw and UPS power to the basement location and also through existing house wiring to a den outlet.  It includes a UPS bypass switch allowing for UPS service.
The trick was to find a DPDT switch that would switch live and neutral at reasonable cost, and an inlet, both of which would fit in a standard multigang box with some feasible cover arrangement.  I could have done it with sectional box covers for about the same price but this plan uses a standard 4-gang Decora plate.
It's easier to build and looks better.
It's all limited to 15A, which works perfectly for what I'm planning.
The key is two devices I found:

The Leviton 5686-2W switch.  This is a 15A DPDT switch.  It's intended use is to switch 2-pole power between two devices, but it works here.  And this specific model is in Decora profile and costs less than $50.
The Midlite 4642-W recessed inlet.  It's intended use is to connect a knee-height outlet to a shoulder-height TV routed through a power conditioner at the lower level.  But it's perfect here because it completes the project without requiring a special cover plate.

The Midlite inlet requires a deep box so I've included a Raco 698, and I'll also replace the den outlet with a red one and put a switch guard over the switch.
The outstanding problem is to pick a UPS that does all the things I want at reasonable cost.  Probably time for some illusions to be shattered.
Here's the design:
Comment: One of the other problems is that typical (and I am talking name-brand) UPSes will often fail in a mode where they try to switch to battery and can't because the battery isn't up to the task. If it is a true power outage then that's life. If it is a < 1 second outage, it can sometimes result in a computer losing power (because of the recovery time for the UPS to switch back to AC) when if there was no UPS at all, the computer power supply would ride through the power glitch.
Comment: All UPSes suck; most especially all remotely affordable UPSes suck. Some of the lithium battery items work well, but "reasonable cost" is not presently compatible with lithium batteries. With Lead Acid batteries, UPSes are very good at killing the battery, rather than having intelligent and capable charge management. Best I can suggest for consumer-grade UPS is to put the UPS and a much larger battery or batteries into a safe enclosure, as the much larger battery is harder for the UPS to kill (but you can't leave the teminals exposed, due to the way most UPSes work.)
Comment: Because UPS's are made for emergencies only, and the battery is going to die *anyway* of old age in 3-5 years, so if you're having 1-2 outages a year, there's no harm in bottoming the battery 3-10 times in its useful life.  If you had an outage a week, then yeah.
Comment: Basically, you can (pretty much have to) build that from "solar" parts. 300W TSW inverter, way more battery than you think you'll need unless you go for lithium, and a decent/intelligent charger. At which point throwing some actual solar panels at it begins to make sense.
Comment: Keep in mind, the transit time of the switch is not zero.
Comment: @Harper-ReinstateMonica I know that all the electronics I'll be connecting to this can survive an outage of almost half a second, and that this switch will be single digit milliseconds or maybe less.  And I'm not running any actual life support systems here, it's just a nice-to-have to be able to service or move the UPS without cutting off my family's electronic life support.   The more serious issue as I delve deeper into affordable UPSs is that they don't do ANY of the things I thought they would.  More on that in next comment ....
Comment: @Ecnerwal and manassekatz indeed.  I have in my imagination an affordable UPS that runs power always through the battery and an inverter, performs its own battery maintenance, and will give me about 200 to 300 Watts for 45 minutes or so without source power.   I think you all know, what I am discovering, that exactly zero of those features are available on any reasonable home UPS.  Well ... I think it was a good question and the accepted answer is a good one.  This implementation might be good if I can find a UPS that does *something* useful.
Comment: @Ecnerwal this is becoming a whole new question but bear with me while I figure out how to ask it.  An automotive inverter ($50) and some Ryobi lithium batteries could almost work but it would be a big hack.   Then there are some new small lithium-based "generators" for, say $300.   Unlike a $300 "UPS", which tends to have vague or no statements about battery capacity or power conditioning, these $300 "generators" all make clear statements about their current, energy, and conditioning ("pure sine wave") capabilities.  I wonder in fact if a $300 lithium generator might be what I want.
Comment: A REALLY neat trick would be to have all the sensitive electronics fed 24x7 by a lithium backed inverter, but when it loses source power, to CUT POWER to those devices don't really need it like the printer (don't need to print) or laptops (have their own batteries).  What I really want is not a UPS, but a battery-backed power conditioner that DOES INTERRUPT power to selected devices during a source outage.
Comment: Easily accomplished with a relay if you are building a "black box" to do the job. There's also the fact (in my setup, anyway) that several parts of the "stuff fed by UPS" are actually 12V wall-warts (*i.e.* the cable modem), so those devices don't need a UPS if you have an appropriate battery.
Comment: @Ecnerwal *everything* in the basement location is 12V but how do you set things up to bypass the wall warts during an outage?  Or do you not use them at all and just power everything from your own battery?  I'd be worried about some of them having their charging logic in the wall wart, i.e. charging too fast, too slow, or too much if I just plug the device into a 12V battery.
Comment: The "solar kit" stuff is way less of a hack when you use components made for purpose. As far as the batteries, as long as people keep crashing electric cars, I see no reason to pay retail for a lithium battery.  You do need to be "on your game" where the BMS is concerned.
Answer: You could install one of these upstream of the outlet: https://ezgeneratorswitch.com
I am not affiliated with them in any way.


How do I number records returned from a database?

Question: If I have records ordered by date from a database, I would like to add a number corresponding according to how the record is ordered. E.g, if a record was ordered by a given date I would like to add an incrementing number to it:
<code>1). Me
2). You
3). Us
</code>
Answer: Iterate over them with an index. E.g. using http://apidock.com/ruby/Enumerable/each_with_index
Answer: Use index method that is defined in an Array
Comment: it tends to start from zero is their any way around that.


How to draw a border around an NSTexturedSquareBezelStyle button

Question: I noticed the other day that one of my web pages was looking ugly. The buttons on the page looked totally different, based on whether they contained one line of text or two.
After some digging, I've learned that the typical button uses NSRoundedBezelStyle, but it has a fixed height. So, if the text is going to wrap, Firefox (and Chrome and Safari) will change the button to use NSShadowlessSquareBezelStyle which can have a variable height. I'd like to petition the maintainers of these browsers to change this and am researching the best alternative.
After finding the already-filed bug and doing some reading, I suggested that maybe they could use NSTexturedSquareBezelStyle instead. It turns out that in Mavericks it looks almost exactly the same as an NSRoundedBezelStyle button. Same in Yosemite, except that it has no border. Changing setBordered has no effect.
So my question, on behalf of browser developers everywhere: is it possible to draw an NSTexturedSquareBezelStyle button with a border? Or, is there another way around this that all the browser vendors have missed?
Answer: Rewritten Answer
I'm not seeing an NSTexturedSquareBezelStyle button showing up borderless in Yosemite:

This is a stock button dragged from the palette in Interface Builder. I encourage you to post your code since it's likely you're generating your button in code. Here's my own code for generating the same button:
NSButton * anotherButton = [[NSButton alloc] initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 100.0)];
anotherButton.bezelStyle = NSTexturedSquareBezelStyle;
anotherButton.title = @"Line 1\nLine 2";

Proof:

If you're seeing different results under Yosemite, you'll need to post your code. At a guess, you might be initializing your button with -init instead of -initWithFrame:, which can cause all kinds of drawing issues since NSButton is an NSView and therefore its designated initializer is -initWithFrame:. Just a guess though.
Comment: There is a very slight border, but not enough to provide contrast against a white background, or light coloured image. In Mavericks, this button looked exactly like a normal button, which was what I was hoping for. It's just frustrating that there's such an obvious limitation that Apple hasn't addressed in their APIs.
Comment: Aside from the ability to subclass the button cell and override its drawing, of course. ;-)


Specs satisfying firebase_analytics from .symlinks/plugins/firebase_analytics/ios dependency were found, but required higher minimum deployment target

Question: I've just tried to build my flutter application via CodeMagic using VNC Viewer and SSH with no luck.
I have tried to run "pod install" with result:
Analyzing dependencies
firebase_analytics: Using Firebase SDK version '8.3.0' defined in 'firebase_core'
firebase_auth: Using Firebase SDK version '8.3.0' defined in 'firebase_core'
firebase_core: Using Firebase SDK version '8.3.0' defined in 'firebase_core'
[!] CocoaPods could not find compatible versions for pod "firebase_analytics":
  In Podfile:
    firebase_analytics (from `.symlinks/plugins/firebase_analytics/ios`)

Specs satisfying the `firebase_analytics (from `.symlinks/plugins/firebase_analytics/ios`)` dependency were found, but they required a higher minimum deployment target.

[!] Automatically assigning platform `iOS` with version `9.0` on target `Runner` because no platform was specified. Please specify a platform for this target in your Podfile. See `https://guides.cocoapods.org/syntax/podfile.html#platform`.

I have also tried to delete the Podfile.lock and pod install. with similar results. I have also tried to run pod repo update and then pod update with similar results as above.
I have also tried to manually change my Podfile iOS version to 10 without luck.
I've tried various combinations of these commands:
flutter clean
flutter build ios

pod install
pod update
pod repo update
pod install --repo-update

Please any responses will be appreciated
Answer: I initially thought I had tried it with 12 but turns out I must not have. 12 and I was able to solve this problem but my advice to anyone is avoid doing this set up via CodeMagic, it's not fun!
Comment: Plz be more specific about what you mean by "tried with 12"!... What exactly did you do with your 12?
Comment: I tried this with IOS version 12, sorry, I thought this would be obvious
Comment: Ok, that explains the "12" bit. Only the "tried" bit remaining. :) What exactly did you do? You say you "were able to solve this problem"... or do you mean that the problem didn't even occur on iOS 12?
Comment: I'm sorry for the late reply and my brain is now likely forgetting this but I believe it did not occur on 12


Read already opened file

Question: Is there a way to read binary data from a read-only file? I have an Excel worksheet, which might be opened in Excel but I want to open it for read purposes only.
I tried to do it this way:
<code>using (FileStream fileStream = File.Open(filepath, FileMode.Open, FileAccess.Read, FileShare.Read))
</code>
And I am getting

The process cannot access the file 'something.xlsx' because it is being used by another process.

Is there any way to achieve that?
Comment: possible duplicate of [Exception in opening a file that is already open](http://stackoverflow.com/questions/3846646/exception-in-opening-a-file-that-is-already-open)
Answer: Change this argument:
<code> FileShare.Read
</code>
to this:
<code> FileShare.ReadWrite
</code>
You are attempting to deny write access to the file, which is causing your issue as Excel already has it open for writing.
Comment: That did the job. Thanks
Answer: You can't open a file who are already open. Be careful to close your file after open it. And you should verify that you didn't use the file in another software (at the same time)...

Read already opened file


Is this kind of clamp on a braided PVC hose reusable or does it get replaced with a new one when it is removed?

Question: I don't have much experience with PVC hose clamps and have never seen the kind in the photos here. I've only seen the kind with the turn-screw that tightens or loosens the clamp. This one looks like it requires a special crimping tool. To remove it, is it simply pried apart with a flat-head screwdriver?
Comment: That clamp cannot be reused.  But I think you can replace it with an ordinary reusable hose clamp.  It would help if you tell us what this is.  What is it clamped to and where does it go?
Comment: Ya you can definitely replace it with a normal hose clamp.  In fact if the hose fits snugly that's probably adequate.
Comment: It is the water feed hose for a masonry saw. There are two hoses, a larger diameter one that attaches to the water supply (such as a garden hose) and this smaller one (10mm OD) which runs from a stop-valve to a port near the blade.
Answer: They are the single use kind and are replaced with the screw clamps.
I do not know if a screwdriver will be enough to remove it. Maybe add snips/pliers to add twisting/cutting or a nice angle grinder.


Do all dungeons have multiple levels?

Question: When you're entering a dungenon and it shows "Random dungeon name First Level", does that mean there is a second and/or third level as well? I'm pretty sure I go through the entire dungeon but don't see a second level on a lot of them.
Answer: All dungeons that have "Level x" in the name will have at least 2 levels.
Random dungeons that have "Level x" will always have only 2 levels (and normally a resplendent chest on the second level), while story dungeons (like the crater in act 3, or the Cathedral in act 1) can have more (I think 4 might be the highest).
Comment: @Mr.November Ah yes, completely forgot about the cathedral since it's so early, I think it goes up to level 5.
Comment: Level 4 on the cathedral("fifth" level is the Royal Crypt, which isn't randomly generated). Can't think of any that go up to five off the top of my head.
Comment: I'm fairly certain The Cathedral has more than 3 levels.
Comment: Only three "Level X" ones though.
Comment: With one exception: The "Defiled Crypt"s that spawn on "The Shattered Crown" don't have any Level information on their first level, because of them being part of the story themselves (no spoilers here, move along please).
Answer: As Mr.Smooth already said, there are always at least 2 levels on a dungeon with "Level x" in the Name. But not every Dungeon have this in the name, for example the Caverns of the Graveyard on Act 1.
You can ensure that you reached the last level of a random dungeon when there is a stone to port you back to the entrance of the dungeon (I don't know at the moment what they are called.)
The entry to the second level might be in some hidden path, be sure there isn't a little dark spot on the map when you don't find it the first time.

Do all dungeons have multiple levels?


IF and ELSIF in the PL/SQL

Question: I have this code that I write, but the problem is that I cannot use the ELSEIF statement in there and I don't know why, and Oracle Developer doesn't let me to execute it.
Is anyone able to help me with this please ?
DECLARE
  CURSOR p_cursor IS
    SELECT PRODUCT_NAME, PRICE
      FROM PRODUCT
  ORDER BY PRICE ;
  p_row p_cursor%ROWTYPE ;
  p_name VARCHAR2(30) ;
  p_price NUMBER ;
BEGIN
  dbms_output.put_line(RPAD('Product Name', 25, ' ') || 'Price Status');
  dbms_output.put_line(RPAD('-', 24, '-') || RPAD(' -', 14, '-'));
  FOR p_row IN p_cursor
    LOOP
    p_name := p_row.PRODUCT_NAME;
    p_price := p_row.PRICE ;

    IF p_price < 5  THEN
      dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Low');
    END IF;
    IF p_price > 5 AND p_price < 20 THEN
      dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Medium');
    END IF;
    IF p_price > 20 THEN
      dbms_output.put_line(RPAD(p_name, 25, ' ') || ' High');
    END IF;

  END LOOP;
END;

I want to have something like this
IF p_price < 5  THEN
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Low');
ELSEIF p_price > 5 AND p_price < 20 THEN
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Medium');
ELSE
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' High');
END IF;

Comment: You didnt got any error message?
Comment: Your code doesn't cover the case where `p_price = 5`.
Answer: Your syntax is wrong - in pl/SQL it's not ELSEIF, it's ELSIF, without the second E:
IF p_price < 5  THEN
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Low');
ELSIF p_price > 5 AND p_price < 20 THEN
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' Medium');
ELSE
  dbms_output.put_line(RPAD(p_name, 25, ' ') || ' High');
END IF;

Comment: I always find it funny the "correct" syntax just *has* to be a typo where someone left out the 'E' back in the day and it was never caught.  I mean come on, 'ELSIF" ?!.
Comment: Thanks for help, I didn't know, and I though that's the correct way and didn't pay attention to that.
Comment: PL/SQL has its roots in the Ada language, and that's the syntax for the IF statement in Ada.
Answer: You need to use ELSIF, and not ELSEIF.
For example:
vcValue VARCHAR2(10) := 'ABC';

IF vcValue = 'ABC' THEN
    -- vcValue = 'ABC';
ELSIF vcValue = 'DEF' THEN
    -- vcValue = 'DEF';
ELSE
    -- vcValue is not 'ABC' or 'DEF';
END IF;

Here is a link with docuentation about the IF, ELSIF, ELSE statement: Link

IF and ELSIF in the PL/SQL


Move my owncloud data directory (running owncloud 9)

Question: So I have an 14.04 server that I've installed owncloud9 on. Everything works fine. i can connect with a browser and using my phone like a champ. the problem is...i want to change my data directory. I created a small raid1 that i want to use solely for my cloud space. i created and tested so i know the space is working. i saw a video that said you basically just move the data (in my case, /var/www/owncloud/data) to its new spot, direct config.php to its new destination and restart apache2:
sudo mv /var/www/owncloud/data /cloud_space/cloud_data
sudo service apache2 restart
After doing this i can get to the login screen but it says to check for an .ocdata file. files wasn't there. i read that some people were able to just add the file so i tried that and restarted apache. nothing changed. i read that i had to change the permissions so i just opened everything up in the folder for now 777. i went as far as just opening the whole drive to test it when that didn't work but nothing. i haven't seen/read anything else besides this way of doing it. All i want to do is change the data directory. It looked so simple on the video. I've uninstalled and purged owncloud quite a few time trying to get this to work this way and it DOES work up until i start messing with moving it.
Question: Is there a different way to do this? or is there something i have to do besides adding the .ocdata file to it?
Answer: It seems that you somehow copied the data directory without the hidden files (.xxx files)
Please copy the complete data directory. You also have to make sure that the new data directory has the exact same owner and permissions. This is sometimes tricky on a NAS which might not support all permissions. I also recommend to upgrade to Nextcloud because it comes with better security features.
If something is still wring with the permissions then check the webserver logfile or the logfile in the data directory.
Comment: I'm actually looking at next cloud right now. I have changed owner and permissions to match several times. Even just went 777 with no changes.  Is there something besides mv that would do a better job moving data?


Access values from theme with React Styled System

Question: In my React project I am using Emotion and Styled System for my Design System and styling.
In theme.js I have some values (to create a responsive CSS Grid):
  template: {
    xs: {
      rows: 'auto',
      columns: 'auto',
    },
    sm: {
      rows: 'auto',
      columns: 'repeat(2,1fr)',
    },
    md: {
      rows: 'auto',
      columns: 'repeat(4,1fr)',
    },
    lg: {
      rows: 'auto',
      columns: 'repeat(6,1fr)',
    },
  },

How do I access those keys from my theme.js so I can use them like:
<Grid
  gridTemplateColumns={[
    theme.template.xs.columns,
    theme.template.sm.columns,
    theme.template.md.columns,
  ]}
  gridGap="30px"
>

I use already Emotion's ThemeProvider:
import { ThemeProvider } from 'emotion-theming';

<ThemeProvider theme={theme}>

How does this work with Styled System library and what is best practice here?
Answer: You can use the useTheme hook in @emotion/react to get access to the theme object:
function Component(props) {
  const theme = useTheme()
  return (
   <Grid
     gridTemplateColumns={[
      theme.template.xs.columns,
      theme.template.sm.columns,
      theme.template.md.columns,
    ]}
   gridGap="30px"
  >
  )
}

References:
[1] Theming - UseTheme https://emotion.sh/docs/theming#usetheme


Limit of a sequence involving partial sums

Question: I've encountered the following curious sequence. I think the limit is correct from simulations, but I'm getting stuck on how to prove it. Any hints?
Fix $\gamma \in (0,1)$. Then:
$$\sum_{i=n \gamma}^n \frac{n}{i^2} \; \to \; \frac{1-\gamma}{\gamma} \quad \textrm{ as } n \to \infty$$
EDIT: I'm not sure it matters, but for now take $n \gamma$ to mean "the ceiling of $n \gamma$."
Comment: Can you explain what does $$\sum_{i=n \gamma}^n \frac{n}{i^2}$$ mean
Answer: Define new index variable $x$ as $\frac{i}{n}$, so that an index increment of $1$ for index $i$ maps to an index increment of $\Delta x=\frac{1}{n}$.
Now, as $n\to \infty$ (i.e. $\Delta x\to 0$) the summation will tend towards the definite integral,
$$\sum_{i=n \gamma}^n \frac{n}{i^2} =\sum_{x=\gamma}^1 \frac{1}{nx^2}=\sum_{x=\gamma}^1 \frac{\Delta x}{x^2} \to \int_\gamma^1\frac{dx}{x^2}=\left[-\frac{1}{x}\right]_\gamma^1=\frac{1-\gamma}{\gamma}  \quad \textrm{ as } \Delta x \to 0$$


Cannot show ArrayList from Servlet to JSP

Question: I am using servlet and jsp to show Access database.
MainDatabase.java
    public class MainDatabase
    {
        private int proId;
        private String proName;
        private String proQuantity;
        private String proPrice;

        public MainDatabase()
        {
            this.proId = 0;
            this.proName = "";
            this.proQuantity = "";
            this.proPrice = "";
        }

        public int getProId() {
            return proId;
        }

        public void setProId(int proId) {
            this.proId = proId;
        }

        public String getProName() {
            return proName;
        }

        public void setProName(String proName) {
            this.proName = proName;
        }

        public String getProQuantity() {
            return proQuantity;
        }

        public void setProQuantity(String proQuantity) {
            this.proQuantity = proQuantity;
        }

        public String getProPrice() {
            return proPrice;
        }

        public void setProPrice(String proPrice) {
            this.proPrice = proPrice;
        }
    }

MainDatabaseUtil.java
    import org.hsqldb.Database;

    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.util.ArrayList;
    import java.util.List;
    import org.json.simple.JSONObject;
    import org.json.simple.JSONArray;

    public class MainDatabaseUtil
    {
        public static List<MainDatabase> getMainDB() throws Exception
        {
            List<MainDatabase> mainDatabases = null;
            JSONArray payload = null;
            try
            {
                Connection conn = DriverManager.getConnection("jdbc:ucanaccess://D:\\study_materials\\Java\\Resources\\Database\\smsDemo.accdb");
                Statement stmt = conn.createStatement();
                ResultSet rs = stmt.executeQuery("SELECT * from Database");

                stmt.close();
                conn.close();

                mainDatabases = new ArrayList<>();

                //payload = new JSONArray();

                if(rs != null)
                {
                    while(rs.next())
                    {
                        MainDatabase proDB = new MainDatabase();
                        proDB.setProId(rs.getInt("ID"));
                        proDB.setProName(rs.getString("ProName"));
                        proDB.setProQuantity(rs.getString("Quantity"));
                        proDB.setProPrice(rs.getString("Price"));

                        mainDatabases.add(proDB);
                    }
                }

                return mainDatabases;
                //return payload;
            }

            catch(Exception el)
            {
                return mainDatabases;
            }
        }
    }

MainDatabaseServlet.java
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.SQLException;
    import java.util.List;

    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.json.simple.JSONObject;
    import org.json.simple.JSONArray;
    import javax.servlet.*;

    @WebServlet("/MainDatabaseServlet")

    public class MainDatabaseServlet extends HttpServlet
    {
        private static final long serialVersionUID = 1L;

        public MainDatabaseServlet()
        {
            super();
        }

        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            try
            {
                List<MainDatabase> mainDatabases = MainDatabaseUtil.getMainDB();
                request.setAttribute("main_list", mainDatabases);
                RequestDispatcher dispatcher = request.getRequestDispatcher("/MainDatabaseView.jsp");
                dispatcher.forward(request, response);
            }
            catch (Exception el)
            {
                el.printStackTrace();
            }
        }

        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
        {
            doGet(request, response);
        }
    }

MainDatabaseView.jsp
    <%--
      Created by IntelliJ IDEA.
      User: Xenon
      Date: 11/15/2018
      Time: 9:15 PM
      To change this template use File | Settings | File Templates.
    --%>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    <%@ page import ="java.util.ArrayList"%>
    <%@ page import ="java.util.List"%>

        <title>Main Database</title>

Student Table Demo

                ID
                NAME
                QUANTITY
                PRICE

            <c:forEach var="tempData" items="${main_list}">

                    ${tempData.proId}
                    ${tempData.proName}
                    ${tempData.proQuantity}
                    ${tempData.proPrice}

            </c:forEach>

I am using IntelliJ Idea. It's showing that in MainDatabaseView.jsp, it cannot resolve variable main_list.
Current Output: Its showing table column name but no data in it.

Expected output should be showing database value in table view when the program is run.
Please help. Thank you.
Comment: Mihir, check my answer and let us know
Comment: how exactly are you going to the jsp? are you trying to access it directly or through the servlet?
Comment: I am accessing jsp from Servlet. I am using RequestDispatcher in MainDatabaseServlet.java file.
Answer: Call stmt.close(); and conn.close(); after retrieving the values from the ResultSet
https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html

When you are finished using a Statement, call the method Statement.close to immediately release the resources it is using. When you call this method, its ResultSet objects are closed.

If you close the statement before retrieving the result set, the result set will no longer have any reference to the data.
Comment: Thanks. After the update, it still doesn't give the expected output.
Comment: Can you display what it shows? I'm think I'm confused by "Its showing table column name but data in it."
Comment: I have put output image in question, please check.


LED lights occasional quick flicker

Question: I recently replaced 3 incandescent BR40 light bulbs (recessed) with eco smart brand LED's. Shortly after doing so we noticed all 3 simultaneously occasionally, but not regularly, flicker off when the switch is on (just 1 quick flicker - kind of like a flash).
I thought this was due to the old Lutron maestro dimmer which wasn't rated for LED bulbs so I replaced the switch with a new Lutron maestro dimmer that is compatible with LED but the lights still do the quick flicker on occasion. I noticed that often turning on a burner on our electric stove will trigger this quick flicker but it does not happen every time.
The stove is not on the same circuit as the lights. The lights are in a bedroom on the opposite end of the house. To make things more confusing, there's a second set of LED lights (eco smart R20's) in the same bedroom (wired to the same box as the other set but they have their own switch) and they do not ever flicker at all.
I've went as far as to completely replace the dimmer with a standard light switch but that hasn't helped either.
I also do not think the issue is directly related to the stove but rather just a big draw of electricity causes it, though this is the only set of lights that flickers.
The flicker is when the lights are on. No issue if lights are off. The bulbs themselves aren't the issue, they don't flicker anywhere else so I've pretty much ruled out the bulbs and switch/dimmer as potential issues.
In the photos below the problematic lights are wired to the switch on the left.
Any ideas? Thanks a lot in advance!
Comment: Can you post a photo of the inside of the switch box please, and is this flickering a brief flash of ON when the lights are OFF, or a brief flash of OFF when the lights are ON?
Comment: @ThreePhaseEel, OP mentions in comments below it's a dark flash when lights are on. Also provides more details there. Almost seems he has a wiring problem, not a load or bulb problem.
Comment: @ThreePhaseEel just added some photos to the main question. The problematic lights are connected to the switch on the left.
Answer: It is not clear if that flickering occurs when the lamp is switched on or off.
The one-shot flickering - when the Lamp is switched off - with a period time of seconds to minutes is often simply caused by wires running parallel.
If a LED lamp is switched off, still some current can flow through the capacitance between the wires which are inevitable with the usual power cables.
A lamp switch or a dimmer is some kind of bridged by those between - wire- capacitors.
This is a very tiny current, which also flows through switched-off old style incandescent bulbs. But no effect is visible, no low frequency flashing is possible, since these bulbs can not store energy.
But some LED drivers have huge capacitors - elcos-  for smoothing out the rectified net voltage.
The tiny currents in switched- off state will slowly accumulate in those elcos. If the voltage is still low enough, the driver electronic can not start working.
But if a certain threshold is reached, the electronic starts working and thus discharges the energy stored in that elco in a short flash of LED light. Now the elco has much less charges or is even empty and the cycle starts again.
Especially lamps which can be switched from different switches have a higher probability to produce these flashes, since there are more parallel cables involved. F.e., between  2 switches 3 wires run, of which one is always hot, another wire is directly connected to the switched-off lamp. Even if switched off, some tiny current flows between the hot and the floating wire.
A flickering when the lamp is switched on would most likely be a defect  LED bulb which should be taken/sent back to the seller under warranty.
Other possibilities for flickering when switched on:
If other devices produce spikes in the net, the current through the LEDs could drastically increase. Many LED bulbs have simple "capacitor power supplies". There is a capacitor in series with resistors and the LED diodes. A capacitor will decrease its resistance, when the frequency increases. Spikes, which could be produced by motors in pumps, compressors (refrigerator, heat pump), drill machines, vacuum cleaners, garbage disposals, etc. and/or devices with triac power phase controls consist of high frequencies.
The capacitor in the LED power supply is only meant for 50/60 Hertz and will increase the current during the spikes for 2 reasons: higher voltage and higher frequencies, which will result in fast flickerings.
Motors and phase controls have filters to suppress those spikes, but those filters could fail or could be missing in old/cheap devices.
The spikes could be effective only in some places of the network, since a domestical power net is a very complicated network for high frequencies >> 60 Hertz.
The grounding of a domestical power net should be realised in one and only one central location, f.e. near the incomer supply line from the power supply company. If a desktop PC is connected to a HIFI Stereo set with a FM-tuner, a loud 50/60 Hertz humming noise could be heard, which disappears when the cable from the tuner to the socket for the roof-antenna is disconnected.
This double grounding is a huge loop (like a secondary winding in a transformer), which could be also produced by double or even multiple connections between Ground and Neutral.
That ground loop(s) could be antennas for spikes which could be a reason for the LED flickerings as well resp. could increase the probability for flickerings.
Just to mention a trivial reason (switched on case): a loose contact ( f.e. backstabs) could reduce the voltage for the LED below the operating voltage range ( f.e. 90 to 250V). A voltage measurement would yield different voltages for on/off.
If no multimeter is available and the circuit can be loaded with a hair dryer' s power demand, the hair dryer would work with a complete other motor sound compared to the same hair dryer connected to another circuit - if the hair dryer worked at all. And the sound of the hair dryer connected to the lamp circuit would also change if the heating level is changed ( f.e. by pressing the switch for "cold" air).
Also an incandescent bulb could reveal the loose contact by different brightness.
Of course, safety first in all works, especially when the lamp circuit has to be (temporarily) connected with an extension cord to accept the hair dryer.
Comment: I should have stated it's when the lights are on. No issue if lights are off.
The bulbs themselves aren't the issue, they don't flicker anywhere else (I've moved them around and switched them with others I knew worked)
Comment: In that case it could be the combination of the dimmer and the bulbs. The dimmer could work fine with other bulbs, the bulbs could work fine with other dimmers - it is just an unlucky combination which can be diffcult to predict. And other circuits as described by George can disturb the electronic in the dimmer and/or the LED driver in the bulb.
Comment: @xeeka the flicker happens even without the dimmer. I replaced the dimmer with a standard light switch and it still happens
Comment: @Mark I just added some reasons for flickerings without dimmers.
Comment: @xeeka I see, thanks! So it doesn't seem that there's really an easy solution? I also added photos of the switch box to the main question in case there's something obvious that I'm missing in there
Comment: @Mark It would help to switch off every other circuit breaker one by one to check if or when the flickering disappears.
Answer: LEDs are notoriously sensitive to voltage variations...they react INSTANTLY to a short drop in voltage, like a heat pump kicking on, Electric range, pump, etc. Compare that to the old incandescent   bulbs with a filament that had to cool for a bit before they would exhibit  a flicker due to a very short voltage drop.   This is the brave new world, we're gonna have to live with it.
Comment: Isn't it odd that the flicker doesn't happen anywhere else in the house though? I have LED's all over.
Comment: This shouldn't much apply to dimmable LED bulbs since they non-naively refactor the power to provide a variable DC current to the LEDs, and in that process, they buffer the line voltage behind a stable DC output voltage. Cruder supplies used in non-dimmable LEDs (ex: a "capacitive dropper") will pass through noise and spikes as output is a direct factor of input.
Answer: This is likely the result of line noise AND a poor dimmer circuit on the LED bulbs. Cheap dimmers will watch the AC waveform and time peak waveform voltages to divine what level it should be running at since even at way dim, the bulb actually still gets more than enough power to run full-blast.
A spike/drop that cancels or delays the expected 120th/sec voltage peak fools the bulb's timer into thinking a new AC phase control waveform (what a dimmer switch does) has been commanded, so it dims, only to "figure out" it's mistake soon thereafter.
A better way to determine brightness, a technique used by better dimmable bulbs, is to voltage divide the line (with high-ohm resistors) and feed that into an RC lowpass filter. This results in a stable low-voltage DC average of the waveform's available power. That signal level is then used to determine how much DC current to provide the LEDs to achieve a brightness. When a good bulb runs too long of a sample because they used a large filter capacitor, it lags, but too small a capacitor and it flickers/blips, so there's a balance there, and different models use different strategies to varying success.
Comment: Appreciate the info! So trying new bulbs could resolve the issue? If so do you recommend any in particular?
Comment: New bulbs could indeed help. Manufactures change thier lines so often that even if I had a good make+model, there's no guarantee they didn't start skimping the next batch. Sorry to say, it's going to take experimentation, but you can usually find a spot for leftover bulbs...
Comment: I finally got some new eveready led bulbs to replace the ecosmart ones and haven't had any flickering since! Seems like it was indeed the bulbs that were causing the issue so thanks so much for your suggestion! I probably would have never tried a different brand since I tried those bulbs elsewhere in the house without any flickering

LED lights occasional quick flicker


How to make pavucontrol changes permanent?

Question: Because of skype sound issues I installed pavucontrol and I can change settings so the sounds work again with skype. I had to set both (recording&playback of skype) to "built-in Audio Analog Stereo" instead of "Monitor of built-in Audio Digital Stereo (HDMI)", I could only edit it when a skype call was in progress.
But unfortunately after a while not using skype the settings in the pavucontrol return to the default sink "Monitor of built-in Audio Digital Stereo (HDMI)", even though I press the lock sign in pavucontrol ...
How do I make the changes to pavucontrol permanent?
I use Skype 4.008 in Ubuntu 12.04 (AMD64).
Interestingly the "Monitor of built-in Audio Digital Stereo (HDMI)" does not show up in the "Sounds settings" of gnome-control, there is only one sink "Analog output - built-in Audio".
I've uploaded to Pastebin the output from pacmd list-sinks and pacmd list-modules.
Answer: From the question and the audio settings posted in the pastes from the commands list-sinks, and list-modules there may be an issue with a pulseaudio module to restore an output device. Let me suggest further steps to narrow doen the issue:
Temporarily remove modules
We don not know if that helps but we may be able to narrow the issue down if we temporarily removed modules that are in question.
To remove a module issue the following in a terminal:
pacmd unload-module <index>

The present <index> will be listed from pacmd list-modules. Try to unload any single one of the following loaded modules (by index!) to test if it is the culprit:

module-suspend-on-idle (because your issue is associated on idle of Skype)
module-loopback (because you don't need the "Monitor of..." device)
module-switch-on-port-available (unlikely but worth a try)
module-intended-roles (switches to the intended device when a phone call comes in)

The default setting with loading of the default modules will be restored by running
pulseaudio -k

Check for errors
Also you may want to see if there are any errors from pulseaudio in the system log files before your HDMI sink is connected.
Remove user-space configuration
Sometimes we have erroneous configuration settings in the user-specific settings. To overcome this me may try if deleting ~/.pulse helps (it will be recreated on next start of pulseaudio)
mv ~/.pulse ~/.pulse.old
pulseaudio -k # to restart pulseaudio

Generate a pulseaudio log
Another approach would be to check for useful messages to narrow down the issue by generating a pulseaudio log file from running pulseaudio in verbous mode (see here on how to do this).
Let us know of the result to better point you to a permanent solution.
Comment: Thanks again for your help. I did not try your steps, sorry! I found a simple tweak in pavucontrol (see other answer), although it might be only a work-around and not addressing the real problem, it worked so far and I did not encounter any side-effect the past 6 months.
Comment: @Filbuntu: I believe by disabling HDMI-audio, and in case you do not need this, you will have a stable workaround here. Thanks for sharing this :)
Answer: A simple configuration setting helped me so far (half a year) on Ubuntu LTS 12.04. In pavucontrol in the last tab "configuration", I have two "Built-in Audio" section where I can choose a profile. The first one had "Digital Stereo (HDMI) Output" as profile. I changed this to "Off" and I had the above described problem not anymore. Here is a screenshot:


Is there a chart showing all unit upgrade paths in Civilization 5 Brave New World?

Question: Is there a chart showing the upgrade paths for the units? Something like
Warrior → Spearman → Pikeman...
for all of the units, similar to the chart on this site for vanilla and for Gods and Kings.
Answer: I made a basic version which is generated directly from the game files, and includes all unique units:
(click on the image for a larger version)

Notes:

Each column represents one era.
Dotted lines represent upgrades by ruins.
Grey lines represent special UU upgrade paths.
The unit "combat type", listed under the unit name, controls which promotions are available to it.
Missiles and non-combat units cannot be upgraded and are omitted from the chart for brevity.
Comment: @DanRasmussen a Python script to extract the data from the game data files and [Graphviz](http://www.graphviz.org/) for laying out the graph.
Comment: +1, graphviz. (Why didn't you export it as svg though?) Also if you have some control on the Graphviz output, you could try make the Scout-Archer edge more evident by changing the edge to (say) `scout:e -> archer:e`
Comment: @badp good idea, but ended up using the `minlen` attribute, worked well.
Comment: What did you use to generate this?
Comment: @Oak, you must be a good game programmer or the 'other one' (the good game hacker and crack maker) +1 though.=D
Comment: Thanks a lot for this effort and awesomely useful product, bro.
Answer: I made my own chart for this:

Link to the spreadsheet


CSS Grid - using grid-template-columns without creating empty div's

Question: I want to create a screen where there is only one div, who is
centered and takes 33% of the screen in size. Both right and left to it is empty.
What I do is :
.loginScreenContainer {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
}

And create 3 elements which two are empty.

Empty

Actual Content

Empty

It feels awkward.
Is there another way?
Answer: Just add grid-column: 2 to your content. Then the content will be in the correct column.

.loginScreenContainer {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}
.content {
  grid-column: 2;
}

Actual Content

Here's a great guide for a lot of css-grid properties: https://css-tricks.com/snippets/css/complete-guide-grid/
Comment: Thank u. Very helpful
Answer: You don't need to use grid. You can do this using width and margin.
HTML

Actual Content

CSS
.loginScreenContainer {
    width: 33%;
    margin:auto;
}

Check this out
https://jsfiddle.net/tb9dqz07/1/


Is Lemmings on Game Boy actually completable?

Question: Feeling nostalgic, I decided to dig out my old copy of Lemmings on Game Boy. However, I soon remembered why I never completed the Mayhem section - level 4 appears to be completely impossible due to a bug in the game.
The full layout is the same as Fun 21 listed here. This time I get 14x Climber and 14x Digger. I need to save 14/14 Lemmings. But when the Lemmings climb up the spiral pattern, this happens:

The Lemmings fall through the platform! And unfortunately the fall is too high so they go splat. After ages trying to find a workaround, I found some levels codes online (above link). Incidentally many pages only gave codes up to this level so obviously had the same problem. I'm guessing the passwords I found were extracted from the game's code.
I was going fine until level 16, which also appears to be unsolveable. I am supposed to get a climber to loop round anti-clockwise from the top then left-to-right along the bottom and back up:

However, my climber cannot climb up those diamond objects - he climbs about halfway and falls back down. There are not enough Builders to bridge the gap. (I get: 1x Climber, 14x Floater, 3x Builder, 8x Basher, 3x Digger.)
So my question: Are these levels actually solvable? And is this a known issue with the game? I couldn't find any information online.
Comment: Just brought some memories back to me regarding this game too. I could never get past... oh, which level was it again... Mayhem 4!!! Never realised there is a bug, I wonder how much time I spent trying to crack that one :(
Comment: Level 4 seems to be solvable: http://www.youtube.com/watch?v=S4phv8Pct3c&feature=related, that is on NES and they don't fall through the platform so possibly the gameboy version is bugged... Can't find anything about level 16 though
Comment: Based on your description, my guess would be *no; the collision detection is too buggy*. *Maybe* you can muddle your way through Mayhem 4 by telling your lemmings to start digging the very instant they get to the top of that wall, and somehow have enough climber skills left to stop them at the right time, but even if that is *theoretically* possible, it would almost surely be very difficult to pull off, and I see absolutely no hope for Mayhem 16.
Answer: Gonna go ahead and answer this. Based on the comments above it looks like the Gameboy version of Lemmings is buggy and it is not possible to complete those levels.
The NES version is basically identical and does not have the same issues with these levels. There are also numerous other bugs in the Gameboy version (which have workarounds) plus some graphical glitches.
That likely puts pay to any chance of it appearing on the 3DS eShop, too...
Answer: What region version of Lemmings were you playing? I'm guessing PAL, as it seems these levels were adjusted in the US release. I just played through the game without encountering any problems (beyond my own stupidity), but the lemming powers were different than described.
Mayhem 4 (3 builders, 8 diggers) =

Mayhem 16 (1 climber, 14 floater, 6 builder, 8 basher, 3 digger) =


construct a string and use it to call a variable

Question: This is probably a dumb question but I have to call one of 30 or so global variables by constructing the variable name to be called from another information. However when i do that it treats it as a string. Any ideas on how to make this work?
eg something like this:
<code>Public gsNewYork As String

public sub Getinfo

dim lslocation as string
dim a as string = "New"
dim b as string = "York"

lslocation = "gs" + a + b
lblLabel.text = lslocation
</code>
Any ideas on how to construct the variable name and have it identified as the variable name?
Comment: Sounds like an enum might work for you.  If not, you may need to use reflection.  Neither are probably good answers, hence the comment.
Comment: I looked at reflection and I found it too hard to figure out. Im going to close this and rephrase to question as there has to be a better way to do this.
Answer: The most common solution to this problem is to store your variables in a Dictionary, where the strings you build are the key.


Date SQL Between

Question: I need to sort the result of my SQL Query by date with a WHERE.
I want to know how can i get the result between the actual date and 6 month before.
Something like
BETWEEN actual_date
AND actual_date - (operator) 6 month

Thanks
Comment: Hi, You should approve a answer if one of them was correct.
Answer: Try this
SELECT * FROM table
WHERE actual_date BETWEEN DATE_ADD(Now(),INTERVAL -6 MONTH) AND Now()

Had a inital error, since its 6 months back, the lower date should be first.
Comment: It would make more sense from a readability point of view to use [`DATE_SUB`](http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-sub) with a positive interval
Comment: Wow im a bit embarrased as i never used `DATE_SUB`, i Always added a - for subtraction. Guess habits are hard to kick. But yes, for readability `DATE_SUB` makes more sense. Upvoted Niels's answer.
Answer: You can do this:
WHERE mydate BETWEEN DATE_SUB( NOW(), INTERVAL 6 MONTH) AND NOW()

Date_sub information
Comment: Need to switch the dates there as between now and 6 months in the past returns nothing.
Answer: i am not in front of a MySQL Terminal but this should work
select
  *
from
  yourtable t
where
  /* Greater or equal NOW */
  r.date >= NOW()
  /* Smaller or equal than 6 months ago */
  r.date <= DATE_SUB(NOW(), INTERVAL 6 MONTH)

Answer: SELECT * FROM table
WHERE actual_date BETWEEN DATE_ADD(actual_date,INTERVAL -6 MONTH) AND actual_date

or

SELECT * FROM table
WHERE actual_date BETWEEN DATE_SUB( actual_date, INTERVAL 6 MONTH) AND actual_date

Date SQL Between


V is linear transformation from $\mathbb{R^3}$ to $\mathbb{R^2}$

Question: $V$ be space of all transformation from $\Bbb{R^3}$ to $\Bbb{R^2}$ under usual addition and scalar multiplication .
Now, what is $\dim{V}$ ?
I am using the fact that in how many ways a basis of $\Bbb{R^3}$ can be used under two binary operation "+,×" to get a element of $\Bbb{R^2}$. Am I right? Please, give me clue!
Comment: If u will use all possible combination u may not get dimension.May be The no. Of independent combination u will have to make for basis.
Comment: Note that this is the same as the space of $2\times 3$ matrices i.e. $M_{2\times 3}$ which is isomorphic to $\mathbb{R}^6$.
Answer: Slightly more general:

a linear transformation $\mathbb{R^n} \to \mathbb{R^m}$ is equivalent to a $m \times n$-matrix $M_{m,n}$;
the space of matrices $M_{m,n}(\mathbb{R})$ form a vector space and from the standard basis, it is clear that its dimenion is $mn$.

Your question follows as a specific case.


Exposing Extension methods in WCF datacontract

Question: Is it possible to expose extension methods on objects which are data contracts in WCF?
Here is an example:
<code>[DataContract]
public class Customer
{
    [DataMember]
    public int ID { get; set; }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public Product CurrentProduct { get; set; }

    public Customer DeepCopy()
    {
        //Do Something else. For example just return a new instance
        return new Customer();
    }
}

[DataContract]
public class Product
{
    [DataMember]
    public int ID;

    [DataMember]
    public int Name;
}
</code>
In the customer class there is a deep copy method. How do I expose this to the client?
Comment: Can you give more information on what you are looking for? Are you wanting to create an extension method for a specific type, data contracts in general, or somehow get the extension method across the wire?
Comment: how about showing what you want to extend, and maybe the answer will be how to implement that without trying to extend a serialized type.
Comment: Why do you need that?  Why not have the client(s) new up the Customer if they need one, but in reality, since this is WCF, Customer will be created by the service and given to the client or vice versa.  Why do you need the DataContract to do that?
Comment: @Mark W. I don't want to create a new in the deepCopy. thai just to show an example I did that. Lets say I am doing some reflection and copying the members to a new object and then returning that object.
Answer: No, you can only expose properties in a WCF DataContract, not methods.
Answer: You can almost do this using the "Reuse types" feature. Unfortunately for your case, it only allows the reuse of types which are actually used by the service as input or output parameters. Your class holding the extension methods will be a static class and will therefore not appear as an input parameter nor as a return type.


Apt-Get using Apt-Cacher NG fails to fetch packages with hash sum mismatch

Question: I have a machine who is using Apt-Cacher NG running on another machine as caching proxy.
When I try to run sudo apt-get update I get the following errors:
W: Failed to fetch gzip:/var/lib/apt/lists/partial/it.archive.ubuntu.com_ubuntu_dists_oneiric-updates_main_source_Sources  Hash Sum mismatch
W: Failed to fetch gzip:/var/lib/apt/lists/partial/it.archive.ubuntu.com_ubuntu_dists_oneiric-updates_main_binary-amd64_Packages  Hash Sum mismatch
W: Failed to fetch gzip:/var/lib/apt/lists/partial/it.archive.ubuntu.com_ubuntu_dists_oneiric-updates_universe_binary-amd64_Packages  Hash Sum mismatch
W: Failed to fetch gzip:/var/lib/apt/lists/partial/it.archive.ubuntu.com_ubuntu_dists_oneiric-updates_main_binary-i386_Packages  Hash Sum mismatch
E: Some index files failed to download. They have been ignored, or old ones used instead.

The directory /etc/apt/sources.list.d is empty.
To fix that I have already tried the following with no success:
Solution 1:
sudo rm -fr /var/lib/apt/lists
sudo mkdir -p /var/lib/apt/lists/partial
sudo apt-get clean
sudo apt-get autoclean

Solution 2:
sudo apt-get update -o Acquire::http::No-Cache=True

Any suggestion?
Comment: This happens also on machines which don't use Apt-Cacher NG. In those cases Solution 1 fixes the problem.
Comment: I have seen this behaviour sometimes. Running **sudo apt-get update** several times consecutively helped in this case but I don't know why, never investigated this issue more closely.
Answer: I would suggest to switch away from APT-cacher-ng and check out Squid-deb-proxy.
APT-cacher-ng has proven to be very buggy in my experience and tons of bug reports are outstanding. Only recently it has been proposed again to get unblocked in Debian now that some major bugs are squashed. For Ubuntu I've switched to Squid-deb-proxy a long time ago and I don't regret it. It's a great alternative and the best APT-cacher I've come around.
For Squid-deb-proxy, just install the package squid-deb-proxy and add allowed destination domains in a new file in /etc/squid-deb-proxy/mirror-dstdomain.acl.d. As a bonus, clients can auto-discover caching-enabled machines in the local network by having the squid-deb-proxy-client package installed.
Answer: You can fix this right now by running:
http://your-cache-server:3142/acng-report.html?abortOnErrors=aOe&byPath=bP&byChecksum=bS&truncNow=tN&incomAsDamaged=iad&purgeNow=pN&doExpire=Start+Scan+and%2For+Expiration&calcSize=cs&asNeeded=an#bottom

This will delete all the broken files in your cache.
To make this permananet, have a look at https://www.unix-ag.uni-kl.de/~bloch/acng/html/maint.html#auto-cleanup
Basically, you can set up the daily cache cleanup cron to do a full checksum match on your entire cache. This will catch all the bad sizes and any other corruption and clean out those files. I edited /etc/cron.daily/apt-cacher-ng and added the following after the comments:
export ACNGREQ="abortOnErrors=aOe&byPath=bP&byChecksum=bS&truncNow=tN&incomAsDamaged=iad&purgeNow=pN&doExpire=Start+Scan+and%2For+Expiration&calcSize=cs&asNeeded=an"

This is equivalent to clicking all the expiry options on the maintenance page except "Skip header checks..."
Comment: This was the only answer that got rid of the error on my systems!
Comment: I think you may need a `?` at the start of your export string.
Answer: Suggestion 1
sudo rm /var/lib/apt/lists/*gzip*
sudo rm /var/lib/apt/lists/partial/*gzip*
sudo apt-get update

Suggestion 2
sudo rm -f /var/cache/apt/partial/*
sudo rm -f /var/cache/apt/*.deb
sudo apt-get update

Suggestion 3
sudo touch /etc/apt/apt.conf.d/no-cache
sudo nano /etc/apt/apt.conf.d/no-cache

And paste this in:
Acquire::http {No-Cache=True;};

Now try:
sudo apt-get update

Comment: Thanks but none of the three worked.
Comment: Worked like a charm setting no-cache to true! Thanks a million! :)
Answer: I have been fighting VERY frequently (1 in 50 downloads) with "Hash Sum Mismatch" and "Invalid Header" errors using apt-cacher-ng on Ubuntu Precise 12.04 LTS since the day of upgrading the distro. Ubuntu Precise uses apt-cacher-ng version 0.7.2-1, to date there are MANY bug fixes to this software, and the newer version: 0.7.26-1 is much more stable.
I have installed the Ubuntu Quantal version of apt-cacher-ng from packages.ubuntu.com, which is version 0.7.26-1.
I highly recommend grabbing the future/testing version of apt-cacher-ng, and manually installing this newer package.
Answer: My upgrades would always almost succeed -- 95% of the files would download through the proxy, leaving maybe the last ~100 files failing with 'hash sum mismatch', and none of the proposed solutions would ever work.
And then, just for grins-and-giggles, I moved 01proxy over to 01proxy.ng, ran aptitude update, then update-manager and selected the distribution-upgrade.  It proceeded to download the remaining files from archive.ubuntu.com (~70M rather than ~1G), and the rest of the upgrade went smoothly.  After rebooting, I moved 01proxy.ng back to 01proxy, and everything was back to normal.
I've done this twice now, once on the proxy server itself and once on a client, and both succeeded just beautifully after failing (at that 95% mark) when going through the proxy.
Answer: Removing the /var/cache/apt-cacher-ng/download.virtualbox.org folder did help me to fix the problem with Failed to fetch ... Hash Sum mismatch on apt-get update that prevented virtualbox-4.3 package from Oracle server.
Answer: Suggestion 4
Running sudo apt-get update && sudo apt-get upgrade -y on the Apt-Cacher NG server may fix the problem. You need to do that every time the problem occurs.
Suggestion 5
Sometimes the problem is on the mirror: changing the mirror in /etc/apt/sources.list, both on the server and the clients, may fix this problem.
Answer: You can also remove the whole repository folder
rm -r /var/cache/apt-cacher-ng/<repository_folder>

where the package with the hash sum mismatch is stored.
On next apt request a new folder with clean hash sum will by automaticaly created by apt-cacher-ng.


modify discrete LinearSegmentedColormap

Question: I'm a climatologist and often plot anomalies of e.g. temperature fields using a "blue-to-white-to-red" colormap. To make the plots more readable, I discretize the colormap in a certain number of levels (bins) with a function which I "found" in the Internet (but I don't really understand it):
Something like this:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib.colors as cols
from numpy.random import randn

def cmap_discretize(cmap, N):
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1) ]
    # Return colormap object.
    return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

cmap_disc= cmap_discretize(cm.RdBu_r,12)

fig, ax = plt.subplots()
data = np.clip(randn(250, 250), -1, 1)

cax = ax.pcolor(data, cmap=cmap_disc)
plt.colorbar(cax)

plt.show()

This results in

Now I want to set the two middle-most segments (i.e. those two close to 0) to white because I don't want to show very small deviations.
My goal would be to end up with something similar to this:

I really have a hard time to figure out how these LinearSegmentedColormap can be modified accordingly. Can somebody help me with this?
Comment: Please read: http://matplotlib.org/api/colors_api.html#matplotlib.colors.LinearSegmentedColormap which has a clear description of how the color maps work.
Comment: And you might get some traction using the code at http://stackoverflow.com/questions/15399095/stacking-colormaps/15399564#15399564 and passing in two descritized color maps.
Answer: The function you have found builds a data structure (in cdict) for defining a LinearSegmentedColormap with segments that don't perform any interpolation (i.e., y1 in row i is always identical to y0 in row i+1, and this gives the constant, or discrete, color "bands").
cdict is a weird data structure, a dictionary which contains the keys 'red', 'green' and 'blue'.  The value for each of these keys is a list structure containing tuples of the form (x, y0, y1).  x is the color map coordinate, which is some floating point number between 0 and 1.  y0 is the color value on the "left" side of x, and y1 is the color value on the "right" side of x.  Colors are linearly interpolated in bands between consecutive values of x; if the first tuple is given by (0, A, B) and the second tuple by (X, C, D), then the color of a point t between 0 and X will be given by (t - 0) / (X - 0) * (C - B) + B.
For your purposes, your function works pretty well, but needs to have the "bands" near the middle of the color map replaced with a white color.  You can try something like the following:
def cmap_discretize(cmap, N):
    colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
    colors_rgba = cmap(colors_i)
    indices = np.linspace(0, 1., N+1)
    cdict = {}
    for ki,key in enumerate(('red','green','blue')):
        cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1) ]
    # "white out" the bands closest to the middle
    num_middle_bands = 2 - (N % 2)
    middle_band_start_idx = (N - num_middle_bands) // 2
    for middle_band_idx in range(middle_band_start_idx,
                                 middle_band_start_idx + num_middle_bands):
        for key in cdict.keys():
            old = cdict[key][middle_band_idx]
            cdict[key][middle_band_idx] = old[:2] + (1.,)
            old = cdict[key][middle_band_idx + 1]
            cdict[key][middle_band_idx + 1] = old[:1] + (1.,) + old[2:]
    # Return colormap object.
    return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

Comment: this is great, but I still need to work it through to understand it
Comment: I'm a little leary of reaching in squashing the colors like this because you are making the color map non-linear in a really non-transparent way.
Answer: Lets start by walking through the code you have
# get some uniformly sampled data, padded out a bit
colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
# sample the input colormap at our sample points
colors_rgba = cmap(colors_i)
# indices for color map
indices = np.linspace(0, 1., N+1)
# dict to pass to the LinearSegmentedColormap
cdict = {}
# loop over the colors
for ki,key in enumerate(('red','green','blue')):
    # in each color assemble a list that looks like
    #[...,
    # (indices[2], colors_rgba[1,ki], colors_rgba[2,ki]),
    # (indices[3], colors_rgba[2,ki], colors_rgba[3,ki]),
    # ....]
    cdict[key] = [ (indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1) ]
    # The color for a number between [indices[2], indices[3]] are interpolated
    # between colors_rgba[2,ki] and colors_rgba[2,ki] which are the same
    # which is what gives you the discrete blocks.
# Construct and return colormap object.
return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

So now the question is how to create a color map with a 'doubled' white band in the middle.  I would change the function bit to have it take in two color maps (top and bottom)
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
import matplotlib.colors as cols
from numpy.random import randn

def cmap_double_discretize(cmap_bottom, cmap_top, N, split=.5):
    """
    Generates a descritized color map using two existing color maps

    Parameters
    ----------
    cmap_bottom : cmap
        The bottom cmap

    cmap_top : cmap
        The top cmap

    N : int
       The number of bins in each color map

    split : float, optional
       Where to join the maps, must be in [0, 1]
    """
    # sanity check
    assert split < 1 and split > 0
    # set up the data structure
    cdict = {lab: [] for lab in ('red','green','blue')}
    # do this in a fancy loop to a) save typing, b) make it easy to
    # retrofit to do arbitrary splits
    for cmap, ends in zip((cmap_bottom, cmap_top), ((0, split), (split, 1))):

        # run over the _whole_ range for each color map
        colors_i = np.concatenate((np.linspace(0, 1., N), (0.,0.,0.,0.)))
        # map the color
        colors_rgba = cmap(colors_i)
        # get the values
        indices = np.linspace(ends[0], ends[1], N+1, endpoint=True)

        for ki,key in enumerate(('red','green','blue')):
            cdict[key].extend((indices[i], colors_rgba[i-1,ki], colors_rgba[i,ki]) for i in xrange(N+1))
            #    print cdict
    # Return colormap object.
    return cols.LinearSegmentedColormap(cmap.name + "_%d"%N, cdict, 1024)

red_cdict = {'red': [(0, 0, 1),
                     (1, 1, 0)],
            'blue': [(0, 0, 0),
                     (1, 1, 0)],
            'green': [(0, 0, 0),
                     (1, 1, 0)]}

blue_cdict = {'blue': [(0, 0, 1),
                       (1, 1, 0),],
            'red': [(0, 0, 1),
                    (1, 0, 0)],
            'green': [(0, 0, 1),
                     (1, 0, 0)]}
red_cmap = cols.LinearSegmentedColormap('red', red_cdict, 1024)
blue_cmap = cols.LinearSegmentedColormap('blue', blue_cdict, 1024)

test_cmap = cmap_double_discretize(red_cmap, blue_cmap, 6)
# these don't actually go to white!
# test_cmap = cmap_double_discretize(cm.get_cmap('Reds_r'), cm.get_cmap('Blues'), 6)

fig, ax = plt.subplots()
data = np.clip(randn(250, 250), -1, 1)

cax = ax.pcolor(data, cmap=test_cmap)
plt.colorbar(cax)

plt.show()

You can easily modify this to split across more than two color maps.
Comment: this also works, but does not support predefined colormaps with white in the middle (like bwr,seismic,RdBu,RdGy...). Still many thanks for your effort

modify discrete LinearSegmentedColormap


Touch pad only works when mouse is connected Kubuntu

Question: I am using Kubuntu 16.04.02
When I connect the USB mouse I can use the touch pad but as soon as I unplug it it stops working. When I go into touch pad from settings it says no touch pad is connected?
Isn't that strange?
From touch pad settings this is the pad: HID 04d9:1133
The command that shows hardware shows the touch pad ONLY when the mouse is connected. As soon as it's gone the device ID is gone with it!
Things went worse after updating the kernel, thinking it might bring driver updates. I'm on 4.11 now.
Comment: run updates, uplug the mouse, keep it upluged and reboot (ctrl-alt-delete arrow keys enter).  Does it still not detect your trackpad? Open the mouse&touchpad settings screencap it (Alt-Print Screen) and add it to your post. thanks
Comment: untik "Tap-and-Drag gesture" in the first and both "Disable-touhpad when typing" and "Disable taps and scrolling only" in the second and do OK. does this have better results?
Comment: i think your kubuntu is entirely broken. Are you adamant about using KDE?
Comment: ah yeah! that could be it!
Comment: OK I'll do that and post the screenshot when I do.
Comment: @tatsu here it is.
Comment: Sadly it stopped working and the message displayed is: "No touchpad found".
Comment: When I downloaded this ISO I checked the checksum and it was a match, installing it went smooth and other than the touchpad issue everything is fine so far.
Comment: @tatsu

I did have a hardware issue were the pins on of the touch pads were twisted due to bad installation (took my laptop apart and didn't bring it back right) so maybe the straightened copper connectors have something to do with this?
Comment: They worked fine for months, we act up now? I don't feel like taking my laptop apart so it stays the way it is for now @tatsu
Comment: @tatsu Do you have a command or something that could clear the doubts for sure? I'd like to grant your answer as the answer that fixed my issue.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/58732/discussion-between-muaad-elsharif-and-tatsu).
Comment: sorry I'm about to go to bed :S
Answer: The issue isn't software related!
Taking apart my laptop I discovered that one of the pins on the touch pad connector was bent. By fixing it and reconnecting the pad works fine - for now-.
Thanks for all the help.


Oracle DB Audit ALL

Question: I have a 5TB large database.
I want to audit everything , really everything.
First of all, I tried with AUDIT ALL, but according to Oracle's document AUDIT ALL does NOT audit everything...
I know that this statement must be executed in order to start auditing db:
 alter system set audit_trail=db,extended scope=spfile;

But what else should I do to start auditing all the SQL statements that users execute?
Answer: You need not to use the AUDIT feature if you only want a view on user queries (SELECT, UPDATE, INSERT) on your database.  $AUD contains rather DDL statements, whereas V$SQL contains only DML statements.
A very simple solution is to use another view: V$SQL. You can extract duration and lot of useful info from it.
Useful example:
  SELECT * FROM v$sql vv
   WHERE lower(vv.SQL_TEXT) like '%delete%'
     AND vv.PARSING_SCHEMA_NAME like 'A_SCHEMA%'
ORDER BY  vv.LAST_ACTIVE_TIME desc;

V$SQL lists statistics on shared SQL area without the GROUP BY clause and contains one row for each child of the original SQL text entered. Statistics displayed in V$SQL are normally updated at the end of query execution.

Long running queries  are updated every 5 seconds. This shows the impact of long running SQLs while they are still working.
Comment: So basically there's no difference beetwen records stored in the view V$SQL and $AUD table ? Except if I was interested in auditing sessions (conection times etc), which I am not interested at.
Comment: That's not what I'm saying. For **your purpose**, you could check what's in `V$SQL`. It is different. `$AUD` would contain ***DDL statements***, whereas `V$SQL` would contain ***DML statements***.

Oracle DB Audit ALL


How does one obtain these achievements in Black Mesa: Source?

Question: Taken from enter link description here

Quantum Capacitance: Overcharge it anyway.
Remote Detonation: Kill a Barnacle with a Satchel.
Unified Coupling Theorum: Help the Barnacle and Headcrab find true
  love. [0/10]
Permeable Infrastructure: Use the alternative path in the Office
  Complex.

I'm having trouble with these four in Black Mesa: Source.  I have already completed all the other achievements, but these have stumped me.
What exactly is a Barnacle?  Do they mean Headcrabs?  I'm very confused.
Comment: Hi, Retrosaur. Asking about *every single achievement* is a bit much for a single question. As such, I'm reverting to your earlier revision, which listed only 4. Even that's pushing it a bit, though; you might have better luck asking 4 distinct questions, talking about what you've tried already, etc, if you're hoping to get the best answer.
Comment: Barnacles are the alien monsters that you see attached to the ceiling with a long slender grey "tongue" stretching down nearly to the floor, which they use to reel in their prey (or you). I haven't gotten the achievement but I suspect you need to get headcrabs to walk or jump into the barnacle's "tongue".
Answer: Quantum Capacitance
Hold the secondary fire button of the Tau Cannon weapon (right-click, by default). The weapon will then overcharge if you hold it for some time (you will know this as your health and shield will take a hit).

Remote Detonation
This is a barnacle

And here is a satchel charge:

Kill one of the former, with the latter.

Unified Coupling Theorum
Lead a headcrab to a barnacle's tentacles and have the barnacle eat/kill the headcrab.

Permeable Infrastructure
There's an alternate route through the vents in the Office Complex chapter. You need to go through that route to get this achievement. See this Youtube video on how to find that route:


What implants are available to increase researching ability?

Question: I've recently started playing Neocron, because Reakktor has just launched a new server called Titan.  I'm playing with some friends, and I am making a researching alt spy to identify my unidentified tech parts.
I have noticed there are some implants that increase researching, like Advanced Nerves 3 and the like, but was wondering if there is a complete list of all implants that increase researching.  I'm also wondering how much researching I will need to reliably research these parts without failing?
Answer: The way that researching in Neocron works, is that you need at least the same amount of skill points in the researching skill as the tech level of what you're trying to research, but until you have double the tech level in research there is always a possibility of failing the research. The more research you have, the less chance of failing.
For example, if you're trying to research a TL90 item, you need to have at least 90 skill points in researching, but require 180 or more before you're guaranteed not to fail the researching process. The possibly outcomes of failure range from simply 'failing', to destroying the item you were trying to research, so it's always better to have as much researching as possible.
There is a good item database over at techhaven.org which contains detail on every item in the game and where you can get it from.
Specifically for researching, there are the following implants:
Brain Implants

Tech Haven CPU: +9.91 research
Special Sciences CPU: +7.86 research
Area MC5 Hawking CPU: +10.45 research

Backbones

Advanced Nerves v1: +2.4 research
Advanced Nerves v2: +4.13 research
Advanced Nerves v3: +5.92 research

Tradeskill Gloves

Machina Research Glove: +13.92 research

This means that with the best available implants in the game, it is possible to get +48.06 to your research from implants. In addition to implants there is a drug called 'Blue Fairy' available from the Black Dragon Faction Supply Manager which adds an additional +9.06 research for five minutes.
For more information on researching, there is a guide to being a researcher on the techhaven.org website.


Testing redux connected component

Question: I have the following connected component in React-Redux
export class IncrementalSearch extends React.Component {

    constructor(props) {
        super(props);
        this.onSearch$ = new Subject();
        this.onChange = this.onChange.bind(this);
    }

    componentDidMount() {
        this.subscription = this.onSearch$
            .debounceTime(300)
            .subscribe(debounced => {
                this.props.onPerformIncrementalSearch(debounced);
            });
    }

    componentWillUnmount() {
        if (this.subscription) {
            this.subscription.unsubscribe();
        }
    }

    onChange(e) {
        const newText = e.target.value;
        this.onSearch$.next(newText);
    }

    render() {
        return (

                <input
                    className={styles.incSrchTextBox}
                    type="text" name="search" id="searchInput" placeholder="Search.."
                    onChange={this.onChange}
                />

        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    onPerformIncrementalSearch: (searchText) => {
        dispatch(performIncrementalStoreSearch(searchText));
    }
});

const IncrementalSearchComponent = connect(null, mapDispatchToProps)(IncrementalSearch);
export default IncrementalSearchComponent;

I'm now trying to write a unit tests for the connected component.  I'm using Jest, Enzyme, and Sinon.  So far this is what my unit test looks like
it('calls \'onPerformIncrementalSearch\' when the user types in something', () => {
    const mockStore = configureStore();

    const onPerformIncrementalSearchSpy = sinon.spy();
    const mapStateToProps = null;
    const mapDispatchToProps = {
        onPerformIncrementalSearch: onPerformIncrementalSearchSpy
    };

    const mappedProps = { mapStateToProps, mapDispatchToProps };

    const incrementalSearchWrapper =
        mount(
            <Provider store={mockStore}>
                <IncrementalSearchComponent
                    onPerformIncrementalSearch={onPerformIncrementalSearchSpy}
                    props={mappedProps}
                    store={mockStore}
                />
            </Provider>
        );

    //find the input element
    const searchInput = incrementalSearchWrapper.find('#searchInput');
    searchInput.node.value = 'David';
    searchInput.simulate('change', searchInput);
    expect(onPerformIncrementalSearchSpy.called).toEqual(true);
    // onChangeSpy.restore();
});

However, when I run this test, I get the following error

TypeError: Cannot read property 'bind' of undefined

How do I fix this?
Answer: Testing connected components can be a huge pain.  I find that it's more trouble than it's worth to try to wrap your components with a Provider to give them access to the store.
Instead, I would just export the component, mapStateToProps, and mapDispatchToProps and test them individually.  Your app will still work the same if you export the connected component as the default.
Dan Abramov (Co author of Redux) suggests this approach in this comment
I would also suggest looking into enzyme shallow rendering instead of using mount when testing connected components.
Comment: bill's point is that you don't need to test the `connect` function since that's not your code. Your code is all in the unconnected component and `mapState/DispatchToProps`. If you test those, then you've tested all of your logic.
Comment: But the connected component is more than just mapStateToprops and mapDispatchToProps, there is other logic in the component which I need to test.  Tehrefore how do I test this?
Comment: You can still test the logic in the component through this approach.  You would just have two `exports`.  One would be to export the connected component `export default connect ...` and you would import this in your app through `import { default as myComponent }`.  You would also export the unconnected component like `export class myComponent` and import in your test like `import { myComponent }`.  Then you can test all of the logic in the component without having to worry about accessing the store and testing the connected component.
Comment: [This answer](https://stackoverflow.com/a/35578985/6326906) might help to explain further.
Comment: maybe I am not understanding something, I have exported both connected and unconnected component, the issue comes when I just try to mount or shallow the connected component just to test its logic.  Is there a working example that I could use?
Comment: You will still have the same issue if you try to mount (or shallow mount) the connected component.  Exporting the connected component is strictly for accessing it in your app, not in your tests.  I would just import the unconnected component and test that.  You should still be able to test all of the logic in the component, minus that `connect` works.  If there is some other logic that you must test through mounting the connected component, then this approach is not right for you.
Comment: Yes this is my whole concern, I have some logic in the connected component which I want to test, and for some reason I cannot get it to mount.

Testing redux connected component


Swapfile does not load when hibernating in Ubuntu 18.04

Question: Many articles seem to have been dedicated to installing hiberate under Ubuntu 18.04 x64 / Kernel 4.20. But, I still cannot get my system loading the swapfile after hibernation. This is what I did:

Install hibernate GNOME extension

Create new swap file of 16GB

sudo swapon --show

NAME      TYPE SIZE USED PRIO
/swapfile file  16G   0B   -2

Update etc/default/grub

GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=/dev/sda1
resume_offset=15140864"

Update to kernel 4.20

After these actions the systems does go into hibernation but, never loads the old system state.
Is there anything I am overlooking here?
Comment: Are swap files supported for hibernation now? At least a while ago, you could only hibernate to swap partitions, but swap files were not supported. Not sure if that has changed yet.
Comment: Check `/etc/initramfs-tools/conf.d/resume` is configured, then do `sudo update-initramfs -c`. Why the offset in your GRUB line? Report back to @heynnema
Answer: I had the same situation here. I've just tried with UUID and it worked like a charm:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash resume=UUID=d2175d30-aee3-418b-8c3f-d4ae61d13b3f resume_offset=2367488"
Hope it helps,
Br,
Martin