New home owner need help installing dimmer switch

Question: Trying to install a dimmer switch in our living room. There are 4 lights connected to two switches. We want to replace one of the switches with a dimmer.
Turned off power and wired it up last night. Everything was working perfectly until we turned off the other switch and heard the circuit breaker trip in the basement. When we flipped the circuit breaker back on nothing in the living room turned on. We uninstalled the dimmer switch and everything is working fine now.
There is probably a lot that I am missing here but curious if anyone can help me understand what I am doing wrong.
Here is the dimmer we purchased.
https://www.farmandfleet.com/products/1080927-leviton-trimatron-universal-rotary-dimmer.html
and I think these are the lights. There are 4 of them.
https://www.farmandfleet.com/products/678881-ge-2-pack-65-watt-soft-white-r30-indoor-floodlight.html
Comment: Can you provide a picture of the inside of the switch box?
Comment: I can when I get home. Funny you mention that I think there was only three wires and the 3-way dimmers seem to have 4 wires? Def need to read the directions I think.
Comment: Yes, can you provide photos of the insides of the junction boxes involved please?
Answer:
connected to two switches

That's what we call a 3-way switch. The traditional configuration of a 3-way switch has something like:

Incoming Power
Switch 1
Switch 2
Lights

The key is that between those 2 switches there are (not counting ground) 2 wires, but really 3 wires with one of them either only connected to one of the switches (hot going to 2nd switch or switched hot coming back from 2nd switch) or not connected to either switch (neutral just coming along for the ride). With typical cables using standard colors (black/red/white), that can get very confusing, because the white wire is not neutral!
The end result is that a dimmer, timer, motion detector or smart switch on a 3-way installation needs to know how to handle that extra wire. Some handle it just like ordinary switches, some require a special compatible switch to replace the 2nd switch, some use just one wire, etc.
The device you purchased is R00-RNL06-0TW, which is for a basic, single switch installation. Leviton makes a similar device, the R00-RDL06-0TW. In a quick search, it seems that Farm & Fleet, Home Depot (note: Home Depot typically has installation manuals online which makes this type of thing easy to figure out) and Leviton all have slightly different model #s available. But the common - and key - denominator is RDL06 instead of RNL06.
If you get something else (fancier Leviton or another manufacturer), make sure it specifically lists "3-way" and "LED". Whatever you get, read the instructions carefully before you get started. 3-way switches can be confusing.
And just in case you think "I'll just figure out some other way around this and avoid another trip to the hardware store", NO. When I was a kid, we had 3-way switches in the dining room and installed a timer. The timer was not designed for 3-way switches. For many, many years (probably until the house was torn down a few years ago to build a new house), we were told "don't touch the other switch, it will mess up the timer!" Of course, there was no internet to consult in those days :-(
Comment: Thank you for the detailed response. I appreciate your help.
Comment: Just looked at the bulb link - **SWITCH TO LEDS!** You'll save short-term (and long-term) in energy costs and long-term in bulb costs - i.e., if you buy decent LEDs they'll typically last 10x as long as incandescents.
Answer: Quick update 3-way plus led support dimmer switch
worked! Thanks for the help everyone.
Here is what I bought
https://www.homedepot.com/p/Leviton-Trimatron-600-Watt-Single-Pole-3-Way-Universal-Push-On-Off-Rotary-Dimmer-White-Light-Almond-R00-RDL06-0TW/301370408#product-overview


Water heater builds up excessive pressure only when reheating the tank. What's going on?

Question: The pressure release valve on my water heater will trip predictably after a significant amount of hot water has been used (e.g. dishwasher, laundry, long shower) releasing 16 oz or less of water.  It only happens if a sizable quantity of hot water is used and the water heater as to heat up cold water, if the tank is sitting idle full of hot water it won't happen.
I've noticed that after using a lot of hot water, if you wait about 10-15 minutes then turn on the hot water there's almost an explosive blast of pressure as the water heater is heating cold water.  Letting a faucet drip hot water usually prevents the pressure release valve from going off.
It's an electric water heater over 6 years old with a cold water expansion vessel.  The temperature is set to about 110 and I've been slowly ratcheting it down to see if it affects this pressure build up, it doesn't.
What's going on?
Answer: Your expansion tank has likely failed or isn't large enough for your hot water tank. Expansion tanks have a bladder in the middle that ensures it is half full of air and needs to be periodically checked to be sure it's properly pressurized. These bladders eventually fail, allowing water to enter the air side, which eliminates the ability to absorb the expanding water.
Replacing the expansion tank may be a simple process if it's just screwed on. With the water shutoff, you unscrew the existing tank, pressurize a new tank, apply some plumbing dope to the threads, and screw the new tank on.
Comment: @MyItchyChin They have a valve on the air side of the tank, same as for a car or bicycle tire. Match the home water pressure if possible (you can get a pressure gauge to measure it at a garden faucet) or just pump it up to 60psi or so.
Comment: Sounds simple enough, what is entailed in pressurizing the new tank?
Comment: Get a bigger expansion tank if possible. The one my builder installed failed in the third year, also at my neighbors'.
Comment: @BMitch Thanks for the info!  I put a tire pump on the existing tank and it registered 0 psi.  I couldn't get it to pump up with a tire pump.  Do you think I'd have better luck with a compressor or should I just replace the tank?
Comment: @MyItchyChin, when the bladder goes, you should still be able to measure some psi from the water supply before shutting off the water. Pressurizing with a failed bladder won't work since you're trying to pump up all the pipes in your home rather than half of the tank. My guess is that the valve itself has failed, maybe rusted from water passing the bladder. Best option is likely to replace the entire tank.


How can I load state from en EnvironmentObject in SwiftUI?

Question: So I am working on a view where I want to load state from an EnvironmentObject which acts something like a database.
I would like to achieve something like this:
class MyDB: ObservableObject {
    func getName(_ id: RecordID) -> String { ... }
    func getChildren(_ id: RecordID) -> [RecordID] { ... }
    var didUpdate: PassthroughSubject...

}

struct TreeView: View {
    let id: RecordID
    @EnvironmentObject var db: DB
    @State var name: String
    @State var children: [RecordID]

    func loadState() {
        self.name = db.getName(id)
        self.children = db. getChildren(id)
    }

    var body: some View {
        Text(self.name)
        List(self.children) { child in
            TreeView(id: child)
        }
        .onReceive(self.db.didUpdate) { _ in
            self.loadState()
        }
    }

}

So basically I would like to just pass the id of the node in the tree view to the child view, and then load the state from this environment object with the loadState function before the view is displayed.
Is there any way to achieve this?  For instance, is there some kind of lifecycle function I could implement which will be called after the environment is bound?
Or for example can I implement loadState inside a custom init?
What would be the idiomatic way to handle this?
Comment: It seems strange that you're both giving the view knowledge of your persistence layer and then creating `@State` properties fetched from the DB. Either reference the properties straight from the DB without making them `@State` or inject those state properties when the view is created so it doesn't need knowledge of your persistence.
Comment: So the part which is missing from this picture is that I would like to reload the state based on update events which are coming from the db object.  I have added an example to the code sample above.
Comment: Your type is MyDB in TreeView right?
Comment: Get rid of the State variables and use the Published wrapper in the ObservableObject and instead of those functions returning the values have then assign the Published variables.
Answer: I have provided an explanation here if you want to check it out.
You will need to pass your MyDB instance using .environmentObject(myDBInstance) on a parent view, so all children views can read from the environment through @EnvironmentObject.
Comment: So I understand how to use EnvironmentObject - what I am struggling with is how to load data from the environment object
Comment: Your code should work just fine, but a few improvements: a) add .onAppear { loadState() } after the List; add also .onChange(of: db) { _ in loadState() } - works if MyDB is Equatable, c) wrap your view elements in a VStack (I believe you didn't put it just for this example)
Answer: Try using a different approach, such as the following code,
where children and name are published var of MyDB, and
the functions just load the data into those.
// for testing
struct RecordID: Identifiable {
    let id = UUID().uuidString
    var thing: String = ""
}

class MyDB: ObservableObject {
    @Published var didUpdate: Bool = false
    @Published var children: [RecordID] = []
    @Published var name: String = ""

    func getName(_ id: RecordID) {
        // ...
        name = "xxx"  // whatever
    }

    func getChildren(_ id: RecordID) {
        // ...
        children = [RecordID(), RecordID()] // whatever
    }
}

struct TreeView: View {
    @EnvironmentObject var db: MyDB
    @State var id: RecordID

    var body: some View {
        Text(db.name)
        List(db.children) { child in
          //  TreeView(id: child)  // <-- here recursive call, use OutlineGroup instead
          Text("\(child.id)")
        }
        .onReceive(db.$didUpdate) { _ in
            loadState()
        }
    }

    func loadState() {
        db.getName(id)
        db.getChildren(id)
    }

}

struct ContentView: View {
    @StateObject var myDB = MyDB()
    let recId = RecordID()

    var body: some View {
        TreeView(id: recId).environmentObject(myDB)
    }
}


Why this Joda offset cannot get daylightsaving right

Question: I have the following code using Joda to calculate offset for any given day, for example
int offset = DateTimeZone.forID("EST").getOffset(new DateTime(2013,8,1,1,1));

this will give me offset of -18000000. But for:
 int offset = DateTimeZone.forID("EST").getOffset(new DateTime(2012,12,1,1,1));

this also give me offset of -18000000.
Looks like daylightsaving is not taken in to calculation. Anyone knows why? Thanks.
I am using Joda-time-2.3
Answer: You are explicitly telling it to ignore Daylight Savings Time.
EST is Eastern Standard Time, notably different than EDT, which is Daylight Savings Time.
Instead, try using the ID US/Eastern, so
DateTimeZone.forID("US/Eastern")

A complete list of the time zones available can be found here. US/Eastern is an alias for America/New_York
Comment: Either Canonical ID or Alias should be fine. The issue with EST is that EST stands for Eastern Standard Time. Eastern Standard Time is not the same as colloquially saying "Eastern". Eastern Standard Time is explicitly Eastern time when it is not daylight savings. In order to get Daylight savings, I'd recommend using either US/Eastern or America/New_York.
Comment: I checked the list. Isn't EST also under the list? So should we use "Canonical ID" or "Alias"?
Answer: You're expected to give a time zone ID - not the abbreviation for "half" a time zone. So for example, America/New_York is one example of a time zone ID for Eastern Time (there are others, for time zones which may be like New York now, but weren't historically, etc).
import org.joda.time.*;

class Test {
    public static void main(String[] args) {
        DateTimeZone zone = DateTimeZone.forID("America/New_York");
        System.out.println(zone.getOffset(new DateTime(2013,8,1,1,1)));
        System.out.println(zone.getOffset(new DateTime(2012,12,1,1,1)));
   }
}

Output:
-14400000
-18000000

You should stay away from the abbreviated forms as far as possible - they're ambiguous (non-unique) and usually only define one part of a time zone. Ick.
Comment: Quoting your [OMG PONIES!!! (AKA HUMANITY: EPIC FAIL)](http://codeblog.jonskeet.uk/2009/11/02/omg-ponies-aka-humanity-epic-fail/) presentation:  "Yes, CST is there three times. Once for Central Standard Time in the US – which is UTC-6. It's also Central Standard Time in Australia – where it's UTC+9.30. It's also Central Summer Time in Australia, where it's UTC+10.30. I think it takes a special kind of incompetence to use the same acronym in the same place for different offsets."


Is it possible to be banned for dying too often?

Question: I saw a thread on the LoL forums that was talking about being banned for dying too often. I know that "feeding" as in intentionally giving the opposing team free kills is a reportable offense, and I understand why. However I can't really see any point in banning someone for dying too often assuming they are legitimately trying.
I'd really appreciate some clarification.
Comment: More of a solution to dieing often: Play more carefull, stay back, you will get the exp anyway at your tower and focus on picking off last hits on minions. Once a opponent loses there tower do not venture further in there land, especially not alone. And finally, stay behind you stronger team members in bigger fights, let them take the aggro. Or play with a tanky character, it's good to die first with a tank in a team fight.
Comment: By the way, congratulation! Your post is the 1200th on gaming.stackexchange concerning League Of Legends!!!
Answer: No you can't be banned because you're bad. And that's a relief, you'll often play against people much stronger or much weaker than you, and you will get destroyed, or will destroy them. The amount of time you die doesn't matter.
What matter are:

Flaming, threatening your teammates.
Going AFK several times during a game
Leaving a game.
Let you killed by the opposite team... on purpose.

The last one is quite complex, becase if you play with someone much weaker than you, he'll make some stupid moves and will die alone. For a well-trained player, it will look just like feeding on purpose but it's not.
In the end, try to play correctly, most of the players can see the difference between feeding on purpose, and playing bad. You won't get banned for playing bad.
Comment: "This option is mainly used as a placebo for players that are acting negatively"
Comment: Reports for "Unskilled player" doesn't count :-D. I just do it to troll my friends ^^
Comment: @Hystic Actually, it just lowers your matchmaking ranking a little bit, if a lot of people report you for unskilled player. And it helps figuring out who is an abusive reporter.
Answer: In general, you don't have to worry about being banned for being bad. If you die because you're trying hard but you make a mistake, don't fret it. The only thing that can cause you to get banned is if you die intentionally.
The thread you linked is specifically talking about a player who is known to frequently use a strategy known as "Proxy Singed". This is a particularly strange case, because of the way Proxy Singed works. For teammates who don't know what you're doing, it looks like you're feeding. This can easily be countered by effective communication. You should also make sure you have buyin frim your team before you do any unorthodox strategies like this.
The main strategy of Proxy Singed is to run behind the enemy tower and farms the minion waves before they can even get to a useful part of the lane for the other team. Since Singed is the best at "proxy" farming like this, this will generally push your lane down very fast. Eventually, Singed will farm both the top and mid minion waves from inside the enemy base.
The obvious downside to this is that you don't really have a means to escape if the jungler or someone else comes to gank you, so you wind up dying a lot. You farm minions so much faster than anyone else in the game, however, that it makes up for the gold lost and gold given to the other team in many cases, as long as you never get a kill. If you kill an enemy champion, it will reset how much gold you are worth. Proxy Singed is effective because you are tanky, not worth a lot of gold, and hanging out in an area that is far away from important resources for the other team.
To your teammates, however, if they don't understand the strategy, it will look like you're just being an idiot and feeding.
I felt like it was important to explain the confusion for this specific case and how the player got banned despite trying his best because it really is a unique case and you shouldn't feel threatened that this will happen to you. If you want to try something extremely unorthodox like proxy Singed, warn your team about it. Otherwise, don't worry.


Is the material behind my wall's surface asbestos?

Question: I'm a bit worried. All the wall is peeled off and its an old house. Just trying to renovate.
Comment: A question like this calls for more information. Please revise to list location, age of home, etc.
Comment: Like Isherwood said, age, location of the home would be great as would any other pertinent information (e.g. asbestos used elsewhere in the home...)
Comment: Hello, and welcome to Home Improvement. We won't be able to give you a definitive answer from out here. And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Answer: It's probably just plaster. However, a test kit is the only reliable indicator.
Comment: I'm unaware of asbestos having ever been used in a domestic setting as a *loose* wall material, +1 (utility rooms notwithstanding, but that comes in sheets). What would be hard to tell is if it's rock lath or asbestos paneling. If the substrate crumbles like plaster, it's probably plaster. If it doesn't, it's one of the other two. But it doesn't matter if the OP is going to just patch the wall; only if they're going to demo it.


Python extending with - using super() Python 3 vs Python 2

Question: Originally I wanted to ask this question, but then I found it was already thought of before...
Googling around I found this example of extending configparser. The following works with Python 3:
$ python3
Python 3.2.3rc2 (default, Mar 21 2012, 06:59:51)
[GCC 4.6.3] on linux2
>>> from configparser import  SafeConfigParser
>>> class AmritaConfigParser(SafeConfigParser):
...     def __init__(self):
...         super().__init__()
...
>>> cfg = AmritaConfigParser()

But not with Python 2:
>>> class AmritaConfigParser(SafeConfigParser):
...       def __init__(self):
...           super(SafeConfigParser).init()
...
>>> cfg = AmritaConfigParser()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: must be type, not classob

Then I read a little bit on Python New Class vs. Old Class styles (e.g. here.
And now I am wondering, I can do:
class MyConfigParser(ConfigParser.ConfigParser):
      def Write(self, fp):
          """override the module's original write funcition"""
          ....
      def MyWrite(self, fp):
          """Define new function and inherit all others"""

But, shouldn't I call init? Is this in Python 2 the equivalent:
 class AmritaConfigParser(ConfigParser.SafeConfigParser):
    #def __init__(self):
    #    super().__init__() # Python3 syntax, or rather, new style class syntax ...
    #
    # is this the equivalent of the above ?
    def __init__(self):
        ConfigParser.SafeConfigParser.__init__(self)

Comment: In your example you don't need to define an `__init__()` in the subclass if all it does is call the super class' `__init__()` (in either Python 2 or 3) -- instead just let the super's be inherited.
Comment: Useful reference with corrected link: http://amyboyle.ninja/Python-Inheritance
Answer:
super() (without arguments) was introduced in Python 3 (along with __class__):
super() -> same as super(__class__, self)

so that would be the Python 2 equivalent for new-style classes:
super(CurrentClass, self)

for old-style classes you can always use:
 class Classname(OldStyleParent):
    def __init__(self, *args, **kwargs):
        OldStyleParent.__init__(self, *args, **kwargs)

Comment: -1. This answer didn't clarify anything for me. In Python 2, `super(__class__)` gives `NameError: global name '__class__' is not defined`, and `super(self.__class__)` is erroneous as well. You *must* provide an instance as a second argument, which would suggest you need to do `super(self.__class__, self)`, but that is **wrong**. If `Class2` inherits from `Class1` and `Class1` calls `super(self.__class__, self).__init__()`, `Class1`'s `__init__` will then *call itself* when instantiating an instance of `Class2`.
Comment: @jpmc26: in python2 you get this error because your trying to call `__init__()` without argument on the unbound super object (which you get by calling `super(self.__class__)` with only one argument), you need a bound super object then it should work: `super(CurrentClass, self).__init__()`. Don't use `self.__class__` because that will always refer to the _same_ class when calling a parent and therfore create an infinite loop if that parent also does the same.
Comment: @CristiFati This isn't about the `__class__` member but about the [implicitly created lexical `__class__` closure](https://docs.python.org/3/reference/datamodel.html#creating-the-class-object) which always refers to the class currently being defined, which doesn't exist in python2.
Comment: To clarify a point, I get `TypeError: super() takes at least 1 argument (0 given)` when trying to call `super(self.__class__)` in Python 2. (Which doesn't make a lot of sense, but it demonstrates how much information is missing from this answer.)
Comment: `__class__` (member) also exists in *Python2*.
Answer: In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.
Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.
In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).
If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):
class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.
What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.
So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).
So by doing nothing in C, you end up calling both, which is what you want.
Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.
class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:
class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.
Comment: `Notice how both base classes use super even though they don't have their own base classes.` They have. In py3k every class subclasses object.
Comment: This is the answer I was looking for, but didn't know how to ask.  The MRO description is good.
Answer: In short, they are equivalent.
Let's have a history view:
(1) at first, the function looks like this.
    class MySubClass(MySuperClass):
        def __init__(self):
            MySuperClass.__init__(self)

(2) to make code more abstract (and more portable). A common method to get Super-Class is invented like:
    super(<class>, <instance>)

And init function can be:
    class MySubClassBetter(MySuperClass):
        def __init__(self):
            super(MySubClassBetter, self).__init__()

However  requiring an explicit passing of both the class and instance break the DRY (Don't Repeat Yourself) rule a bit.
(3) in V3. It is more smart,
    super()

is enough in most case. You can refer to http://www.python.org/dev/peps/pep-3135/
Answer: Just to have a simple and complete example for Python 3, which most people seem to be using now.
class MySuper(object):
    def __init__(self,a):
        self.a = a

class MySub(MySuper):
    def __init__(self,a,b):
        self.b = b
        super().__init__(a)

my_sub = MySub(42,'chickenman')
print(my_sub.a)
print(my_sub.b)

gives
42
chickenman

Answer: Another python3 implementation that involves the use of Abstract classes with super(). You should remember that
super().__init__(name, 10)

has the same effect as
Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it.
Hence super()gets translated to  Person and then if you include the hidden self, you get the above code frag.
from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass

class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass

a = Man("piyush", "179")
print(a.showIdentity())


Getting no reverse match at /post in django

Question: I have been facing this issue. And I have a url name post-page-detail but then also getting error please
See the error screenshot below.

My html page

{{post.tractor_company}} || {{post.tractor_model}}

{{post.implimentaion}}

{{post.farmer}}
Uplode Date : {{post.date}}

URLs.py
from . import views
urlpatterns = [
    path("",views.starting_page,name = "starting-page"),
    path("posts",views.posts,name = "post-page"),
    path("posts/<slug:slug>",views.post_detail,name="post-detail-page"),
]

View.py
from django import forms
from django.contrib.auth.models import User
from django.shortcuts import render, redirect ,get_object_or_404
from .models import Post, Farmer
# Create your views here.
from django.http import HttpResponseRedirect
# Create your views here.
def starting_page(request):
    return render(request,"tractor/index.html")

def posts(request):
    qs = Post.objects.all()
    context = {"posts":qs}
    return render(request,"tractor/all-post.html",context)

def add_post(request):
    pass

def post_detail(request,slug):
    indentified_post = get_object_or_404(Post,slug=slug)
    return render(request,"blog/post-detail.html",{'post':indentified_post})

i am iterating through posts and using the post-detail.html page
all-post.html.
{% load static %}

{% block title %}
All Tractors
{% endblock  %}

{% block content%}

All Tractors

      {% for post in posts %}

        {% include "tractor/includes/singlePost.html" %}
      {% endfor %}

{% endblock %}```

Comment: could you please show your views.py ?
Comment: @amadousow added view.py
Answer: Try this:
{% url 'post-detail-page' post.slug as post_detail_url %}

Let me know if it worked.
Comment: No it's Not working
Comment: @Max_len I have made an edit. Check it
Comment: Yeah error is gone but when I am clicking on box it's not taking me to post detail page. Just doing refresh on same page.


Symfony: Unable to replace alias "swiftmailer.mailer.default.transport.real" with actual definition ""

Question: I've encountered a strange error when installing libraries from composer.
After running 'composer install' and installing all libraries this is what I get in the terminal:
Updating the "app/config/parameters.yml" file

Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

[Symfony\Component\DependencyInjection\Exception\InvalidArgumentException]
  Unable to replace alias "swiftmailer.mailer.default.transport.real" with actual definition "".
Strangely on my MAC dev (mac air, homebrew php and mysql) setup I don't have this issue. However on this machine (windows 10, Yoga 900) when installing the the project from my github repo, I've had this issue.
I can't run 'php bin/console debug:container' without the error occuring again.
Versions:
Symfony 3.0.9
SwiftMailer v5.4.3
I've googled the issue and had no luck finding an answer but found related issues:
https://github.com/symfony/swiftmailer-bundle/issues/59
Error after updating symfony/swiftmailer-bundle to 2.2.5
Any help greatly appreciated, unfortunately I don't have the knowledge to solve this one.
Answer: Same issue here, my problem was that I do not set mailer_transport in parameters.yml


"PermissionError: [Errno 13] Permission denied:" In flask application

Question: Problem:
I'm getting the following error

"PermissionError: [Errno 13] Permission denied:
'/home/[user]/daily_events_20200722.txt'

from this line of code:
with open(settings.HOME_PATH + f'daily_events_{time.strftime("%Y%m%d")}.txt', 'a') as fileobject:

What I've tried:
This is the fourth "location" I've tried.  The others I tried were the directory where the init.py file is and the parent of that directory (e.g. /var/www/FlaskApp/FlaskApp/ and /var/www/FlaskApp/), my "home" directory, and /tmp.
I should mention, here, that configuring the app to write to the /tmp directory eliminated the permission error, but no file gets written.  There is no error, the code continues on its merry way through that section of my code as if it wrote the file, and then errors in a different place (unrelated error) further down.

UPDATE:  I think the answer to why no file gets written to /tmp is
that apache2 redirects the output, as described here:
https://unix.stackexchange.com/questions/167835/where-apaches-tmp-located,
so I'm going to abandon writing to /tmp as a solution and concentrate
on the permissions problem.
It would be SO helpful if I could understand what credentials apache2
and my flask app would be using when it tries to write the files.

I've also fiddled with the ownership and permissions (chmod) for all three of the attempted directories (e.g. user:rwx, group:r-x, others:r-x originally, but tried others:rwx.  Also tried root and  [user] as owner (chown) on all the mentioned directories and their parents).
I've also tried changing the FlaskApp.conf file in /etc/apache2/sites-available/ from:
<VirtualHost *:80>
    ServerName [serverip]
    ServerAdmin admin@[mydomain].com
    WSGIScriptAlias / /var/www/FlaskApp/FlaskApp.wsgi
    <Directory /var/www/FlaskApp/FlaskApp/>
        Order allow,deny
        Allow from all
    </Directory>
    Alias /static /var/www/FlaskApp/FlaskApp/static
    <Directory /var/www/FlaskApp/FlaskApp/static/>
        Order allow,deny
        Allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

to:
<VirtualHost *:80>
    ServerName [serverip]
    ServerAdmin admin@[mydomain].com
    WSGIScriptAlias / /var/www/FlaskApp/FlaskApp.wsgi
    <Directory /var/www/FlaskApp/FlaskApp/>
        Order allow,deny
        Allow from all
    </Directory>
    <Directory /home/[user]/>
        Order allow,deny
        Allow from all
    </Directory>
    Alias /static /var/www/FlaskApp/FlaskApp/static
    <Directory /var/www/FlaskApp/FlaskApp/static/>
        Order allow,deny
        Allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

What research have I done:
I got most of the ideas for things to try (as described above) from searches here (Stack Overflow) on the error cited above.
Conventions:
I have substituted generic words inside brackets (e.g. "[stuff]") for actual entries in my production app config files, etc., just for the sake of not revealing too much info in a public forum like this one.
I'm using Python 3.6.9, a freshly installed mod-wsgi and apache2 (assuming latest versions) running on top of a fully updated Ubuntu Server 18.04, all on a Lightsaber instance at AWS.
What I want:
In general, elp fixing the problem so my FlaskApp can write the file somewhere. Specifically,I think it would be helpful to know what "user" credentials flask apps run under.  If I knew that, I might be able to figure out how to configure permissions for some place to write the file.  What's confusing to me is why the file isn't getting written to /tmp, which makes me think this issue may be more complex than a "permissions" error.
Thank you!
Answer: The user running Apache2 will need permission to write to the file whose path you're constructing. You can verify that by trying /tmp, which is world-writeable.
daily_events_path = '/tmp/test_daily_events.txt'
with open(daily_events_path, 'a') as fileobj:
    ...

If that works, either your prior fiddling with protections wasn't correct, or there's a gremlin like SELinux involved, in which case they may be a log entry in some obscure place in /var/log that provides a hint.
Comment: /tmp works.  I think I'm going to just let it go there since it doesn't really matter where as long as I can check it .  I'm going to have to remember /tmp in the future.  I didn't realize that was universally writeable.  The weird thing (and I forgot to put this in the original question) is that I am also writing data to a sqlite3 file and moving that to the '/home/[user]/' directory fixed a writeability problem with it.  Anyway...  Thanks!
Comment: I guess I spoke to soon.  writing to /tmp avoids the error, but no file actually gets written there.  I'm not sure if that's an effect related to writing 'anything' to /tmp or if I now have a new problem.  :-(
Comment: fileobject.write(json.dumps(data) + "\n")

And that is the end of the "with."  The next line is blank followed by an outdented "logging.info()," which, strangely, is also not getting written to /tmp where it's supposed to go as specified by this line earlier in the code:
    logging.basicConfig(filename='/tmp/FlaskApp.log',
                        format='%(asctime)s %(levelname)s:%(message)s',
                        level=getattr(logging, 'INFO'))
Comment: What OS (and version) are you running this on?
Comment: Kernel = 5.3.0-1030-aws GNU/Linux,
Distro = Ubuntu 18.04 LTS Server,
On a Lightsail instance at AWS
Comment: @'Dave W. Smith' - I've made some updates to this and wonder if you have seen them.
Comment: @JohnCroc I'm hoping that someone with Lightsail experience can chime in. In your position, lacking that, I'd try writing to several places using a try/except block with logging in each section.
Comment: Thank you , Dave.  I am grateful for your help and will keep trying.


yii mysql using subqueries with query builder

Question: I am builing an app with yii and I tried doing my sql calls the "pretty way" using the yii query builder the same way seen on this guide
http://www.yiiframework.com/doc/guide/1.1/en/database.query-builder
And this is my built query:
$diseaseCountSqlQuery = Yii::app()->db->createCommand()
                                    ->select ('tbl_disease.ICD10, COUNT(tbl_disease.ICD10) AS disease_count')
                                    ->from ('tbl_disease')
                                    ->join ('tbl_symptom_disease', 'ICD10=diseaseCode')
                                    ->where ($symptomsOrQueryArray)
                                    ->group ('ICD10')
                                    ->queryAll();
            //placeholder

            $maxDiseaseCountQuery = Yii::app()->db->createCommand()
                                    ->select ('MAX(disease_count) AS max_disease_count')
                                    ->from ($diseaseCountSqlQuery)
                                    ->queryAll();
            //multiple symptom query
            $diseaseCodes = Yii::app()->db->createCommand()
                            ->select ('ICD10')
                            ->from ($maxDiseaseCountQuery)
                            ->join ($diseaseCountSqlQuery, 'max_disease_count=disease_count')
                            ->queryAll();

The problem appears in the second command specifically the line:
->from ($diseaseCountSqlQuery)

I get an "strpos() expects parameter 1 to be string, array given " error.
I can solve my problem by just copying the entire mysql command into a string and then using create command, but I wanted to use this more "elegant" way. Can someone help me fix it and explain a bit how subqueries work with query builder? Thank you :)
Comment: the error tells you exactly what the problem is: you're trying to use an array where a string is expected. you'd need to do a `foreach($diseaseCountSqlQuery as $part) { ...->from($part)}` or whatever.
Comment: ok, so is there a way to use the result table of the sql command in a different query?
Answer: You can't create subqueries like this. The first queryAll returns an array with results. You can't query this like it's a database. The from() part expects a parameter in the form of a string, not an array.
Try it like this:
Yii::app()->db->createCommand('complete query, including subquery')->queryAll();

Or use PHP to filter the results after executing the first query.
More info on createCommand:
http://www.yiiframework.com/doc/api/1.1/CDbConnection#createCommand-detail
http://www.yiiframework.com/doc/api/1.1/CDbCommand
Comment: Do you have any useful resources so I can understand the use of createCommand that way better?
Comment: Take a look at the links I've added to the answer.


ECMA6 classes not working on IE11 with Webpack and Babel

Question: I am trying to get a React project to work with being packaged using Webpack and Babel using @babel/pollyfill. When I try to run on IE I get the following error...

SCRIPT1002: Syntax error

It is failing here...
<code>class HealthCheck extends react__WEBPACK_IMPORTED_MODULE_0__["Component"]{
    render(){
        return _HealthCheck_jsx__WEBPACK_IMPORTED_MODULE_1__["HealthCheckTemplate"].call(this);
    }
}
</code>
So I am guessing it can't handle class so how do I fix this?
Answer: Try using @babel/plugin-transform-classes .
https://babeljs.io/docs/en/babel-plugin-transform-classes
Comment: What does your configuration look like now? Might be helpful for others to see it. I'm curious too.
Comment: Actually shoot this is the part that isn't using babel. I am only using Babel for JSX files this is a js file. I am using webpack to bundle the js files but not babel. Maybe I will need to start with those too
Comment: Adding js to the babel loader and including this worked thanks!


excel 2003 etc. web query "treat consecutive delimiters as one", how to shape a query in such way in the (excel 2016) "Power Query"

Question: Excel 2003 etc. web query offers to group a single row whose columns are different than above or below, essentially.
But so far I see no INTUITIVE or "wizard-guided" way to shape a query in such a way with the new Office 365 (excel 2016) "Power Query", neither saw I anything on the topic in cursory skimming of superficial help documentation,
and while I can work around this issue (on the spreadsheet itself where I am already doing relatively extensive post-query processing,) it is far easier using the wizard!
Seems the wizard configuration is "treat consecutive delimiters as one" in excel 2007 options dialogue of "edit query" (also of found when making a new query in excel 2007 etc. versions).
How can I do this in Office 365 without manually constructing a "synthetic" or home-made "query" via left(), right(), and mid() formulae tactical stuff on the grid itself (the old school super excel finesse & monstrosity of it!! as much fun as it is!)
Thank you so very much!
miscellanea and detail:
Not sure if it is the browser or stack overflow doing the spell check but it cites etc. as a misspelling, and offers to replace it with etc. LOL =^)
I am pulling from a simple html that is local, and is a funky annoying table spat out by  software I wish I had more control of, so it is a web query.
I suppose I could edit the html file prior to pulling it in excel, but this would defeat the point of making this as simple as possible and as FAST as possible.  Ideally if I new how to just scrape the data looking at the guts of the software I wish I controlled more of, without exporting to html, I'd love to watch all the dependant models flicker (the data can be relevant on an microsecond basis) live with the live data it is based on, but alas, one thing at a time, minding redundancy bloat etc....
Answer: Since my company upgraded to Excel365(ver 1803), I had the same problem when importing/getting data from txt (CSV) with space delimiter(one or more  consecutive).
However, Excel365 is still having the previous import wizard  on "Text to Columns" function, but this function requires all the text in a single column.
Though I am still looking for a power editor solution, paste the plain text on a spreadsheet and Excel automatically uses consecutive spaces as a column delimiter.

excel 2003 etc. web query “treat consecutive delimiters as one”, how to shape a query in such way in the (excel 2016) “Power Query”


how can i improve upon Map>> using guava

Question: I have the following data structure for the entity relationships:
Map<Integer, Map<Integer, Map<PAXType, BigDecimal>>>

Entity Relationships:

1 Package(P) has Many Variants(V)
1 Variants(V) has Many Price data-points
Price is based on the PAXType (which is an enum: Adult, Child, Infant)

I modelled this using:
Map<Package, Map<Variant, Map<PAXType, BigDecimal>>>

for the purpose of quick price lookup based on

package
package variant

The way I'm using this right now is:
As I read data from the db, I create/update the above map. After I get all the info, for each variant, I need to transform the price map, from Map<PAXType, BigDecimal> to Map<OccupancyType, BigDecimal>, where OccupancyType is another enum. This is the final price format which I need to output for serialization etc.
Is there any data structure in guava which would be a good fit for the ugly map construct I have and support the operations I suggested above ?
Answer: In addition to Tomasz's answer suggesting encapsulating Map<PAXType, BigDecimal> in class PriceByType (note that if PAXType is an enum, you should use EnumMap) I think you should consider using Guava's Table as substitution for Map<Integer, Map<Integer, PriceByType>>. Table use case:

Typically, when you are trying to index on more than one key at a
  time, you will wind up with something like Map<FirstName,
  Map<LastName, Person>>, which is ugly and awkward to use. Guava
  provides a new collection type, Table, which supports this use case
  for any "row" type and "column" type.

Your indexes are package and package variant, both Integers, so table should end up with Table<Integer, Integer, PriceByType>.
Comment: +1 for both `EnumMap` and `Table` suggestions (so, after all, Guava *does* provide a helper for what OP needs).
Answer: Guava has nothing to do here, you need to create few objects with meaningful names. First encapsulate Map<PAXType, BigDecimal> into e.g. PriceByType class holding this map:
Map<Integer, Map<Integer, PriceByType>>

Now proceed with Map<Integer, PriceByType> in the same way:
Map<Integer, PriceByVariant>

The final map can be called priceByPackage. Now create few helper methods to query these classes effectively:
public class PriceByType {

    private final Map<PAXType, BigDecimal> byType = //...

    public BigDecimal find(PAXType type) {
        return byType.get(type);
    }

}

and:
public class PriceByVariant {

    private final Map<Integer, PriceByType> byVariant = //...

    public BigDecimal find(int variant, PAXType type) {
        //handle unknown values here
        return byVariant.get(variant).find(type);
    }

}


Xamarin.Android MPAndroidChart c# version RoundBarChart

Question: Im currently using MPAndroidChart in C# via Nuget.
I tried to build a RoundedBarChart using this reference WW-Digital/MPAndroidChart
But the issue some methods/variables for example:
In this line setBarSpace is existing. refer MPAndroidChart
// initialize the buffer
    BarBuffer buffer = mBarBuffers[index];
    buffer.setPhases(phaseX, phaseY);
    buffer.setBarSpace(dataSet.getBarSpace());
    buffer.setDataSet(index);
    buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency()));

while in c# MPAndroidChart in C# via Nuget

  // initialize the buffer
        BarBuffer buffer = BarBuffers[index];
        buffer.SetPhases(phaseX, phaseY);
        ///buffer.Bar(dataSet.getBarSpace());
        buffer.SetDataSet(index);
        buffer.SetInverted(Chart.IsInverted(dataSet.AxisDependency));

There is no BarSpace variable or method that is existing.
The java and c# version is the same 3.0.2
If I am missing something kindly provide me insight on this.
Answer: The  MPAndroidChart in C# via Nuget is different from the WW-Digital/MPAndroidChart.
The MPAndroidChart.Xamarin nuget you are using  is a Xamarin.Android binding for MPAndroidChart by Philipp Jahoda. So you should refer to this example.

There is no BarSpace variable or method that is existing.

You could use buffer.SetBarWidth() method, usage like this :
protected IBarDataProvider mChart;

...

buffer.SetBarWidth(mChart.BarData.BarWidth);

You could refer to BarChartRenderer.
Comment: Actually your answer is right, But unfortunately I have to recover my time and do a fork and created a binding myself.


What is Best way to earn XP?

Question: my friends and I were playing on a world together, but now, we ask ourselves: what is the best way to earn xp?
It was a mob tower, but they never decide to fall. And for mobspawners, we have tried but the yield is poor !!!
Comment: http://gaming.stackexchange.com/q/39458/38952
Comment: I'm afraid this question is too vague to get a decent answer on this site and might be closed unless you edit it. Perhaps a better question might be: 'Why don't the mobs fall out of my mob grinder?'.
Comment: "Best" is subjective. Blaze farms have a very high EXP yield but on the other hand are rather expensive and very dangerous to build.
Comment: The answer is currently mining nether quartz is the best way to gain Xp. That is an answer on the linked question, all be it it only has my up vote currently.
Answer: EXP only drops when a player kills the mob, so a mob tower won't work for your plan. Also, mobs won't walk over edges on their own. You need to push them with a water current or piston. Although the yield is "poor" in a mob spawner system where you kill manually, that's really your only option on Vanilla Minecraft.
You gain small amounts of exp for mining. a Good mining expedition will easily net you 15+ levels. Killing passive mobs (cows/sheep/pigs) also give a small handful of exp. You could use this and make a breeder slaughterhouse.
But as I already stated, a set up Mob Spawner will be your optimal exp flow.
Comment: What is best in a mob grinder is to drop them 22 blocks, so that it almost kills them, but not quite. They then only take one punch to kill, so it's the most efficient way.
Answer: You may want to look at this enderman farm by Panda or this blaze farm by Etho. By far those two are one of the best XP sources in the vanilla game.

What is Best way to earn XP?


How to get the route name of back screen

Question: Before I back to the previous screen, is it possible to get this back name and conditional execute the needed method call?
Answer: if you use Get, you can get previous route name directly by Get.previousRoute.
It implements this by a NavigatorObserver (lib/get_navigation/src/routes/observers/route_observer.dart)(https://api.flutter.dev/flutter/widgets/NavigatorObserver-class.html). You can also implement your own observer and maintain the route history.
Comment: Could show a example code how to pass arguments to the specific back screen?
Comment: I assume you are using getx. At first screen, use `final YOUR_RESULT = await Get.toNamed(page);` to get the result. At second screen, use `Get.back(YOUR_RESULT);` to pass the result to previous screen.


How do i use a cell in a formula to take info from a sheet that has the same name as the cell context?

Question: To explain my terrible title...
Lets say i have an excel (well its a google sheets file, but they are similar, except when they arent XD). This file has 200 tabs with lets say client names as their titles. and i also have a summary sheet with a table with much general info and in the table i have a column with the exact same names to those sheets (client names).
as i am trying to automate and add some functionality to that summary sheet (AND HAVE EXTRA OTHER SHEETS take info from the summary sheet) i want to find a way to use the names of clients from that column in 'summary' to have formulas go pick up specific cells from said sheets.
So:
1* sheet 'summary'
200*sheets "clients-names"
in 'summary' there is a table, with column with clients names (exact same text as the names of the sheets).
lets say i want a formula that in sheet 'summary', in cell A2 would pick the name of a sheet from the table, lets say from cell B2, and then it would bring up the information from the relevant sheet (named in cell B2) from lets say cell C2.
i can create manually connections for ALL the sheets and cells needed, but it would take a lot of time and the problem is that new sheets will be added (and the info to table) and some are gonna be deleted... and biggest problem is the file is gonna be used by sb else, so i want to set it uip to work and not have them "work on it" as they dont have much experience with spreadsheets (well way less than me)
Comment: Check [INDIRECT function](https://support.microsoft.com/en-us/office/indirect-function-474b3a3a-8a26-4f44-b491-92b6306fa261) for an Excel solution (don't know if there is the same in Google Sheets)
Comment: For what it's worth, as an expert who's been developing spreadsheet solutions of all sizes since spreadsheets were first introduced to the world, whenever I hear someone say that they have "200+ individual sheets of data with one summary sheet," I can't help but think that this is backward. Instead, the norm would be to create ONE database/master, and then have other sheets present various "reports" from that master sheet (which can often be done in just ONE sheet wherein any "client name" can be searched/reported, rather than needing 200+ sheets).
Comment: @ErikTyler well first it is in google files so about 35 people can work on it together. its 200 tabs as client names because 1- thats how i was asked to make it after i made something closer to your proposal and it wasnt liked by management,
2- the summary tab is be updated by a secretary and add the new tab (with the clients name) and then some of the 35 people working  in the company are supposed to be inputting all the tasks that they have completed for said clients.

we could have used a project management software, but "oh it costs 10$ a month!!! we can do that with an excel".
Comment: Ah. If management is that tight with their money, there isn't much that can be done anyway. I'm surprised they have money to pay you to do anything on it, as that would most surely be far and away more than $10/month. But it looks like you solved the immediate issue. Good luck.
Answer: I just had to input this in cell A1 in my 'summary' sheet:
<code>=INDIRECT("'"&B2&"'!C2")
</code>


How to select multiple checkboxes in a Drag event

Question: We have multiple checkboxes, as shown below:

We want the user to be able to select first checkbox for A,B,C, by him dragging over the checkboxes.
Is this possible in android?
Comment: Yes it's possible but  it would make a poor UX pattern.
Answer: Yes, you could do something like that.  You'd have to first start a drag operation and drag a view.  If you tried to do it with just your finger, it would be an exercise in gesture detection.  But dragging a view would be simple.
Using this tutorial as a guide - http://developer.android.com/guide/topics/ui/drag-drop.html - you should be able to start a drag operation using a click listener on the view you want to drag. Then, as the dragged view enters the bounding boxes (you set up draglisteners on each) of a checkbox, you can set it to checked.


Why can I not turn off my ceiling lights?

Question: Three ceiling lights which worked for years, cannot be turned off.  There are three switches, each of which controls all three lights (they are all on or all off).  Is there a simple fix or must I call an electrician? I didn't change anything.
Comment: Toggling any one switch is supposed to change the lights so something is wrong. But to start with have you systematically checked all the states of the switch system to insure that there is no state in which the lights go out? S1 up, S2 up, S3 up; S1 up, S2 up, S3 dn; S1 up; S2 dn, S3 up; S1 up, S2 dn, S3 dn, etc.?
Comment: If you are not electrically savvy - call an electrician. For now until your electrician comes out : To turn the lights off - turn off your circuit breaker in the circuit breaker panel.
Comment: This shows the basic idea of how these switches are wired: http://users.wfu.edu/matthews/misc/switches/4WayAnimation.html
Answer: One of the switches has failed and will likely need to be replaced. There will be two "three way" switches and one "four-way" switch. It's the four-way that has broken. The switch may feel different when you toggle it.
Unscrew the bulbs until you get it fixed.
Comment: how do we know its the 4 way that failed?
Comment: @agentp seems like the only likely cause is a short between the two switched wires. This short could happen at any of the switches. The four way might be more likely (more complex), but I agree it could be any of the three.
Comment: Sorry, I was wrong, Jeffrey's right, it could be any of the switches that has failed in such a way that the normal connections for both switch positions remain connected.
Answer: One of you switches have failed.  The solution is to start replacing switches, like for like.
Answer: The switch leg for the light is hooked up to the constant hot.
Comment: This wouldn't explain why it worked for 3 yrs.


Can I connect a gazebo light to a shed sub-panel or outlet?

Question: I have a sub-panel in my garage and there is UF cable 12-2 running underground to my shed with a disconnect box, and the 12-2 wire is running to a GFI.  Within the shed, I have another 20 amp outlet, two ceiling lights on a single pole switch and two outside lights on their own switch.  I'm adding a gazebo on my deck and need to add a ceiling fan with a single pole switch and one outlet.   Can I run another UF 12-2 underground to my shed and tie the wires to the disconnect box or to the other 20 amp outlet?
Here is the diagram:
Comment: Your plan and descriptions are not entirely clear. I think that I understand what you want to do, but the exact layout is kind of important. How far away are these runs? You might need to increase the diameter of the wire and breaker size going from the garage to the shed in order to add a run from the shed to a gazebo. Or it might be easier to go from the garage to the gazebo.
Comment: First – I would like to thank you for your response.  I have added numerous outlets, recessed lighting etc. You are right, running the wire from the sub-panel is probably the easiest option (it's only about 14 feet), but I'm not comfortable with going into the electrical panel to run wires – only to shut down the power.   If possible, can I run the UF 12-2 wire to the disconnect box or to the 20-amp outlet which is approximately 60 feet from the deck.
Comment: I can't tell if you are actually talking about a disconnect or not... to my knowledge you cannot make extra connections in a disconnect box, so why would you think that would be okay (or more comfortable than) going from the subpanel? Where would you attach the wires? How large is the breaker going to the disconnect? How large is the main breaker in the subpanel? How many small breakers do you have in the subpanel? Can you add pictures of the (open) subpanel and (open) disconnect box?
Comment: Where is the other 20 amp outlet, two ceiling lights on a single pole switch and two outside lights (on their own switch) comming from? The disconnect or the subpanel? Are they all on the same circuit, connected together in an outlet or switch box in the shed? Is everything in the shed comming from one breaker?
Comment: Is this the lay-out? [![enter image description here](http://i.stack.imgur.com/rZJRP.jpg)](http://i.stack.imgur.com/rZJRP.jpg)
Comment: @BenWelborn feel free to post pictures to the chat and copy the link to a comment here, rather than posting a non-answer.
Answer: Since the garage panel is a subpanel and not a service entrance, you should be able to turn the entire subpanel's feeder off upstream -- I'd lock it out with a breaker-lock + padlock myself to avoid a shocking surprise from somebody else in the family.
With that done, running the gazebo circuit into the subpanel should not be an issue -- it's like running wires into a giant junction box in that you'll need to support and clamp them in the same way as you would a box. Once you have the wires in there with enough slack to make the connection -- simply screw the bare wire to the ground bar, the white wire to the neutral bar, and the black wire to the screw terminal on a spare 20A breaker, presuming you have one.  You'll also have to take the front cover (dead front) off and put it back on, but that shouldn't be too hard.
Once everything is hooked up, put back together, and ready to go, simply take the lock off the feeder breaker and turn it back on.


SqlDataSource lost the where clause during paging

Question: I have a SqlDataSource with this query:
SELECT [ProductName], [Debscription], [Price] FROM [MyDb] WHERE ([Date1] >= @Date1) ORDER BY [ProductName]">

When I load the page, it works fine and shows me only the products that I want.
When I try changing page of the GridView, and for example, go to page 2, it refreshes the page and generates lots of page indexes as the where clause is lost.
How can I solve this?
I thought that the statement was automatically saved, but it's not.
How can I save the where clause during paging?
Answer: For dynamic paging you should use an ObjectDataSource instead of a SqlDataSource.
Answer: If you want the grid to handle paging, bind it to a DataTable or DataSet. For ex:
private void Page_Load(object sender, System.EventArgs e)
{
   if (!Page.IsPostBack)
       BindData();
}

private void BindData()
{
    // Connect to the Database
    SqlConnection myConnection = new SqlConnection(connection string);

    // Retrieve the SQL query results and bind it to the DataGrid
    string SQL_QUERY = "SELECT ProductName, UnitPrice, UnitsInStock " +
                  "FROM Products";
    SqlCommand myCommand = new SqlCommand(SQL_QUERY, myConnection);

    // Use a DataTable – required for default paging
    SqlDataAdapter myAdapter = new SqlDataAdapter(myCommand);

    DataTable myTable = new DataTable();
    myAdapter.Fill(myTable);

    dgProducts.DataSource = myTable;
    dgProducts.DataBind();
    myConnection.Close();
}

https://msdn.microsoft.com/en-us/library/aa479006.aspx
Comment: While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference.  Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/16419576)
Comment: I wasn't sure if the original answer/link answered the question exactly so I skipped the code. Updated with code.


Brightness works with Function (FN) Keys in Lubuntu 12.10 but not Ubuntu 12.10

Question: I have a Toshiba Portege R930 laptop and installed Lubuntu 12.10 through Wubi and then installed the Ubuntu-Desktop package afterwards.
When in Lubuntu, pressing FN+F6 and FN+F7 lowers and increases my screen brightness perfectly, however, when logging into Ubuntu (instead of Lubuntu), the function keys don't work.
Ideas?
Comment: I have a similar problem with an Asus S200E. Some function  keys (brightness, touchpad-toggle) do not work in Lubuntu. But they do in Ubuntu.
Answer: same problem for me, brightness key don't work with the kernel Linux 3.5.0-23-generic.
But when I boot with the Linux 3.5.0-17-generic (with grub, just hold shift key when booting and choose advanced , Linux 18.104.22.168 kernel) everything just work !
as the Linux 3.5.0-17 is the base kernel, you should have it installed and you can try that trick.


How to format numpy arrays?

Question: I have data that looks like this
listL= array([array([-12939613.07220617,   3962855.50690994]),
       array([-12939614.67349505,   3962828.80807231]),
       array([-12939484.00289515,   3962828.1637531 ]),
       array([-12939484.98046737,   3962854.91251931]),

print(type(listL)) -> <class 'numpy.ndarray'>
print(type(listL[0])) -> <class 'numpy.ndarray'>
print(type(listL[0][0])) -> <class 'numpy.float64'>

I have a second piece of data that looks like this:
A = array([[ 73.87682896,   8.55827956],
       [ 57.43741519,  10.40224912],
       [ 87.88970753,  75.42971056],

print(type(A)) -> <class 'numpy.ndarray'>
print(type(A[0])) -> <class 'numpy.ndarray'>
print(type(A[0][0])) -> <class 'numpy.float64'>

The types are the same across both sets of data, but I have a function that works with 'A', but not with 'listL' and I cannot figure out why.
A[spatial.KDTree(A).query(coordinate)[1]]

works, but
listL[spatial.KDTree(listL).query(coordinate)[1]]

returns the error:
not enough values to unpack (expected 2, got 1)

Comment: The `type` doesn't help much.  Look at `shape` and `dtype` instead.  `listL` Iwhich  is missing a `])`) is a 1d object dtype array (shape (4,).  `A` is a 2d array of numbers, shape (3,2).  `np.stack(listL)` should produce a (4,2) numeric array.
Answer: ListL is in some respects a pathological structure, it is an array of arrays where a 2D array is expected.
numpy/scipy goes to some lengths to graciously accept most things that can be interpreted as 2D array, for example if you repace KDTRee(ListL) with KDTree(list(ListL)) it works.
Why does it work? Because list(listL) behaves like most "essentially 2D" structures (like lists of lists etc.). We can send it through array or asarray or asanyarray etc. to obtain a genuine 2D array.
>>> np.array(list(listL))
array([[-12939613.07220617,   3962855.50690994],
       [-12939614.67349505,   3962828.80807231],
       [-12939484.00289515,   3962828.1637531 ],
       [-12939484.98046737,   3962854.91251931]])
>>> np.array(list(listL)).shape
(4, 2)

An array of arrays is one of the few cases left that still trip up the array conversion machinery:
>>> np.array(listL)
array([array([-12939613.07220617,   3962855.50690994]),
       array([-12939614.67349505,   3962828.80807231]),
       array([-12939484.00289515,   3962828.1637531 ]),
       array([-12939484.98046737,   3962854.91251931])], dtype=object)
>>> np.array(listL).shape
(4,)

We can see despite our attempt to convert to an ordinary array, listL keeps reporting its shape as 1D. Which appears to be what triggers the exception you are observing.

How to format numpy arrays?


Where do you find solar panels to make the solar flare in Mafia Wars?

Question: I can never find solar panels in jobs/fights/robbing. My chop shop is a high enough level to make the "Solar Flare", but I just can't find the parts.
Where are these?
Answer: They drop randomly from doing jobs and fighting in New York. Presumably, the rate is similar to any other Chop Shop item, as there are not exceptions noted, but I personally haven't fought or done jobs in NY at all really since the Chop Shop was introduced, so I'm not entirely sure.
~Source


Is there a standard hole diameter for corner braces?

Question: I'm planning a project that requires corner braces, and I want to figure out what size bolts I can put through them. Unfortunately, at least on the Home Depot website, the corner brace product listings do not list the hole diameters, though they do have the length and width of the brace.
Is there a standard hole diameter for corner braces? Or is there, perhaps, a standard hole diameter for each width of corner brace? If not, other than by going to the store and measuring, is there a way to know how large the holes are?
Comment: 1" or 12" braces? There is a huge range of brace and screw/bolt sizes. Also, different braces/uses/wall materials require different screws/bolts and differnent fasteners. What are the particulars of your project?
Comment: @bib, I'm looking at 2" or shorter braces, and I want to put bolts through them and through 2x4s. The goal is to temporarily join two 2x4s with the 1.5" face of one resting against the 3.5" face of the the other, using a bracket on the inside of the join (hence maximum 2"). I want to use bolts rather than screws to make it easier to detatch and re-attach.
Comment: Sites like HD often have a question and answer feature that the manufacturer monitors and answers questions on.  You may want to check if the particular product page you're looking for has such a feature. That way you can get an exact answer.
Answer: There are no standard sizes.
Braces of the type you are considering most commonly have holes that are less than 1/4" and more than 1/8", somewhere around 3/16".  They are usually intended for #6, #8 or #10 screws. You could probably use 1/8" bolts, or maybe 3/16" depending on the brace. 1/4" bolts probably won't fit unless you ream out the holes.
Which bolts will be sufficient depends on how much strain will be on them and how many braces you are using.


Sovle $I=\int_{0}^{\infty}\frac{\ln^2x}{1+x^4}dx$. Using function Euler. Help me please..

Question: Solve $$I=\int_{0}^{\infty}\frac{\ln^2x}{1+x^4}dx$$
Using function Euler. Help me please..
Comment: What is "function Euler"? Are you thinking of a particular programming language and library? Also, is that an iterated logarithm, or a power in the integrand?
Comment: What does Euler's Toitient have to do with evaluation of this integral?  Or perhaps you meant something different from that.
Comment: By breaking the original integration range into $(0,1]\cup[1,+\infty)$ and performing the trivial substitution, the integral takes the form $$\int_{0}^{1}\frac{1+x^2}{1+x^4}\log^2(x)\,dx.$$ By expanding $\frac{1+x^2}{1+x^4}$ as a Taylor series around $x=0$ and exploiting  $\int_{0}^{1}x^n \log(x)^2\,dx = \frac{2}{(n+1)^3}$, the problem can be solved through a well-known identity: http://math.stackexchange.com/questions/850442/an-interesting-identity-involving-powers-of-pi-and-alternating-zeta-series
Answer: You can use contour integration here: \begin{align*} \int_0^{\infty} \frac{\ln(x)^2 + (\ln(x) + \pi i)^2}{1+x^4} \, \mathrm{d}x &= \int_{-\infty}^{\infty} \frac{\log(z)^2}{1+z^4} \, \mathrm{d}z \\ &= 2\pi i \mathrm{Res} \Big( \frac{\log(z)^2}{1+z^4}; z=\sqrt{i} \Big) + 2\pi i \mathrm{Res} \Big( \frac{\log(z)^2}{1+z^4}; z= \sqrt{i}^3 \Big) \\ &=2 \pi i \Big( -\frac{\log(\sqrt{i})^2 \sqrt{i}}{4} - \frac{\log(\sqrt{i}^3)^2 \sqrt{i}^3}{4}\Big) \\ &= 2\pi i \Big(\frac{(\pi i / 4)^2 (-1-i)}{4 \sqrt{2}} + \frac{(3\pi i / 4)^2 (1 - i)}{4 \sqrt{2}}\Big) \\ &= -\frac{\pi^3}{4\sqrt{2}}i - \frac{5 \pi^3}{16 \sqrt{2}}, \end{align*} so $$2 \int_0^{\infty}\frac{\ln(x)^2}{1+x^4} \, \mathrm{d}x + 2\pi i \int_0^{\infty} \frac{\ln(x)}{1+x^4} - \pi^2 \int_0^{\infty} \frac{1}{1+x^4} \, \mathrm{d}x = -\frac{\pi^3}{4\sqrt{2}}i - \frac{5 \pi^3}{16 \sqrt{2}}.$$ Taking real parts, $$\int_0^{\infty} \frac{\ln(x)^2}{1+x^4} = \frac{\pi^2}{2} \int_0^{\infty} \frac{1}{1+x^4} \, \mathrm{d}x - \frac{5\pi^3}{32 \sqrt{2}}$$ Another contour integral will calculate $\int_0^{\infty} \frac{1}{1+x^4} \, \mathrm{d}x = \frac{\pi}{2 \sqrt{2}}$, so $$\int_0^{\infty} \frac{\ln(x)^2}{1+x^4} \, \mathrm{d}x = \frac{\pi^3}{4 \sqrt{2}} - \frac{5\pi^3}{32 \sqrt{2}} = \frac{3 \pi^3}{32 \sqrt{2}}.$$
Comment: Nice, but it's even simpler if you integrate about a quarter-circle.


Windows Mobile - Get Encryption Key

Question: Windows Mobile Supports Encryption (Settings -> System -> Encryption). My application needs to read encrypted files and decrypt it. How can I get encryption key used by Windows Mobile and decrypt it?
Comment: If you could just "get" the key, wouldn't that defeat the purpose of encryption?  You should only be able to decrypt data that you encrypted with your own, known key.  Or am I misunderstanding your question?
Comment: You are right. But, we have a requirement that we need to decrypt the data encrypted by native encryption. I know that it will defeat the purpose. But, I need to make sure that it is not possible. Thanks.
Comment: I gone throught one of the article of Windows Mobile Encryption FAQ (http://blogs.msdn.com/b/windowsmobile/archive/2007/03/26/windows-mobile-6-storage-card-encryption-faq.aspx). In the answer of question, "Where are the encryption keys stored?", he repied that, "untrusted" application cannot access it. What does it mean? How can we install application as a trusted application? Can we retrieve Encryption key as a trusted application?
Comment: You'll have your app signed by a trusted third party: More details: http://msdn.microsoft.com/en-us/library/ms839681.aspx
Answer: If the only reason you want the key is to use it to decrypt an object, then just use the CryptDecrypt function of the Windows Mobile Cryptography API.
-PaulH
Comment: But, which key I should use to decrypt?
Comment: You can enumerate the certificates in the store with `CertEnumCertificatesInStore` to get a `CERT_CONTEXT` structure then use `CryptImportKey` to get a key from that structure.
Comment: Are you sure that I can get the Encryption Key used by Native Encryption in Windows Mobile?
Comment: No, but if this is important to you it may be worth 20 minutes of your time to hammer out some test code to try this.

Windows Mobile - Get Encryption Key


get last blobitem in azure container

Question: My application uses the Microsoft Azure cloud blob storage, and i'm looking for an alternative way to get the last item in a folder in a container.
This is how it goes now:
CloudBlobClient blobClient = new CloudBlobClient("http://ferryjongmans.blob.core.windows.net/", new StorageCredentialsSharedAccessSignature(signature.Text));
CloudBlobContainer container = blobClient.GetContainerReference(cameraList.Items[Convert.ToInt32(Label1.Text)].ToString());

//Maak mooie datum notatie zoals : 01-01-2013 (standaard methode geeft in dit geval: 1-1-2013)
string dag = DateTime.Now.Day.ToString();
if (dag.Length == 1)
{
    string temp = dag;
    dag = "0" + temp;
}
string maand = DateTime.Now.Month.ToString();
if (maand.Length == 1)
{
    string temp = maand;
    maand = "0" + temp;
}
//Complete datum (DD-MM-YYYY)
string datum = dag + "-" + maand + "-" + DateTime.Now.Year.ToString();

CloudBlobDirectory direct = container.GetDirectoryReference(cameraList.Items[Convert.ToInt32(Label1.Text)].ToString());
CloudBlobDirectory subdir = direct.GetSubdirectory(datum);

BlobRequestOptions options = new BlobRequestOptions();
options.UseFlatBlobListing = true;
options.BlobListingDetails = BlobListingDetails.Snapshots;
//maak string voor het tijdelijk oplaan van de uri
string uri="";
//Ken steeds een waarde aan 'uri' toe om vervolgens wanneer de for loop klaar is
//de laatste uri te krijgen.
foreach (var blobItem in subdir.ListBlobs(options))
{
    uri = blobItem.Uri.ToString();
}
string url = uri + signature.Text;
if (url != pictureBox2.ImageUrl)
{
    loadImage(url);
}

So I'm looping through the items and use every time the same string to assign the URI of the blob.
When the loop is finished, my string has the URI of the last item in the directory.
I think i can do this on a more efficiency way. The directory's have lots of blobs in it. (+- 30000)
This piece of code will be run once in a second, so its important it will be run on a efficient way.
Answer: What if you convert your list in a hashSet? change your foreach for this and see what happend
 var hashSet = new HashSet<IListBlobItem>(subdir.ListBlobs(options).ToList());

 string url = uri = hashSet.Last().Uri.ToString() + signature.Text;

hashSet are faster for search and find.
Comment: This doesn't work, the application is responding very slowly with this function, and I don't get a picture when I assign the URL as image location
Answer: I have created a function in my upload application that will write every time the full URI of the newest image in a text file (txt)
                CloudBlobClient blobClient = new CloudBlobClient(sUrl, new StorageCredentialsSharedAccessSignature(signature));
                CloudBlobContainer container = blobClient.GetContainerReference(container1);
                CloudBlobDirectory dir = container.GetDirectoryReference(cameranaam);
                CloudBlob cloudBlob = dir.GetBlobReference(cameranaam+".txt");
                cloudBlob.UploadText(blobSAS.Uri.ToString());

And this is the timer of my other project who is loading the last image of the server:
            blobClient = new CloudBlobClient(blobstoreurl, new StorageCredentialsSharedAccessSignature(signature));
            container = blobClient.GetContainerReference(containerName);
            CloudBlobDirectory dir = container.GetDirectoryReference(comboBoxCameras.SelectedItem.ToString());
            CloudBlob cloudBlob = dir.GetBlobReference(comboBoxCameras.SelectedItem.ToString().Replace(" ","")+".txt");
            pictureBoxLiveViewer.ImageLocation = cloudBlob.DownloadText()+signature;

Comment: blobclient and container in the second part is declared out of this function (globally)
Answer: I find the accepted answer confusing and poorly explained. My preference is as follows:
To create a transient file (ie: it's name gives it context) I make use of Azure Blob Storage Virtual Directories and name the blob specifically using Seconds Since Epoch.
An example, assuming you have a directory with path "SomeContainer/SomeFolder/". This directory has one or more files in it, named using the Seconds Since Epoch mentioned above. To fetch the "last" or latest file, use the following:
StorageCredentials cred = new StorageCredentials("{{YOUR ACCOUNT NAME}}", ""{{YOUR ACCOUNT KEY}}");
CloudStorageAccount storageAccount = new CloudStorageAccount(cred, true);
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); //invoke the blob client
CloudBlobContainer container = blobClient.GetContainerReference("SomeContainer"); //get your container reference
CloudBlobDirectory directory = container.GetDirectoryReference("SomeFolder"); //resolve the directory
IListBlobItem latestBlobItem = directory.ListBlobs(true, BlobListingDetails.All).LastOrDefault(); //get the latest blobItem
CloudBlockBlob blockBlob = null;

if(latestBlobItem != null && !String.IsNullOrWhiteSpace(latestBlobItem.Uri.LocalPath))
{
    //get the blob's local path
    string fullLocalPath = latestBlobItem.Uri.LocalPath;
    //remove container and leading slash
    string localPath = fullLocalPath.Substring(fullLocalPath.IndexOf('/', 1) + 1);

    //get your blob reference
    blockBlob = container.GetBlockBlobReference(localPath);
}

From there do as you wish with the block blob reference (download etc.)
Happy blobbing!

get last blobitem in azure container


Angular.js table mapping brain fahrt

Question: I'm new to front end development and am playing with angular.js (1.4.8).  In the code below, I do an http get.  I then
map the json data into a table.  I think I have a mapping problem, ie, the ng-repeat isn't pulling stuff out of the
json correctly.  Or perhaps it's something else and I'm unintentionally misleading you.  Do you see a programming
error here?
Here is the relevant html:

            {{header}}

                        {{ record.data.day }}
                        {{ record.data.date }}
                        {{ record.data.value }}

Here is my angular file:
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http) {
    $scope.init = function () {
        $http.get("https://localhost:4567/1")
            .then(function (response) {
                var json = angular.toJson(response.data.records);
                $scope.records = json;
                $scope.headers = response.data.headers;
            });
    };

    $scope.httpPost = function (journal) {
        var theJson = angular.toJson(journal);

        var successCallback = function (data, status, headers, config) {
            $scope.postResponse = data;
        };

        var errorCallback = function (data, status, headers, config) {
            console.log();
        };

        $http.post('https://localhost:4567/journal', {"foo": "bar"}).then(successCallback, errorCallback);
    };

    $scope.master = {};

    $scope.update = function (journal) {
        $scope.master = angular.copy(journal);
    };

    $scope.reset = function () {
        $scope.journal = angular.copy($scope.master);
    };

    $scope.init();
    $scope.reset();
});

Here is the response body (json):
{
  "headers" : [ "day", "date", "value" ],
  "records" : [ {
    "data" : {
      "day" : "Tuesday",
      "date" : "5/3/2011",
      "value" : "2.6"
    },
    "id" : "646312cc-1931-4137-af2a-e712300b489b",
    "dateCreated" : 1453842720871,
    "dateUpdated" : 1453842720871,
    "etag" : "3bee5500-fd03-4d69-84af-8b8dc85292b0"
  }, {
    "data" : {
      "day" : "Wednesday",
      "date" : "5/4/2011",
      "value" : "2.6"
    },
    "id" : "f58eae54-6b30-4f61-b8cc-b04984a8436a",
    "dateCreated" : 1453842720871,
    "dateUpdated" : 1453842720871,
    "etag" : "29e4dc69-c118-4fad-91ae-8a1efaf9b984"
  }, {
    "data" : {
      "day" : "Thursday",
      "date" : "5/5/2011",
      "value" : "2.6"
    },
    "id" : "ebf8dba4-52a9-4e0b-a575-cda2ea29a2ea",
    "dateCreated" : 1453842720871,
    "dateUpdated" : 1453842720871,
    "etag" : "986961bb-84ff-4ac6-9f70-96827006ed87"
  } ],
  "id" : null,
  "dateCreated" : null,
  "dateUpdated" : null,
  "etag" : null
}

=====
As pointed out by two people, the problem was this line (I had turned json object to debug something and forgot to revert ;(
var json = angular.toJson(response.data.records);

Comment: You do not need to explicitly serialise your data to JSON before receiving or sending requests to your server unless you have customised [`$httpProvider`](https://docs.angularjs.org/api/ng/service/$http#setting-http-headers). It sets the `Content-Type: application/json` header by default.
Comment: Why are you serializing the return value to json before assigning it to $scope.records? Serializing records means that it is now a string not an array. Try changing that line to $scope.records = response.data.records. Ng-repeat needs to be passed an array to iterate over not a string.
Comment: Thanks to both of you - that was the problem.  I am coding alone and that's the kind of thing that pairing with another person would have caught.  I knew I was doing something dumb and just missed it ... hence the title "brain fahrt" ... I knew it was something like this.  You probably saved me a good bit of time.  @Miqid, you answered first, so feel free to post and I'll credit you.
Answer: Angular's $httpProvider automatically adds the Content-Type: application/json header to all outgoing service requests made by your application.
In addition, it will also automatically deserialise responses using a JSON parser if a JSON-like response is detected.
As such, there is no need to use functions like angular.toJson() to do the JSON conversion yourself unless you have overridden the default provider behaviour somewhere.
Glad that helped. :-)
Comment: While a little embarassing to publish my brain fahrt's, I realize everyone has them from time to time.  I've at times pointed out obvious things to brilliant programmers.  Thanks for being my code buddy ;)

Angular.js table mapping brain fahrt


Proget server feed does not include Nuget packages even though package has been pushed to the Proget server successfully

Question: We are using Proget 184.108.40.206. We can successfully push the Nuget package to the Proget server but am not seeing the package in the feed.
The "nuget install" command fails when we omit the version (i.e. we want to fetch only the latest). It works for other Nuget packages that appear in the feed when version is omitted. The nuget install command only works on this package when the version is specified.
I have tried restarting the Proget Service but that does not appear to resolve the issue.
Thanks in advance for any assistance. This is an ugent / blocking issues for us.
Answer: Figured out that my specific package is a pre-release and thus required the prerelease option to be set on the nuget install command.


Printing every variable to a file

Question: Good afternoon. I'm printing to a file but having a bit of problems. First of all, the program reads from a file, stores the contents in variables and prints to another file with a bit of additional information. The problem however, it only prints to new file the last person's information in the first file. If anyone is able to fix this I'm greatly thankful. Below is a snippet of the code
#include <stdio.h>
#include <conio.h>
#include <errno.h>

int idArray[100];
int AmtArray; //stores the number of ID's in array

int Stud_List();
//FUNCTION TO PRINT STUDENT'S LIST
int Stud_List(){
    //DECLARATION OF VARIABLES
    FILE *kfile;
    char ffname[28];
    char flname[28];
    int fID;
    int x; //counts amount of entries within file

    //INITIALIZATION OF VARIABLES
    x = 0;

    if ((kfile = fopen("information.txt", "r")) == NULL)
    {
        //this to be displayed if file path is incorrect or file cannot be found.
        fprintf(stderr, "Error while opening file (%d: %s)\n", errno, strerror(errno));
        return 0;
    }

    while (!feof(kfile)){

        fscanf(kfile, "%s %s %d", ffname, flname, &fID); //reads the contents of the file
        printf("\n\n%s - %s - %d", ffname ,flname, fID);
        idArray[x] = fID;
        x++;
    }
    AmtArray = x;
}

int Stats( char *, int);
int Stats (*status, int id){

    FILE *Register;

    Register = fopen ("update.txt","w");
    fprintf( Register, "%5d%8s", id, status);

    fclose(Register);
    }

int main (void){
    int IDentry;
    int x, y; //counters in ID check
    printf("            ========Attendance Recording System========\n");
    printf("                              Menu\n");

    Stud_List(); //call to the function to print the list of the students

    printf("\n\n");
    for (x = 0; x < AmtArray; x++){

        printf("Please enter ID for absent student: ");
        scanf("%4d[0123456789]", &IDentry);

        if (IDentry == idArray[x]){
            Stats ("Absent", idArray[x]);
        }
        if (IDentry == idArray[x]){
            Stats ("Absent", idArray[x]);
        }
    }
getch();
return 0;
}

Comment: feof() is only valid AFTER trying to read past the end of file, so should not be used as a loop control,
Comment: this line: 'int Stats (*status, int id){ ' should be 'int Stats (char *status, int id){ '  as both a prototype and the declaration must have all parameter types listed.  (the prototype does not need the parameter names, although including the names is a good documentation habit)
Comment: getch() and conio.h are not available everywhere, and not portable.  suggest using getchar() and stdlib.h
Comment: why is the code block, beginning with: ' if (IDentry == idArray[x]){' repeated?
Comment: The local variable: 'IDentry' is being used, but never set'
Comment: the code is missing #include  for the strerror() function  in main(), variable 'y' is not used
Comment: function: Stats() says it returns an 'int' but there is no 'return value' statement,  function: Stud_List() says it returns an 'int' but there is no ' return value' statement
Comment: 'register' is a reserved word in C, the code should not use the same name (even with a capitalization difference)  This will compile, but is very bad programming practice.
Comment: file 'information.txt' was opened in Stud_List()  but never closed
Comment: the returned value from fscanf() (and family) should always be checked to assure the input/conversion operations were successful.  in this case, if the returned value is != 3, the fscanf() failed
Answer: Register = fopen ("update.txt","w");

It clears the file every time the file is opened. The 2nd parameter should be changed into "a" so every calls to Stats() append to the end of file.
Comment: Either that, or open the file *once* in `main` and pass it as an argument to `stats`.

Printing every variable to a file


Convert the iterated integral $ \int_{0}^{6}\int_{0}^{\sqrt{36-x^2}}e^{-x^2-y^2}dydx $ into polar integral

Question: $$
\int_{0}^{6}\int_{0}^{\sqrt{36-x^2}}e^{-x^2-y^2}dydx
$$
I tried converting it into polar coordinates using the following equations
$y = \sqrt{36-x^2} \implies y^2 + x^2 = 36 \implies r = 6$
$0=6\cos\theta, 6=6\cos\theta \therefore \theta = \frac{pi}{2}, 0$
$$
\int_{\frac{\pi}{2}}^{0}\int_{0}^{6}re^{-r^2}drd\theta \\
= \int_{\frac{\pi}{2}}^{0} \frac{1}{2}(1-e^{-36})d\theta \\
= \frac{\pi}{4}(e^{-36}-1)
$$
But I keep getting the answer wrong, I am not sure what I am doing wrong
Answer: The region where you are integrating can be described as:
\begin{align*}
R = \{(x,y)\in\mathbb{R}^{2} \mid (x^{2} + y^{2} \leq 36)\wedge(0\leq y\leq 6)\wedge(0\leq x\leq 6)\}
\end{align*}
If you make the change of variable $x = r\cos(\theta)$ and $y = r\sin(\theta)$, the region $R$ can be described as
\begin{align*}
R = \{(r,\theta)\in\mathbb{R}_{\geq0}\times[0,2\pi) \mid (0\leq r\leq 6)\wedge(0\leq \theta \leq \pi/2)\}.
\end{align*}
Given that the correction factor in this case is given by $r$, one arrives at the desired integral:
\begin{align*}
\int_{0}^{6}\int_{0}^{\sqrt{36 - x^{2}}}e^{-x^{2} - y^{2}}\mathrm{d}y\mathrm{d}x = \int_{0}^{\pi/2}\int_{0}^{6}re^{-r^{2}}\mathrm{d}r\mathrm{d}\theta
\end{align*}
From now on, I think you can handle it.
EDIT
Here I provide a picture of the integration region:
Comment: This makes a lot more sense. But I still don't get why I ended with my outer integral as $\frac{\pi}{2} to  0$, when I solve for $r\cos\theta$ for 0 and 6, if that makes any sense.
Comment: @currentexplanation I provided a picture of the integration region.


How can I find dart path in intellij idea

Question: I am stuck .. The intellij idea has said me to paste the path name of dart but I donot know how to know the dart path.. I am very beginner at the dart programming please help me how to find the path of dart that have been installed..
Answer: If you have installed through flutter sdk, which also contains the dart sdk, then it will be at C:\Program Files\flutter\bin\cache\dart-sdk
Answer: If you already ran flutter doctor you should be able to find the dart SDK in your_flutter_sdk_folder/flutter/bin/cache/dart-sdk


Lie group SU(n) and symmetric group S$_k$

Question: Given a simple compact Lie group, SU($n$) group, for $n=2,3,4,...$,
Can we determine what are the allowed symmetric groups S$_k$ realized as a subgroup embedded into SU($n$)?
What is the restriction of $k$ for given  SU($n$) of
$n=2?$
$n=3?$
$n=4?$
(BONUS but not necessary: Are there some general rules one can use to determine any $n$ what is the allowed $k$?)
Answer: In the Euclidean space $\mathbb{R}^n$ you can always construct a standard $n$-simplex $\mathcal{S}_n$ :
https://en.wikipedia.org/wiki/Simplex
This is the convex hull of  $n+1$ points. Furthermore one can show that its isometry group is acting $n+1$-transitively and faithfully (it is not so hard to show that you can exchange any two given points and fix every other). As a result its isometry group is $S_{n+1}$ which is therefore included in $SO(n)$ and thus in $SU(n)$ as well.
So, at least, you can always embed $S_{n+1}$ in $SU(n)$. Actually you have the more general rule:

There exists a subgroup of $SU(n)$ isomorphic to $S_{k}$ if and only if $n\geq k-1$.

Remark: $\Leftarrow$ is direct.
Hint: $\Rightarrow$ use character tables for instance.
Comment: thanks +1, if you give the definite answer for the above three cases -- I can accept you as an answer right away. :)


How to ensure the wax seal on my toilet is set properly?

Question: I recently renovated our upstairs bathroom which included a fresh new toilet. We raised the flange to flush with floor level (technically a hairline above) and placed the wax gasket to the base of the toilet as per manufacturer instructions. It was pretty hot that day and the wax was extremely malleable.
When setting the toilet, we felt little to no resistance from the wax gasket. Past toilet installs I've done I used an oversized wax ring just to be sure, but my brother insisted on using the wax ring that came with the toilet. I flushed a few times, no leaks appearing anywhere. Toilet water level decreases a bit after a flush but stays at that level (assuming toilet flange).
Just wanted to see if not feeling a lot of resistance from the gasket when setting the toilet is OK.
Comment: A) It was a hot day & the was was soft. B) It's not leaking. I'd guess that you're good to go, but I'm not a plumber so I'll leave an answer to the experts.
Answer: From my experience, the wax rings of today are a little softer than the ones years ago and settle easier. Using an oversized ring is bad because it can squish out and impede drainage when flushing. You were smart to raise the flange a hairline above the finished floor as that will also ensure a proper fit. Using the one that came with the toilet was also smart because the rest of your directions would be based on the ring they included. You probably caulked around the toilet after setting it in place. I have always left a weep hole in the back just in case a ring started to fail, you'd see signs of leakage.
Answer:
Toilet water level decreases a bit after a flush but stays at that
level (assuming toilet flange).

There is no relationship between those two factors. The level of the water in the bowl is not dependent on the wax seal. The seal only prevents leaking during the flushing process as water is passing through the trap and  past the wax seal. ( All toilets have built in trap between the bowl and the flange )  After the water has  evacuated the bowl it passes from the toilet to the drain pipe in the floor, That connection is sealed with the wax ring.

It was pretty hot that day and the wax was extremely malleable.

If it was extremely malleable then you would not feel much resistance but that does necessarily mean that a good seal was not achieved.

I flushed a few times, no leaks appearing anywhere.

A leak, if there is one, may not be visibly detectable . If there is path for the water to go down through the floor you may not see any water appearing from under the toilet on the floor.
Comment: The only way to verify it would be to remove the toilet and examine the ring and flange. then you'd have to reset the toilet..... and want to verify if it was seated properly.. :-)
Comment: Cheers, thank you. Is there any way to verify that the toilet has been seated properly. Or just wait for water damage?


Why is my WordPress installation unable to create a directory?

Question: I am a new user of Ubuntu 12.04 64 bit and I want to test WordPress on my local PC installation. I've only installed LAMP and the latest version of WordPress for now. Further actions were

creating a directory www in /home, i.e /home/www
install wordpress in it.
changed Apache to use /home/www instead of /var/www

Apache is running smoothly & wordpress seems to be so as well. However, if try to change my background of my wordpress blog it throws an error

Unable to create directory wp-content/uploads/2012/12. Is its parent directory writable by the server?

Plese help me to resolve my problem.
Answer: The webserver (Apache) runs as user www-data and group www-data by default. Change the filesystem permission on the directory the web application wants to write to - the "parent directory" as mentioned in the error message.
For example, do (prepend with sudo if you're not the current owner and need to elevate your own permissions in order to do it):
chown www-data /path/to/directory

to make www-data the owner which makes it writeable usually, or another approach via groups:
chgrp www-data /path/to/directory
chmod g+w /path/to/directory

If you don't understand this, start reading about how file system permission work in Linux.
Comment: Thank you gertvdijk... I am new comer to Ubuntu Family, So i have a little knowledge how file system permission work in Linux.
Comment: @Ankur No problem - I suggest to practice it using [this tutorial](http://www.howtogeek.com/67987/htg-explains-how-do-linux-file-permissions-work/) (just one out of many).


Prevent clients from using mods on a server

Question: I want to forbid any modded files from a client (xray, other cheats) on my 1.7.10 server.  How can I do this?
Is there a way to force a certain texture pack as well, to prevent people from using transparent ones to find ore?
Answer: If you want a vanilla server, you cannot prevent cheats. If you use forge / bukkit, you can use NoCheat or similar plugins.
The texturepack part is a bit more technical. The way they work is that minecraft looks for textures inside. For example, if it finds grass.png(Example), minecraft will replace the original grass texture.
Lets say my texturepack is as follows:

Grass.png
CraftingTable.png
Dirt.png

What happens is that minecraft looks for all textures, and only finds those 3. In the end, you end up with the new Grass, Dirt and Crafting Table.
 The rest of the blocks are the regular texture. So what you could do is get the "Vanilla Texturepacks" where no textures are changed. Because of the way texturepack sorting works, the server's texturepack is loaded last, overriding the client's texturepack.

Note:

Use resourcepacks. Texturepacks are outdated.
This also applies to entites.
The file names are examples. Do not follow them.
Answer: It is possible to use NoCheat/NoCheat+ to prevent cheating, and Orebfuscator to prevent X-raying; however, to my knowledge there is no way to completely ban all mods.
I don't think it's possible to force a certain texture pack.


Making dense subset of continuous functions using a single continuous function

Question: I have a question about set of continuous function on the compact interval.
Denote the set of all continuous $n$-dimensional real functions on $[0,L]$ as $\mathcal{C}_{[0,L]}$
($\mathcal{C}_{[0,L]} = \left\{ u: [0,L] \rightarrow \mathbb{R}^n\right\}$)
Is there any $T>L$ and a continuous function $f: [0,T] \rightarrow \mathbb{R}^n$ such that
finite combination of $L$-length segments of $f$ is dense in $\mathcal{C}_{[0,L]}$ with respect to supremum norm?
I mean if we define $f_{[t,t+L]}:[0,L] \rightarrow \mathbb{R}^n$ as $f_{[t,t+L]}(\cdot) = f(\cdot + t)$ for $t \in [0,T-L]$, is it possible to find continuous function $f: [0,T] \rightarrow \mathbb{R}^n$ such that any finite linear combination of $f_{[t, t+L]}$, is dense subset of $\mathcal{C}_{[0,L]}$ with respect to sup-norm.
If not, is there any space of functions that satisfies a similar property?
(e.g., rather $L^2$ space satisfies such a condition etc.)
Thank you for your attention.
Comment: Thanks for a comment. It seems Problem of Wiener Tauberian theorem little different from my problem because it is considering translates but I'm considering varying time windows.
Comment: We recently discussed something similar but in $L^2$. In that space the problem is easier, since there is the Tauberian theorem of Wiener which completely answers the question: https://math.stackexchange.com/a/4441449/8157
Comment: The following is the Tauberian theorem of Wiener: https://en.wikipedia.org/wiki/Wiener%27s_Tauberian_theorem
Answer: The answer is positive for $n=1. $
Let $L=2\pi$ and $T=4\pi.$ For a fixed $0<r<1,$ for example $r={1\over 2},$ let $$f(x)=1+2\sum_{n=1 }^\infty r^{n}\cos nx
={1-r^2\over 1-2r\cos x+r^2}$$ Then for $0\le t\le 2\pi$ we get
$$f_t(x)=1+2\sum_{n=1 }^\infty [r^{n}\cos nt\cos nx -r^{n}\sin nt\sin nx]  $$
Assume, by contradiction, that  the linear  span, with real coefficients, of the functions $f_t$ is not dense in $C_{\mathbb{R}}[0,2\pi].$ Then there exists a nontrivial bounded linear functional $\varphi$ on $C_{\mathbb{R}}[0,2\pi]$ vanishing on every $f_t.$ Hence $$\varphi(f_t)=\varphi(1)+2\sum_{n=1}^\infty [r^n\varphi(\cos nx)\cos nt-r^n\varphi(\sin nx)\sin nt]=0 \quad 0\le t\le 2\pi$$ Thus the Fourier coefficients of the function $[0,2\pi]\ni t\mapsto\varphi(f_t)$ vanish, hence $\varphi(1)=0,$ $\varphi(\cos nx)=$ and $\varphi(\sin nx)=0.$ As trigonometric polynomials are dense in $C_\mathbb{R}[0,2\pi]$ we get $\varphi=0,$ a contradiction.
Comment: Thanks for a comment. I was in doubt that rather such a function exists. At least now I know there is some.