Why is a ♭5 chord not a "triad"?

Question: If you look at the kinds of thirds and fifths, you immediately see six obvious combinations:

minor third/diminished fifth
minor third/perfect fifth
minor third/augmented fifth
major third/diminished fifth
major third/perfect fifth
major third/augmented fifth

Four of these comprise the complete set of so-called triads:

m3+d5 = a diminished triad
m3+P5 = a minor triad
M3+P5 = a major triad
M3+A5 = an augmented triad

Of the two which remain, the minor third/augmented fifth combination results in another major triad in 1st inversion. However, the last remaining combination—major third/diminished fifth—is simply ignored, overlooked, or perhaps purposely excluded from triadhood. Why?
I'm sure someone is going to think, "Ah, but triads are constructed by stacking thirds, and the distance from a major third to a diminished fifth is a major second."
And I would say, "Well, if you look at an example like C-E-G♭, it seems to me that E to G♭ is a diminished third, not a major second."
♭5 chords are a thing, particularly in the "triadic" portion of dominant chords, so I must guess that there is some historical reason why they aren't considered triads. (Perhaps because classical theory was well-established before jazz came about?) What is it? Or am I missing something?
Comment: @leftaroundabout -- I am not sure that there needs to be any meaningful explanation; it's just nomenclature. Triads are formed by stacking major and minor thirds, not by adding a third and a fifth to a root or stacking intervals other than major and minor thirds. As to why the nomenclature is the way it is, I guess that is historic.
Comment: I agree, there's no really meaningful argument why the diminished chord should be considered a triad but the ♭5 chord not. It's just historic.
Comment: @DavidBowling the definition of triads as stacked thirds is backwards however, because fifths are clearly the more fundamental interval. In fact, a (consonant / post-Pythagorean) minor third is constructed as the _difference_ between a major third and a fifth, so you can't really construct any of the triads except the augmented using only this "standard definition".
Comment: Somewhat related: https://music.stackexchange.com/questions/56332/triads-with-thirds-that-arent-major-or-minor
Comment: @leftaroundabout -- even if you require that a minor third be constructed as the difference between a major third and a fifth, how does this prevent the construction of the other triads? You can still define the triad in terms of major and minor thirds (which are constructed in a certain way). And that the fifth is more fundamental (I don't disagree) seems irrelevant: why not define in terms of major and minor thirds?
Comment: @DavidBowling it doesn't prevent the construction of the other triads, but it makes it questionable why we consider _the class of 3-note chords that can be constructed by stacking major and minor thirds_ as particularly meaningful. What I'd really argue is, the class of 3-note chords we should consider as particularly meaningful is that which can be constructed from only pure fifths and major thirds. That gives the major, minor, augmented and sus9 chords, but no diminished. Those, for their minor thirds, basically require an extra "virtual note" at an interval of a fifth, making a dissonance.
Comment: @leftaroundabout -- that is an interesting viewpoint; it reminds me of George Russell's Lydian Chromatic Concept. I like the idea of building in fifths better than mixing thirds and fifths. I am not at all opposed to thinking of triads more broadly. I think a lot more could be said, but if your point is that stacking major and minor thirds is conventional, I agree. If you want to suggest that there may be better ways to define "triad", I would probably agree. I don't think I'd agree that the traditional definition is meaningless, as I think it fit harmonic practice well at one time.
Comment: Why don't we name I-♭♭♭3-5 a triad as well? It has I-♭♭♭3 as a doubly-diminished third and ♭♭♭3-5 as a doubly-augmented third, and doesn't form an inversion of any other triad. Ultimately, it comes down to convention, and I can't explain that convention, but it's an interesting thought to think of how many "triads" one could make. I'm sure that has an answer somewhere on this SE too.
Comment: It isn't actually a 1st inversion of a major triad: see https://music.stackexchange.com/questions/127519/what-chord-do-we-get-by-raising-the-fifth-of-a-minor-triad
Answer: The triads found in traditional harmony are built by stacking major and minor thirds. The list of triads generated in this way is short:

    major 3rd + minor 3rd  -->  major triad
    minor 3rd + major 3rd  -->  minor triad
    major 3rd + major 3rd  -->  augmented triad
    minor 3rd + minor 3rd  -->  diminished triad

Diminished, doubly diminished, augmented, and doubly augmented thirds are just not used to build the harmonic structures called triads in traditional harmony. That does not mean that C, E and G♭ can't be used together, and you can make up your own "triads" if you wish. These days some people talk about sus4 triads and Lydian triads, for example.
"♭5 chords are a thing, particularly in the 'triadic' portion of dominant chords." Sure, ♭5 chords are a thing, but here the ♭5 is considered an alteration. Such a chord may be written as C7(♭5), or C-7(♭5) for example. Here, the underlying chord quality (major, minor, diminished, augmented) comes first, then the highest degree of upper structure (7th, 9th, 11th, 13th), and finally added pitches or alterations (sus4, add9, ♭5, ♯9, etc.). Here, I don't think that you should say that the ♭5 belongs to the "triadic portion of the chord", but rather that it is an alteration of the underlying chord quality.
Comment: "So saying a ♭5 is integral for diminished triads and merely an alteration for a ♭5 chord is anything but consistent." The trouble is, in a traditional context triads are not defined in this way. They are defined in terms of stacked major and minor thirds. There are many other note collections, but this is just a matter of how we name different types of collections. "Triad" is just a name. It refers to something specific, which in common use may differ from what formalized music theory says, or even from what may intuitively make sense.
Comment: So far, this is the only answer that both makes sense and seems consistent, to me. Stacking thirds other than major or minor and calling them triads would lead to all kinds of "chords" that I might call "degenerate", in the sense that they would have wildly different harmonic functions from what we currently call triads.
Comment: I don't think it's consistent... thirds and fifths *both* play a role in determining the quality of a triad. So saying a ♭5 is integral for diminished triads and merely an alteration for a ♭5 chord is anything but consistent. I agree with this and other answers that if we started building "triads" off diminished or augmented thirds, we'd end up with a mess. I see now that stacked thirds (of the major and minor variety) are the traditional way to look at triad construction. Continued...
Comment: However, I feel that looking at the combination of third and fifth would make a lot more sense. I also know my feelings aren't going change anything. I hoped there was a self-consistent explanation that I was overlooking, but I don't think there is one.
Answer: Tonal chord analysis is based around the idea of stacked thirds that naturally occur in some diatonic scale. 1-3-♭5 doesn't naturally occur. This is also why 1-♭3-♯5 doesn't exist, not because it's enharmonic to another major triad.
Of course, you can write anything you want, but once you get away from stacked diatonic thirds, you get far enough away from classical tonal theory that it doens't make sense to use the same notation system. Within tonality, you're most likely to encounter this combination of pitches as 1-3-♯4, which would get analyzed differently.
Comment: I like this explanation, but where, in chords built off diatonic scales, does one encounter an augmented chord? (My understanding of "diatonic scale" is "the major scale and its modes".)
Comment: I think that the harmonic minor scale, treated as a melodic device, doesn't really exist (at least in tonal music). But the harmonic minor scale as a set of pitches--a musical alphabet--totally exists, and so it makes sense to describe chords as being a combination of those pitches.
Comment: I have come across III+ in minor pieces. I will try to find an example. Pretty sure it was Bach. I have also used it in my own composition, but I probably would not have used it if I hadn't heard it somewhere else and tucked it away in my musical subconscious. III+ is a pretty cool chord. However, analysis could say that the altered note (say a G# in CEG#) is some kind of passing tone instead of calling the set of notes it's own chord. In analysis, different people can argue over the meaning of the same thing. Thankfully, it is not analysis that produces music.
Comment: @trw Some claim it's a variant of III in the harmonic minor scale, but that's bunk. III+ doesn't exist, as far as I'm concerned.
Comment: @HeatherS. I'd be interested to see an example of III+ in "diatonic harmony" for sure (something baroque especially), please do post if you think of one!
Comment: @Some_Guy, I will get back to you in the next few days. I was rummaging through Mendelssohn Songs Without Words today waiting for a student to arrive for a lesson, and behold!, a III+. I will look in my Bach, too. I'm sure it's there.
Comment: @MattPutnam, the harmonic minor is alive and well in the music of the Middle East.
Comment: I should have to look up first, but just by memory I would say in the Violin Concerto in a-minor 1041 by Bach in the 2nd section there is a fitfth-fall sequence iv-vii-III+-vi ....
Answer: Major triad = maj3 +min3.
Minor triad = min3 +maj3.
Diminished triad = min3 + min3.
Augmented triad = maj3 + maj3.
All these common stacked thirds use only maj or min 3s.
A dim3 ends up as the same note as a M2 (in sound, in 12et), while an aug3 ends up, in similar manner, as P4. So, I guess there's no real point in calling them another third, to be stacked, as the notes will make another named chord.
C>E (M3) + A (P4) is Am.
C>D (M2) + G (P4) is Csus2.
C>F (P4) + G (M2) is Csus4.
C>F (P4) + Bb (P4) is Bbsus2.
C>E (M3) + F# (M2) is C b5
C>Eb (m3) + Bb (P4) is Cm7.
C>F (P4) + A(M3) is Fmaj.
C>F (P4) + Ab is Fm.
C>Eb (m3) + F (M2) is F7 (most of!)
Think I've covered most if not all eventualities, hoping to show that 'stacked' dim and aug thirds (aka M2 and P4) already have names, mostly, and would duplicate things unnecessarily.
Wouldn't surprise me if this gets downvoted - it's somewhat avant-garde, so please attach reasons!
Comment: No downvotes here; I once asked a question related to your answer, pointing out that they're largely enharmonic with other chords: https://music.stackexchange.com/questions/56332/triads-with-thirds-that-arent-major-or-minor
Comment: @ToddWilcox - yes, but partly that was my point. I was saying that if we agreed that dim and aug 3rds could be used in 'stacked thirds', they would sound like other chords that already have other names. For example, if I played C-E-Gb (with a dim3), and you played C-E-F# (with a M2), they would sound pretty similar, I guess, so here, I've tried to rationalise by giving effectively enharmonic names. I could have gone the other way- maybe I should have - but the offering here took a bit of working out, and I'd got a tired brain by then.
Comment: Would describing the interval as a diminished 3rd that is not major or minor be clearer than saying it's enharmonic to a major 2nd? If it's spelled C-E-Gb then it's not actually a 2nd but some kind of 3rd.
Comment: @Richard -- the question and discussion you linked to was interesting and seems quite relevant here; I hope that OP takes a look at it.
Answer: You're overthinking this.  If we only allow 'triads' to be derived from major and minor scales, or built from major and minor thirds, it's a modified triad.  It's only a label.
Answer: Your minor third/augmented fifth combination is not ignored: it is indeed a thing: it is 3 notes of the French sixth chord.
Wikipedia's example is A♭CDF♯. Transpose down a major 2nd and you get G♭B♭CE, which includes your chord's 3 pitches. When used as a French 6th, it is a predominant to B♭ minor (or B♭ major, if either there's a tierce de Picardie or the G♭ was just a chromatically lowered G).
Answer:
well, if you look at an example like C-E-G♭, it seems to me that E to G♭ is a diminished third, not a major second.

Triads are formed by 'stacking' major or minor thirds, as you already noted. So, whether or not a major second seems like a diminished third is irrelevant.
Think of it this way: if we 'stacked' diminished thirds, then, C-D-E would be considered a triad.
Comment: E to G♭ is absolutely a diminished third.
Comment: E to G♭ does not _seem_ like a diminished 3rd; it _is_ a diminished 3rd, and not a major 2nd.
Comment: _C-D-E would be considered a triad_  ?!? This is flat out wrong: C-D-E is 1/2/3. A triad is 1/3/5 - two 3rds of some sort. You only have one 3rd in C-D-E : C->E.
Comment: @DavidBowling *"E to G♭ does not seem like a diminished 3rd"* That is why I put it in italics. I was simply making use of the language that he had chosen.
Comment: @Tim: Going up or down a diminished third from D would yield B# and Fb.  If diminished thirds could be part of a triad, that wouldn't allow C-D-E, but would allow B#-D-Fb, which would sound identical.
Comment: @Stinkfoot That was my exact point.
Comment: Sure, but that doesn't get us anywhere. Technically, the interval between E and Gbbb is a "third" (because we used the let s E and G), but we don't consider that interval for making triads.
Comment: @DavidBowling Edited for clarity
Comment: Ah, I see what you are getting at; it wasn't clear to me from your answer. OP has an imaginary dialog in which the first interlocutor states incorrectly: "the distance from a major third to a diminished fifth is a major second," and the "seems to me" is part of the response.
Comment: Perhaps a little confusion: a diminished *chord* has a dim5, but certainly no dim3...   And - dim3s, from C ought to be C - Ebb - Gbbb - I guess!
Comment: No. Your example would evaluate to **C - Ebb - Gbbb**, which is two diminished 3rds, and according to the argument might be considered  a triad of the form **C-E-G**.
Comment: @Stinkfoot His argument was, "...  it seems to me that E to G♭ is a diminished third, not a major second". So, that is why I pointed out that if we 'stacked' diminished thirds we would end up with a 'triad' of `C-D-E`, which is not a triad.
Comment: @DougRisk that's not the way intervals work.  C and D isn't ANY third, it's a second.  When we name intervals, the letter name matters.  So C and D# is an augmented second, which is *enharmonically equivalent* to a minor third, not *not* a minor third.  Conversely, E and G♭ are a diminished third and E and F♯ are a major second. That may seem picky, but it does make a difference (even if in equal temperament, the notes sound exactly the same).
Comment: C-D-E would be Cadd9, not any sort of triad unless you want to include quartal triads and secundal triads in the mix.
Answer: If we have a look at the status of contemporary qualities, as a theorist, we are a bit in the twilight zone. Triads are built upon stacking min/maj thirds, while sevenths can be subdivided into qualities built upon staking min/maj thirds, and those that also include dim/aug thirds. But there is additional inconsistency, not all sevenths stacked the above way have a unique quality.
Traditional stacking:
stack min/maj thirds
Contemporary stacking:
stack min/maj/dim/aug thirds as long the notes approximate the main intervals (m/M3, d/p/A5, m/M7). One exception to this rule is the very symmetrical m3-d5-d7.

The following altered qualities are left in nomandsland, but deserve
  their own quality in my opinion: maj(b5), m7(#5), mΔ7(#5), 7(b5),
  Δ7(b5)

Triads
Traditional stacking
- quality  i1  i2   3th 5th
- dim      m   m    m   d      diminished triad
- min      m   M    m   p      minor triad
- maj      M   m    M   p      major triad
- aug      M   M    M   A      augmented triad

Contemporary stacking
- quality  i1  i2   3th 5th
- min(#5)  m   A    m   A     inversional equivalent of major triad
- maj(b5)  M   d    M   d     <nameless quality!>

Sevenths
Traditional stacking
- quality  i1  i2  i3   3th 5th 7th
- o7       m   m   m    m   d   d      diminished seventh
- ø7       m   m   M    m   d   m      half-diminished seventh
- m7       m   M   m    m   p   m      minor seventh
- mΔ7      m   M   M    m   p   M      minor-major seventh
- 7        M   m   m    m   p   m      dominant seventh
- Δ7       M   m   M    m   p   M      major seventh
- +Δ7      M   M   m    m   A   M      augmented-major seventh

Contemporary stacking
- quality  i1  i2  i3   3th 5th 7th
- oΔ7      m   m   A    m   d   M     diminished-major seventh
- m7(#5)   m   A   d    m   A   m     <nameless quality!>
- mΔ7(#5)  m   A   m    m   A   M     <nameless quality!>
- 7(b5)    M   d   M    M   d   m     <nameless quality!>
- Δ7(b5)   M   d   A    M   d   M     <nameless quality!>
- +7       M   M   d    M   A   m     augmented(-minor) seventh

Why is a ♭5 chord not a "triad"?


Python typing return type of class composition's method

Question: I have a class Human which can have a pet and a method to make it talk, either a Dog or a Cat. I initialize the Human with a Dog, and the method pet_speak has the correct return type hint Literal["Woof"].
If I change the Human's pet to a Cat after initialization, the method return type hint isn't updated to Literal["Meow"].
Is there a way to change this behavior? This is a simplified version of my problem, creating two classes, such as, HumanDog and HumanCat is more complex.
class Cat:
    def speak(self): # implicit return type hint Literal["Meow"]
        return "Meow"

class Dog:
    def speak(self): # implicit return type hint Literal["Woof"]
        return "Woof"

# Class `Human` has a `pet`, and can call its `speak()` method
class Human:
    pet = Dog()

    def pet_speak(self):
        return self.pet.speak()

# Helper function to change `human`'s pet
def change_pet(human):
    human.pet = Cat()
    return human

bob = Human()
woof = bob.pet_speak() # Return type is correctly Literal["Woof"]
bob = change_pet(bob) # change attribute `pet` to `Cat`
meow = bob.pet_speak() # Return type is Literal["Woof"], but should be Literal["Meow"]

The closest question I could find was Can you type hint overload a return type for a method based on an argument passed into the constructor?, but it also adds an overhead to every Human method and subclasses.

Sorry if I dumbed the problem down too much, here it's more similar to what I'm trying to do:
from __future__ import annotations

class Api:
    def request(self):
        return "Response"

class AsyncApi:
    async def request(self):
        return "Response"

class Database:
    api: Api | AsyncApi = Api()

    def get(self):
        return self.api.request()

def Async(database):
    database.api = AsyncApi()
    return database

async def main():
    db = Database()
    db.get()
    adb = Async(db)
    await adb.get() # typing error

Comment: You can't use a literal for the return type of `Human.pet_speak()` because the type of `Human.pet` can be anything.
Comment: You should define an abstract base class for all pets, and specify the general return type (e.g. `str`) for all of their `speak()` methods.
Comment: @Barmar Thank you for the help! I can define `Human.pet` as `Cat | Dog` but the problem is still there. Having a general type doesn't help, I need the type hint to be exactly the only possible outcome, `Literal["Woof"]` or `Literal["Meow"]`.
Comment: Could you perhaps provide a more realistic example? What are you trying to achieve?
Comment: > { but it also adds an overhead to every Human method and subclasses. }

Could you elaborate what you mean by "overhead" here?
Comment: It makes little sense to be so specific in the `Human` class. Next you'll want to add `bird`, later you'll add other types of pet. So all you can really say is that `petspeak()` will return a string.
Comment: Thanks for the comments, @decorator-factory. The overhead I mean is that I have to add `cast(T, ...)` to every new method, but I think this might indeed be the best way to do it. Sorry if my original problem wasn't too clear, I updated the answer with one more similar to what I'm having.
Comment: @Leonardo ah, I see now :) Well, keeping both a sync and async client with DRY code seems like an unsolved problem, at least in Python (unless you want to mention the M-word). If there aren't dozens of requests I would just make two classes to be honest. This is also more flexible: if you need to make two requests in a single method or if you want to make retries, your way will not really work.
Comment: @decorator-factory what would the `M-word` be? I just want to solve this problem, and I have no strong opinions :) Duplicating the class is more complicated, since I have more than one `Database` class
Comment: The M-word is "monad" - it's a construct from functional programming that lets you, for example, write a single piece of code that will work in both synchronous and asynchronous context ([this article explains it](https://sobolevn.me/2020/06/how-async-should-have-been)). I doubt it's relevant here, but it's a path one can take
Comment: Why do you have these `Database` classes? Why not just use the `*Api` classes directly? Is there something more to the `Database` classes maybe?
Comment: I don't think I would restructure the entire codebase with Monads to accomodate this. For now the answer to the other question I posted will do it, using generics and overload.

`Database`s are some interfaces to some services API's. So let's say I want to create a `Youtube` class, it will have an `api_client`, either sync or async, and maybe some methods specific to it, such as `upload_video`, `like`, `report`.
Answer: If you add the missing annotation run the code through Pyright (or Mypy), it will spot an error here:
def change_pet(human: Human) -> None:
    human.pet = Cat()
    # ^
    # Cannot assign member "pet" for type "Human"
    #  Expression of type "Cat" cannot be assigned to member "pet" of class "Human"
    #    "Cat" is incompatible with "Dog"
    return human

Indeed, the type of human.pet is Cat. Generally, the type of an object can't change when you're mutating it. This makes sense, for example because an object might be shared:
class CatHumans:
    def __init__(self, humans: Iterable[Human]) -> None:
        # somehow establish that all the `humans` have a cat
        self._humans = list(humans)

    def do_something_assuming_humans_have_cats(self) -> None:
        for human in self._humans:
            assert human.pet.speak() == "Meow"
            ...

alice, bob, charlie = make_humans_with_cats(3)
cat_humans = CatHumans([alice, bob, charlie])

alice.pet = Dog()
cat_humans.do_something_assuming_humans_have_cats()

It would be very difficult if not impossible for type checkers to track situations like this.

I don't know what real problem you're solving, but I have two solutions:

Specify a more general type for pet:

A common protocol/base class:
class Human:
    pet: Animal = Dog()

Or a union type:
from typing import Union

class Human:
    pet: Union[Cat, Dog] = Dog()

Make a generic class

from typing import Generic, TypeVar

Pet = TypeVar("Pet", bound=Animal)

class Human(Generic[Pet]):
    def __init__(self, pet: Pet) -> None:
        self.pet = pet

This still doesn't let you have the same object be Human[Dog] today and Human[Cat] tomorrow, but you can have distinct Human[Cat] and Human[Dog] objects.


SSRS report with dynamic query taking parameters defined from a database

Question: My overall goal is to produce an SSRS 2012 report which displays metrics about workers in different teams. Additionally, I would like to have some custom dropdown (customizable per team) where only particular workers are displayed.
For example, I have 2 Projects - Project1 and Project2. Project1 wants dropdown choices which allow them to show their workers in San Francisco and New York teams. Project2 wants a dropdown that allows them to show workers in Houston and San Francisco teams.
Teams are not a construct represented by data in the database. I also want to arbitrarily define custom Teams in the future (Team that works from home, Team that knows C++, etc..). The "All" team means no filtering.
The query for a project would be
select Member.MemberName, Member.MemberWork from Member where Member.Project='Project1'

For Project1, San Francisco team, I would write
select Member.MemberName, Member.MemberWork from Member where Member.Project='Project1' and Member.MemberID IN (123, 125, 127) /* teams are not stored in the database so I need to hardcode member IDs that compose a team */

The way I am storing the relationship between each custom dropdown choice is as follows
CREATE TABLE [dbo].[TeamQueries] ([ProjectName] [nchar](128) NULL,
[TeamName] [nchar](64) NULL,[TeamQuery] [nchar](3096) NULL
) ON [PRIMARY]

Example Rows in this table would be in this image (which I cannot post from lack of reputation)
The query (the dataset is called "data") in the SSRS report is as follows
 declare @query nvarchar(max)
    set @query= 'select Member.MemberName, Member.MemberWork from Member where Member.ProjectName=' + @ProjectDropdown + ' and Member.MemberID IN (' + @TeamQuery + ')'
    exec(@query)

The @ProjectDropdown is a single valued TEXT parameter with default and available values coming from a query
select ProjectName from Projects
The @TeamQuery is also a single valued TEXT parameter with default and available values coming from a query
SELECT TeamName  ,TeamQuery FROM TeamQueries
  WHERE (ProjectName=@ProjectDropdown or ProjectName = 'All')

Choosing Team1 and San Francisco in the available dropdowns, the error message I get is:

Query execution failed for dataset 'data'. Incorrect syntax near
  '127'.

The dropdowns get populated fine. By choosing Project1, I get choices of San Francisco and New York in the dropdown.
My question is - what's wrong, how do I get this to work? The general issue is I want a where predicate string (that is part of an IN clause) to come from the database and be optionally applied in SSRS.
Here are some things I have tried.

I tried to make this construct work outside of dynamic SQL. for example, using an OR construct to avoid the select Member.MemberID from Member and have the following

select Member.MemberName, Member.MemberWork from Member where member.ProjectName=@ProjectDropdown and (@TeamQuery IS NULL OR Member.MemberID IN (@TeamQuery))
I kept getting VARCHAR to int conversion errors. I tried
select Member.MemberName, Member.MemberWork from Member where Member.ProjectName=@ProjectDropdown and (@TeamQuery IS NULL OR CONVERT(VARCHAR(Member.MemberID)) IN (@TeamQuery))
or converting @TeamQuery to INT by SPLIT and making TeamQuery a multi-valued parameter.
I tried printing @query in SSRS with the hopes of some debuggability but I cannot see the query that SSRS is using.
If I hardcode the parameter of @TeamQuery in SSRS, the query does work. I suspect something with strings and quotes - the database is retrieving something slightly different than I am expecting (perhaps I need to strip quotes?)
Answer: The issue was the definition of the column. I mistakenly made the column definition nchar rather than nvarchar. This caused extra padding and the query error.


Flask Form, keep values after submit

Question: I have a flask form that has some values for a given event. On submit I redirect the user to page where I take the values from the form and calculate some statistics about the event. The user can accept these values, and submit the event to the database, or click an edit button which will take them back to the form for them to modify the values. The issue is since the form has already been submitted, when they click edit and are redirected back to the form, all the values are gone. I want the values to stay because chances are they will only be modifying one or two fields and I don't want them to have to re-enter all of them. Any ideas how to do this?
Comment: Hard to say without seeing any code. But why can't you store the values in the DB and load the values when you open the form? If the user wants to edit the values, you just update the values in the DB.

Or, can't you store the values in a global dictionary and just re-load it when you go back to the form if some values in the dictionary exist? Again, hard to say since you have no code sample but this is just some thoughts which you can think about.
Comment: @Payam thanks for the reply! Currently I am storing in a global dict, that just didn't seem like the cleanest way to do it. I'm new to flask so I didn't know if there was a clean way that the flask form could handle this.

`if (current_user.username in current_app.config["current_form"] and request.method != "POST"):
    form = current_app.config["current_form"][current_user.username]
else:
    form = Form()`
Answer: You can let Flask-wtf generate the form automatically, and it can remember the user input. If you pass the form instance to your Jinja template like this:
form = SomeForm()
return render_template("template.html", form=form)

A minimal example of a form:
class SomeForm(FlaskForm):
    name = TextField(label='name', default="")
    save = SubmitField(label='Save', description="Save")

And in your Jinja template:
<form method="post" action="the url" class="form-inline">

        {% for field in form %}

{{ field.label }} {{ field }}

        {% endfor %}

</form>

Answer: You can use window.history.back();.
From History API:  "This acts exactly as if the user clicked on the Back button in their browser toolbar"
This works because the browser saves the users inputs , all except for the type="password" ones

Flask Form, keep values after submit


Cannot Find CSS Class For A Custom Block

Question: Hello due to much help from here in the past im starting to theme whatever part of my drupal site that i like. Its great. Ive ran into a a strange one though. I have created a custom block (block 130). You can see it on top of my site
BBC Live Olympics | Add Olympic Comment | Football Livescore | OLB Olympics
http://onlinebanter.com/latest
For some reason it doesnt have any div class Im trying to change the p bit.
Ive tried various things but still cant seem to find this blovk. Does anyine have any suggestions?
Thanks
Comment: durrr the p class was in the block itself. sorry.
Answer: You don't have a class, but you do have an ID so you can use:
<code>#primary p {color:red;}
</code>
Note: there is also a nice module call block class (http://drupal.org/project/block_class) that you can use


Performance issue with too many open http sessions in jenkins?

Question: we are using Jenkins Enterprise for a while now.
Since the latest update it seems as if the performance dramatically decreased when having multiple http sessions open.
Our experiments showed that there seems to be a limit (varying but always between 10 and 30) of open http sessions that can be served well while adding even one more takes everything down. As soon as we are closing a few sessions everything is back to normal
CPU, Memory and IO on the master machine are OK.
Anyone else experienced this recently?
Tobias
(technical details: Hosting the master machine on a Windows Server 2003 box, same happens on Win7 and XP, running in JRE 1.7, Jenkins ver. 1.466.12.1 (Jenkins Enterprise by CloudBees 12.11))
Comment: Did you notice this change going between versions in the 1.466 series itself, or going between 1.466.x and say 1.447? I think it's worth opening a ticket, and perhaps providing the scripts you use for testing.
Answer: This has been filed as JENKINS-16474 and is under investigation.


Dependency Injection in ApplicationEventHandler. Bug?

Question: Umbraco v7.5.8
I have bunch of problems with DI setup (shown below).
1) Neither OnApplicationInitialized, nor OnApplicationStarted (and other) events firing if constructor takes parameter(s).
2) Backoffice is broken. It's not possible to access a content node. Exception message is:
An error occurred when trying to create a controller of type 'ContentController'. Make sure that the controller has a parameterless public constructor.
<code>    // Application handlers
    public class UmbracoApplicationEventHandler : IApplicationEventHandler
    {
        private IMenuManager _menuManager;

        public UmbracoApplicationEventHandler(IMenuManager menuManager)
        {
            _menuManager = menuManager;
        }

        public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            ContentService.Saving += UpdateMenu;
        }

        private void UpdateMenu(IContentService sender, SaveEventArgs<IContent> saveEventArgs)
        {
            _menuManager.UpdateMenu();
        }
    }

// Unity config:
public static class UnityConfig
{
    public static void RegisterComponents()
    {
        var container = new UnityContainer();

        container.RegisterType<IMenuManager, MenuManager>();

        GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
    }

}

// Owin Startup:
public class UmbracoStandardOwinStartup : UmbracoDefaultOwinStartup
{
    public override void Configuration(IAppBuilder app)
    {
        //ensure the default options are configured
        base.Configuration(app);

        UnityConfig.RegisterComponents();
    }
}
</code>
Answer: Please read: https://our.umbraco.org/documentation/reference/using-ioc.
You need to register and build your container on OnApplicationStarted event, not earlier if you want to make it work with Umbraco.
Comment: Thanks, Marcin. The approach in the article works OK with regular controllers. But it doesn't work with ApplicationEvenHandler, due to lack of supporting parametrized constructors (as I stated in topic description). Any ideas?
Comment: Why you want to inject your MenuManager straight to the ApplicationStartup class? I would create a service to handle this method(s) which would have it injected inside it's own constructor.
Comment: Because ApplicationStartup depends on MenuManager. For example, I'd like to trigger MenuManager.UpdateMenu() each time document gets published in CMS.
Comment: @MarcinZajkowski Were you able to make it work with a `ApplicationEvenHandler ` constructor taking a parameter? Or is Umbraco just shit when it comes to IoC? Seems to be the latter since there hasn't been a resolution on this since March 2017...
Comment: @Ash there is no issue with using IoC/DI with Umbraco, but it needs to follow the instruction posted above - those two classes are fired up when the app is starting and all the registrations should occur after that - no injections to those directly. Besides that - all fine :)
Comment: @MarcinZajkowski So essentially, can't have the constructor accept parameter(s)...which was your original requirement?
Comment: Of course, we can. We only can't have them in those 2 classes/interfaces which are starting before the IoC registration should occur.
Comment: @ivan-studenikin I repeated this word - studenikin - for many years, don't have idea where i got this word from... And now I see the person with such lastname, hahaha =)))


Saxophone and Dentures

Question: Some years ago I was a pretty hot alto player but the guitar was always my first instrument and I have been a busy pro for much of my working life. I had to drop the horn.
Now I am thinking of playing again. But time hasn't been kind to my teeth. The dentist tells me I will need a denture very soon - as soon as finances and time allows.
Am I going to be able to play with a denture? Are there special dentures for musicians?
I know that one option is dental implants. I'm told that these are just as good as having your own teeth. The problem is they are about $5000 per tooth; I just can't afford it.
Comment: Have you asked the dentist for his/her thoughts? They may not know a lot about music but I bet they know a lot about teeth. ;) also they may have encountered this before and most likely have access to resources that will have a good answer.
Comment: Possibility of off-setting the cost against tax? As a pro player, it's feasible. Which teeth? If it's top, there shouldn't be a problem, as they don't bite the mouthpiece.
Answer: There are certainly cost-benefit trades here.  One significant benefit to choosing implants is that the shape of your oral cavity remains unchanged.  If you go with any kind of denture which includes a plate (covering part or all of the upper palate), the volume and shape of the cavity will change, and that can affect air flow.
In any case, I strongly recommend talking with medical professionals rather than random strangers on the internet whose tooth problems may or may not be similar to your own.
Answer: After forty years of playing I had 17 teeth extracted (also known as the most unexciting hour of my life) Unsurprisingly I was unable to play very well subsequently. Five years down the track I can wear my dentures to eat food but find it easier to play with none. Palm key notes are difficult on sop and I am contemplating baritone as the bigger saxes do have a less demanding embouchure. I do not have implants and am sure they would help.
My advice is to look after your teeth!
Answer: I don't know much about dentures, but I have had lots of dental work done on myself.
When you get dentures, you're embouchure is going to change big time and it's gonna be hard to play. But on the bright side, that is your new embouchure. As you continue to play, you're going to adjust. It'll be like doing tone work all over again. In your head you're going to hear the tone that you want, and, using your ear and mouth/throat/embouchure, you're going to adjust over time.
It's gonna probably suck at first because it'll feel weird and you're tone will probably be pretty cruddy. But you will adjust and you'll be back to normal.
Answer: I'm not a wind player but I do have long term experience (40 years) with dentures.
In my personal experience a full set "work" better than a partial set. I have a full set with a metal plate (which is a stainless steel casting) and they are as rock-solid as normal teeth. In fact at the first fitting of the plate, it "stuck" in place so firmly it took the dentist about 10 minutes to remove it! I wear them 24/7/365 and basically never think about them. The plate has also lasted "for ever" - it's now more than 30 years old and works as well as when new.
They are held in place by the surface tension in the saliva which fills the (tiny) gap between the plate and the mouth structure - not by being a mechanical "tight fit". The thinner the saliva layer (i.e. the more accurate the fit) the firmer the grip.
From my personal experience I think a mixture of natural teeth and individual implants may be more problematic, since natural teeth move around in the gums as a person ages, but implants do not. Certainly, partial denture plates don't work so well, since as the natural teeth grow and move the shape of the gums changes and the fit with the denture plate becomes worse.
Note also, in the UK you can get a "full set of implants" which is effectively a denture attached to only 3 or 4 fixing points in the jaw, not a separate implant for each tooth. That should reduce the costs compared with "individual tooth implants" - but I don't know anything about the US healthcare cost structure (except that, viewed from the rest of the world, it seems extortionate).
Some of these options may involve removing healthy teeth - which is an irreversible procedure, of course. Professional advice, both musical and dental, would seem a very wise course to take.
Answer: Just to add my two cents, my fiancé had to get dentures both top and bottom. The first six months are rough for here because her gums are swollen and constantly having to go in and get them re fitted as the swelling goes down. But there's a couple alternatives. They now have dentures where they surgically add titanium rods in your mouth where the dentures snap in and off like a button on your clothes. There is also glue you use so they stay in your mouth all day long and I guarantee you have no worries about "blowing the horn again" after the procedure. If you go the more exspensive route then there's always porcelain veneers?

Saxophone and Dentures


Turning product of multiple variable factors with constants into Big-O

Question: I have a function which requires $(m+1)k(n+1)$ operations. How would I describe it in Big-O notation? I guess I need to keep the constants in $(m+1)$ and $(n+1)$ since they ensure that at best the complexity is $O(k)$ which is still not constant.
Comment: @MånsNilsson because to define the complexity, you need all three input variables. The number of operations scales with each of them linearly.
Comment: Then, I think the correct notation would be $O(mkn)$
Comment: We can ignore the "$+1's$" if $m$ and $n$ are large.
Comment: Does the input depend only on $k$ ?
Comment: @Peter No, they are all independent input variables.
Comment: @Peter Why, do you think?
Comment: @Peter But we don't know that.
Comment: But the text clearly indicates that $m,k,n$ are integers and that they can (in theory) be arbitary large. Without this assumption, we can only guess the complexity. Anyway, $O(kmn)$ is the worst possible complexity, since we know that the required number of operations does not grow more than linear in any variable.
Comment: If we assume that $m,k,n$ can be anything, fore example , bounded , then, the complexity could as well be $O(1)$
Answer: If you have no information about $k, m, n$, then the best you can do is $O(kmn + km + kn + k)$. I'll argue that you can have a case where each of the terms in this sum could dominate the others:

If $m, n = \frac{1}{\sqrt{k}}$, then you have $O(1 + \sqrt{k} + \sqrt{k} + k) = O(k)$.
If $n = m = k = w(1)$, then it should be $O(kmn)$.
If $m > 1, n = \frac{1}{m}$, then you have $O(k + km + \frac{k}{m} + k) = O(km)$.
You can construct similar to point 3 for the result to be $O(kn)$.
Comment: This answer confuses me. The two users who commented on my original post agreed that $O(mkn)$ was the right way to go, since constants don't affect the asymptotic behavior in the long run (i.e. for big enough $m$ and $n$).
Comment: Case 2 of my answer covers the "big enough m and n" case. I totally agree that if m and n are big, then the answer is trivially O(mnk). I was only trying to cover for all possible edge cases. For instance, m could be a probability, in which case it could be something of the order $1/2^n$. Then, like you mentioned in your question, the + 1 cannot be ignored. Your question says nothing about what these parameters are, so my answer is intended to cover all possibilities. Let me know if this is not clear.
Comment: If something requires m + 1 operations, you could say $O(m + 1)$, but you would drop the constant so it becomes $O(m)$, even if m isn't large. Doesn't the same rule apply in my case in general?
Comment: No, it wouldn't. For instance, if m = 1/n where n is large, then O(m + 1) should be O(1/n + 1) = O(1). It would be wrong to say O(m) in this case right?
Comment: Let me say something slightly different which I hope might be helpful. Normally, when you want to say O(max(a, b)), you can write it as O(a + b). You can surely see why. So when you are saying O(m + 1), you really want O(max(m, 1)). Now, in MOST cases, m would be much greater than 1, so like you said, you end up with O(m). But if m < 1, then you have O(1).
Comment: In the example I constructed m = 1/n with n large, so m is less than 1. That's why m would dominate. An example of where this could occur is if m is a probability or an error parameter. They are always <= 1.


When the effect size of a covariate is high and yet not significant

Question: I was reading this answer to the question on whether all covariates should be kept in the model or just those that are statistically significant, and I noticed the point number 2:

The effect size of a covariate may be high, even if it is not significant.

And, this has always been on my mind, why we could have such a situation. Can you please elaborate this point on why this could happen and maybe a hypothetical example?
Answer: Significance means detectability.  That, in turn, depends (among other things) on the amount of data.  A common way to see large but insignificant effect sizes, then, is when there isn't much data.  Since such examples are numerous and easy to create, I won't dwell on this rather uninteresting point.
There are subtler things that can go on.  Even with relatively large amounts of data, a model can fail to detect an effect because that effect is masked or otherwise confused with another effect.
Here's an example involving a plain-vanilla linear regression with two explanatory variables $x_1$ and $x_2$ and a response $y$ that is conditionally independent, Normal, and of constant variance--in other words, as beautiful a situation as one could hope for when applying Least Squares methods.

This scatterplot matrix shows how the three variables are related within a sample of three hundred observations.  Perhaps, for instance, an experimenter was able to observe a system in three different conditions; measured $x_1,x_2,$ and $y$ one hundred times in each condition; and wishes to understand how $y$ might be related to the $x_i$.  That sounds like a typical (and therefore important) situation to understand.
There does seem to be a relationship: although the values of $y$ are spread over ranges of roughly $0-4$, $1-5$, and $2-6$, these ranges shift upwards as the values of the $x_i$ increase from near $-1$ to near $1$.  The regression overall is significant (the p-value is too tiny to be calculated).
Here are the coefficient estimates and their associated statistics:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)  3.06269    0.05619  54.501   <2e-16
x.1         -1.95875    1.88340  -1.040    0.299
x.2          2.96594    1.88206   1.576    0.116

Notice:

The p-values for the coefficients are 0.299 and 0.116.  Neither would be considered "significant" in most situations: they are too large.
The coefficient estimates ("effect sizes") of $-1.96$ and $2.97$ are large.  What does "large" mean here?  Simply that since each of the $x_i$ varies by more than $1 - (-1)=2$ in the dataset, a coefficient of (say) $2.97$ translates to variations of more than $2\times 2.97\approx 6$ in the prediction of $y$.  Since the total variation in $y$ is only from $0$ to $6$, this means $x_1$ alone can completely determine the value of $y$!  That's large.

This failure-to-detect the effects of the $x_i$ comes about because the $x_i$ separately give us nearly the same information: they are said to be (almost) collinear.  Collinearity can be subtle and much more difficult to detect when there are more than two explanatory variables.  Search our site for more examples.
You may modify this example to explore the effects of sample size, variability, coefficients, and so on.  Here is the R code.  Comment out the line set.seed(17) when experimenting, so that you get randomly different results each time.
library(data.table)
n <- 100    # One-third of the sample size
tau <- .02  # Conditional standard deviation of the explanatory variables
sigma <- 1  # Error standard deviation
#
# Create data.
#
set.seed(17)                            # Creates reproducible data
x <- c(rep(1,n), rep(0,n), rep(-1,n))   # Experimental "condition"
X <- data.table(x.1=rnorm(3*n, x, tau), # Regressor x.1
                x.2=rnorm(3*n, x, tau)) # Regressor x.2
invisible(X[, y := rnorm(3*n, 3+x+x.2-x.1, sigma)]) # y (including error)
#
# Plot the data.
#
pairs(X, pch=19, col="#00000010")
#
# Perform least squares regression.
#
fit <- lm(y ~ ., X)
summary(fit)


Order mySQL query by year with several year specifications

Question: I am using this query to pull out article entries from my database:
$sql = "SELECT *
        FROM articles
        WHERE author LIKE ? AND title LIKE ? AND year LIKE ?
        ORDER BY year DESC";

With single year specifications, the query orders the entries by year as intended:
1999
1998
1979
1969
...

Problematic is that this older database uses several publishing years in the same table cell, looking like this:
Example: 1970, 1974, 1983  or sometimes with semicolons 1970; 1974; 1983
This makes the script order the entries only using the very first year specification (1970 in the above example). Now I am looking for a way to order the entries by the most recent year specification (1983 in the above example).
So the random entries

1966, 1977, 1989
1925; 1956; 1977
1933, 1947, 1975, 1999

should be ordered like this:

1933, 1947, 1975, 1999
1966, 1977, 1989
1925; 1956; 1977

(only the most recent years 1999, 1989, 1977 are relevant for the order of the entries)
Comment: Is the most recent year always last in the list?
Comment: Yes, always the same pattern
Answer: Assuming the year column has at least one year, you can use
ORDER BY RIGHT(year,4) DESC


Opencv Circle Detection - RAM loading

Question: I have recently been doing some circle detection in OpenCV and I have had some great success. The code below works wonderfully in C++ on a 32-bit platform. I do however have one small problem; as the program runs my RAM loads continues to load up. For example, when I start the program I am at 250mb, 30 seconds later I am at about 800mb. This continues and eventually overflows to the hard drive. I have tried to move the cvReleaseCapture inside the while loop but I just get the old "Exception at memory location....". Any ideas how I can clean this up? Thanks a lot. Here's the code:
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>

int main( int argc, char **argv )
{
    CvCapture *capture = 0;
    IplImage  *img = 0;
    int       key = 0;
CvFont font;
cvInitFont(&font, CV_FONT_HERSHEY_PLAIN,1.0,1.0,0,1,CV_AA);

capture = cvCaptureFromCAM( 0 );

if ( !capture ) {
    fprintf( stderr, "Cannot open initialize webcam!\n" );
    return 1;
}

cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );

while( key != 'q' ) {
    img = cvQueryFrame( capture );
    IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 );
    CvMemStorage* storage = cvCreateMemStorage(0);
    cvCvtColor( img, gray, CV_BGR2GRAY );
    cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9 );
    CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, gray-    >height/4, 200, 100, 20, 100 );
    int i;
    for( i = 0; i < circles->total; i++ )
    {
         float* p = (float*)cvGetSeqElem( circles, i );
         //cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 2, CV_RGB(0,255,0), -1, 8, 0 );
         cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(0,255,0), 2, 8, 0 );
         cvLine (img, cvPoint(cvRound(p[0]+40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
         cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]+40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
         cvLine (img, cvPoint(cvRound(p[0]-40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
         cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]-40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
         cvPutText(img, "Meow",cvPoint(cvRound(p[0]+45),cvRound(p[1]+45)), &font, CV_RGB(0,0,255));

    }

    if( !img ) break;
    cvShowImage( "result", img );
    key = cvWaitKey( 1 );
    cvReleaseCapture( &capture );
}

cvDestroyWindow( "result" );
cvReleaseCapture( &capture );

return 0;

}
Answer: Get rid of the cvReleaseCapture inside the while loop. Instead, you should have
cvReleaseMemStorage(storage);
cvReleaseImage(gray);

And you should probably move the if (!img) break; line up so it reads:
img = cvQueryFrame(capture);
if (!img) break;

Edit
Actually, instead of constantly creating and then destroying gray, you should do an initial capture (img = cvQueryFrame(capture);) outsid eof the while loop. Then create gray in the normal way. Then you don't have to keep creating it in the while loop, which is why you're running out of memory (you're creating an new image every iteration without releasing it).
So
#include "stdafx.h"
#include <cv.h>
#include <highgui.h>
#include <math.h>

int main( int argc, char **argv )
{
    CvCapture *capture = 0;
    IplImage  *img = 0;
    int       key = 0;
    CvFont font;
    cvInitFont(&font, CV_FONT_HERSHEY_PLAIN,1.0,1.0,0,1,CV_AA);

    capture = cvCaptureFromCAM( 0 );

    if ( !capture ) {
        fprintf( stderr, "Cannot open initialize webcam!\n" );
        return 1;
    }

    cvNamedWindow( "result", CV_WINDOW_AUTOSIZE );

    img = cvQueryFrame( capture );
    if (!img)
        exit(1);
    IplImage* gray = cvCreateImage( cvGetSize(img), 8, 1 );
    CvMemStorage* storage = cvCreateMemStorage(0);

    while( key != 'q' ) {
        img = cvQueryFrame( capture );
        if( !img ) break;

        cvCvtColor( img, gray, CV_BGR2GRAY );
        cvSmooth( gray, gray, CV_GAUSSIAN, 9, 9 );
        CvSeq* circles = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, gray-        >height/4, 200, 100, 20, 100 );
        int i;
        for( i = 0; i < circles->total; i++ )
        {
            float* p = (float*)cvGetSeqElem( circles, i );
            //cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), 2, CV_RGB(0,255,0), -1, 8, 0 );
            cvCircle( img, cvPoint(cvRound(p[0]),cvRound(p[1])), cvRound(p[2]), CV_RGB(0,255,0), 2, 8, 0 );
            cvLine (img, cvPoint(cvRound(p[0]+40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
            cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]+40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
            cvLine (img, cvPoint(cvRound(p[0]-40),cvRound(p[1])), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
            cvLine (img, cvPoint(cvRound(p[0]),cvRound(p[1]-40)), cvPoint(cvRound(p[0]),cvRound(p[1])), CV_RGB(0,255,0), 1, CV_AA,0);
            cvPutText(img, "Meow",cvPoint(cvRound(p[0]+45),cvRound(p[1]+45)), &font, CV_RGB(0,0,255));

        }

        cvShowImage( "result", img );
        key = cvWaitKey( 1 );

    }
    cvReleaseMemStorage(storage);
    cvReleaseImage(gray);
    cvDestroyWindow( "result" );
    cvReleaseCapture( &capture );

    return 0;
}

Comment: Worked perfectly. Thanks a lot my computer doesnt overheat after a minute of this program.
Comment: Sweet. You're new to stackoverflow; the next course of action here is to upvote my answer and select it as correct ;)

Opencv Circle Detection - RAM loading


PHP's register_shutdown_function() using an anonymous function

Question: According to the manual http://php.net/manual/en/function.register-shutdown-function.php, register_shutdown_function() is implemented as:
<?php
function shutdown()
{
    // This is our shutdown function, in
    // here we can do any last operations
    // before the script is complete.

    echo 'Script executed with success', PHP_EOL;
}

register_shutdown_function('shutdown');
?>

Could it be implemented as an anonymous function?  If so, how?
Answer: Anonymous function are simply passed as an argument:
register_shutdown_function(function(){
    // Code
});

Note that this applies to every function, not only to register_shutdown_function();
The only differences between using a named function vs an anonymous one, is if you need to call this function outside the context of register_shutdown_function, at this point you need to use a named function (altho this is a rare edge case).
Comment: Thanks dynamic.  Easier than I expected!  Any reason not to do so?
Comment: can anyone elaborate on "outside the context of register_shutdown_function" with an example?


Laravel 5.4: Erro ao criar tabela - unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

Question: Ao executar o comando php artisan migrate para criar a tabela no banco, aparece o erro abaixo:
[Symfony\Component\Debug\Exception\FatalThrowableError]
  Parse error: syntax error, unexpected '(', expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

Parece ser um erro de sintaxe, porém não consigo ver onde está o erro, já criei outras tabelas, incluindo as que são chaves estrangeiras dessa sem problema nenhum.
Minha migration está assim:

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateConvServsTable extends Migration
{
    public function up()
    {
        Schema::create('conv_servs', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('id_convenio')->unsigned();
            $table->integer('id_especialidade')->unsigned();
            $table->foreign('id_convenio')->references('id')->('convenios')->onDelete('cascade');
            $table->foreign('id_especialidade')->references('id')->('especialidades')->onDelete('cascade');
        });
    }

    public function down()
    {
        Schema::dropIfExists('conv_servs');
    }
}

Answer: Isto parece errado:
$table->foreign('id_convenio')->references('id')->('convenios')->onDelete('cascade');
$table->foreign('id_especialidade')->references('id')->('especialidades')->onDelete('cascade');

Não tem muito sentido ->('convenios')-> e ->('especialidades')->, tenho certeza que deveriam ser funções.
Comment: Segundo a documentação do Laravel, aí nesse lugar é onde vai o nome da tabela que eu to referenciando. Já criei desse jeito outras tabelas com chaves estrangeiras e funcionou normalmente.
Comment: Cara, não acredito que esqueci do ON antes do nome da tabela. Meus Deus velho. Que erro estúpido.
Comment: @DiegoVieira se é programação acredite sempre cometeremos erros estupidos :) ... é como eu com portugues, é uma gafe atras da outra XD, pode marcar a resposta como aceita?
Answer: Esqueci de colocar o "ON" antes do nome da tabela. Segue o código arrumado:
Schema::create('conv_servs', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('id_convenio')->unsigned();
            $table->integer('id_especialidade')->unsigned();
            $table->foreign('id_convenio')->references('id')->on('convenios')->onDelete('cascade');
            $table->foreign('id_especialidade')->references('id')->on('especialidades')->onDelete('cascade');
        });


How can I add an object to an object in Javascript?

Question: I have the following javascript object that came back from an Entity Framework 5 get from a SQL Server database.
var a =
 {
  "questionId":14,
  "questionStatusId":1,
  "answers":null
 }

var b =
 {
  "questionId":15,
  "questionStatusId":1,
  "answers":[
   {"answerId":34,"correct":true,"response":false,"text":"5","image":null,"questionId":15},
   {"answerId":35,"correct":false,"response":false,"text":"50","image":null,"questionId":15}]
 }

I would like to add an empty answer object and then send back to the server with a PUT.
How can I add an answer object to variable a and to variable b ?
Comment: `a.answers = [{}]`, `b.answers.push({})`?
Comment: What do you mean by "an empty answer object" ?
Answer: var answer=[];
a.push( { "answer":answer } );
b.push( { "answer":answer } );

Answer: Something like
var newAnswer = {"answerId":0,"correct":false,"response":false,"text":"","image":null,"questionId":0};
b.answers.push(newAnswer);

is probably what you are looking for.
Answer: You can add properties o objects at runtime in JavaScript. For example
var a = { f : 10, g : 20 };
a.h = 30;

Similarly, just add the answers property to your a & b with blank objects.
a.answer = []; // Empty non null array
b.answer = []; // "


Retornar o dia da semana em Javascript

Question: Tenho dois códigos para retornar o dia da semana, porém no primeiro retorna indefinido, e no segundo retorna o dia errado, por exemplo no dia 22/05/2016 retorna quarta, e o correto seria domingo.
Código 1:
$(document).ready(function(){
    $("input#dataR").blur(function(){
        var data = $("#dataR").val();
        var teste = new Date(data);
        var dia = teste.getDay();
        var semana = new Array(6);
        semana[0]='Domingo';
        semana[1]='Segunda-Feira';
        semana[2]='Terça-Feira';
        semana[3]='Quarta-Feira';
        semana[4]='Quinta-Feira';
        semana[5]='Sexta-Feira';
        semana[6]='Sábado';
        alert(semana[dia]);
    });
});

Código 2:
$(document).ready(function(){
    $("input#dataR").blur(function(){
        var data = $("#dataR").val();
        var arr = data.split("/");
        var teste = new Date(arr[0],arr[1],arr[2]);
        var dia = teste.getDay();
        var semana = new Array(6);
        semana[0]='Domingo';
        semana[1]='Segunda-Feira';
        semana[2]='Terça-Feira';
        semana[3]='Quarta-Feira';
        semana[4]='Quinta-Feira';
        semana[5]='Sexta-Feira';
        semana[6]='Sábado';
        alert(semana[dia]);
    });
});

Comment: No seu segundo caso, você está passando como parâmetros para o construtor do `Date` os valores de dia, mês, ano, mas a ordem é o contrário (ano, mês, dia). E note que em JS os meses começam a partir de 0 (0 = janeiro, 1 = fevereiro, ...)
Comment: E só pra constar, não precisa desse array com os dias da semana, daria para fazer `data.toLocaleString('pt-BR', {weekday: 'long'})`
Comment: @carlosfigueira vi agora o teu comentário depois de colocar a resposta. Basicamente a dizer o mesmo que tu. Na próxima podes colocar resposta logo :)
Answer: Criar objetos Date com strings como '22/05/2016' não é boa ideia. O melhor é como no teu outro exemplo com .split('/').
O problema que te está a escapar aqui é que os meses em JavaScript começam em 0. Ou seja janeiro é o mês 0.
Repara ainda que o construtor Date recebe argumentos por esta ordem:

Ano, Mês, Dia, Hora, Minuto, Segundo

Dito isso podes fazer o teu código assim:
$(document).ready(function(){
    var semana = ["Domingo", "Segunda-Feira", "Terça-Feira", "Quarta-Feira", "Quinta-Feira", "Sexta-Feira", "Sábado"];
    $("input#dataR").blur(function(){
        var data = this.value;
        var arr = data.split("/").reverse();
        var teste = new Date(arr[0], arr[1] - 1, arr[2]);
        var dia = teste.getDay();
        alert(semana[dia]);
    });
});

Exemplo: https://jsfiddle.net/nzcoxtar/
Comment: Isso mesmo cara, obrigado pela ajuda!
Answer: No meu caso, eu consegui resolver assim:
const diaSemanaAtual = new Date().getDay();

Answer: Pode fazer assim:
var diaSemana = ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]

function obterDiaSemana(value){
    let sp = value.split("-")
    let result = new Date(sp[0], sp[1] - 1, sp[2])
    let day = result.getDay()
    return diaSemana[day]
}

console.log(obterDiaSemana("2023-10-31"))

Comment: Para que fazer isso? Sabia que pode fazer assim `console.log((new Date()).toLocaleDateString("pt-BR", {weekday: "long"}));`
Answer: com essa função aqui tu pega os dias da semana
export function getDaysOfWeek() {
  const daysOfWeek = Array.from({ length: 7 }, (_, i) => {
    const date = new Date()
    date.setDate(date.getDate() - date.getDay() + i)
    return date.toLocaleDateString('pt-BR', { weekday: 'long' })
  })

  return daysOfWeek
}

Retornar o dia da semana em Javascript


Find regular representation of $(\mathbb{Z}_3,+_3)$ in given base and reduce it

Question: So, first of all we have $\mathbb{Z}_3=\{0,1,2\}$ and base vectors $\{e_0,e_1,e_2\}=\{[1,0,0],[0,1,0],[0,0,1]\}$ numerated by elements of group, which means we are looking for representation $\phi:\mathbb{Z}_3\rightarrow GL(3,\mathbb{C})$. Regular representation is given by linear transformation $\phi_s$ (for element $s\in\mathbb{Z}_3$) such that for given vector from base $e_r$ it returns $\phi_s(e_r)=e_{rs}$, so for element $0$, it does nothing (doesn't change base vectors) so it's given by matrix
$0\mapsto \begin{bmatrix}1,0,0\\0,1,0\\0,0,1 \end{bmatrix}$, $1$ shifts everything by one so first vector in base is now second etc. so
$1\mapsto \begin{bmatrix}0,1,0\\0,0,1\\1,0,0 \end{bmatrix}$, and $2$ shifts everything by two, so
$2\mapsto \begin{bmatrix}0,0,1\\1,0,0\\0,1,0 \end{bmatrix}$.
Is my reasoning with regular representation for given base correct?
I suspect that it will reduce into three $\mathbb{C}$ representations, because i know that if group is abelian, then its irreducible representations are of dimension 1, but i don't know how to get them.
Answer: You always have the trivial subrepresentation, given by the span of $e_1 + e_2 + e_3$.
Furthermore, to find them all, if an element is fixed by the generator of $\mathbb{Z}_3$, then it is fixed by $\mathbb{Z}_3$, so to find one dimensional $\mathbb{Z}_3$-invariant subspaces, this is equivalent to finding eigenvectors of the matrix of (what you have called) 1.
From this perspective, the trivial subrepresentation given above, corresponds to the eigenvector [1,1,1] with eigenvalue 1.
I hope this points you in the right direction!
Comment: @rubiccube713 I will write $\mathbb{Z}_3 = \{1 , x , x^2\}$ for clarity.
An element of $\mathbb{C}^3$ is fixed by $x$ if $xv = \lambda v$ for some $\lambda \in \mathbb{C}$. If this is true, then for any element $x^k \in \mathbb{Z}_3$, $x^k v = \lambda^k v$, so $v$ is fixed by the group (by all elements).
Comment: Notice that this condition is the same as $v$ being an eigenvalue of $x$. The thing to notice for cyclic groups is that an eigenvector $v$ of a group generator is an eigenvector for the whole group, and so the (1-dimensional) subspace spanned by $v$ is a $\mathbb{Z}_3$-subrepresentation.
Comment: @rubiccube713 does this clear things up?
Comment: could you tell me what do you mean with element being fixed by generator/group? I have found all three vectors (two are complex), why are subrepresentations related to eigenvectors? I guess by finding these vectors i can show that $\mathbb{C}^3$ is direct sum of span of them but how can i get subrepresentations from them? Is it even possible?
Comment: Is it because eigenvectors of such matrix are invariant for changing of base? And because 1 is generator of $\mathbb{Z}_3$ they are invariant for any of changes of bases given by regular representation?
Comment: Yes! Thank you very much :)


Markov Chain question?

Question: Let $M=(S,A,\{A(s)\}_{s\in S},P)$ be a Markov chain, where $S$ is the set os states, $S \subset \mathbb{N}$ and $A$ is a finite set of actions. For each $s \in S$, $A(s) \subset A$ is the non-empty set of admisible actions at state $s \in S$.
Ok, this is a construction that my teacher told us, but I don't understand the idea of the set $A(s)$, what is the function of this set? I don't understand why called it admissible actions? what is the difference with the set of actions?
And with this there is an observation that said:
Without loss of generality we may take $A =  \cup_{s \ n S} A(s)$. Whereas, $\mathbb{K}=\{(s,a)| s \in S, a \in A(s)\}$ is the set of admissible state-action pairs. And the variable $p_{j|ik}$ is a stationary controlled transition matrix (why is controlled? what does that mean?), which defines a stochastic kernel on $S$ given $\mathbb{K}$ (I don't understand this implication), where
$$p_{j|ik}:= P(X_{t+1}=s_j|X_t=s_i,A_t=a_k), \ \ \forall t \in \mathbb{N}  $$
So Is this the representation of the probability associated with the transition from the state $s_i$ to $s_j$, $i,j=1,...,n$ under an action $a_k \in A(s_i)$ ?
Could someone explain this construction or definition of Markov chain pls.
Thanks for your help and time everyone.
Comment: This sounds like a Markov Decision Process, which is a bit more involved than a regular Markov chain. The general idea is that at each time $n$, some action $a\in A$ may be taken, and if so, then the distribution of $X_{n+1}$ is given by the transition matrix corresponding to $a$.
Comment: This seems equivalent to a [hidden Markov chain](https://en.wikipedia.org/wiki/Hidden_Markov_model).
Answer: Perhaps I can explain this concept more clearly with some example. As a brief note, what you are describing is not a Markov Chain, but rather a Markovian Decision Process. Consider the following MDP:
A robot is allowed to move on a grid of dimension $(n,n)$. He starts on the grid at $(0,0)$ and at each timestemp may choose to move to a square that is either one unit away vertically or one unit away horizontally so long as he stays on the grid. After some time, me might look like this:
|------------|------------|------------|-----------|
|            |            |            |           |
|      (0,0) |      (0,1) |        ... |           |
|------------|------------|------------|-----------|
|            |            |            |           |
|      (1,0) |            |            |           |
|------------|------------|------------|-----------|
|            |            |            |           |
|        ... |            |            |           |
|------------|------------|------------|-----------|
|            |            |            |   O_O     |
|            |            |            |   \||     |
|------------|------------|------------|-----------|
|            |            |            |           |
|            |            |            |           |
|------------|------------|------------|-----------|

What are all the states? We can denote them by their coordinates: $(a,b) \forall a \in [0,1]$. What is the set of all actions? Well that is simply (up,left,right,down). However, the robot can not perform all of those actions from every state. For example, in his starting state, he may only move down or right as he is restricted to staying on the grid. Thus we can say, $A((0,0)) = \{up, right\}$ as those are the only admissible or "allowed" actions in state $(0,0)$ which is clearly different than the set of all actions. Furthermore, one could say that $\cup_{s \in S} A(s) = \mathbb{A}$ for all MDP.
As for the probabilities, it may be the case that in certain states, the robot likes to do certain actions more than others (or perhaps completely uniformly). Suppose we observed the robot for a very, very long time and came up with the percentages of the time he transitioned from state $s$ to state $s'$. We could write out a matrix representing such transition probabilities. This is the stochastic kernel.
Comment: For example, I was reading what is a MDP and talked about histories and policies, i.e, The space $\mathbb{H}_t$ of possible histories up to time $t \in \mathbb{N}$ is defined by $\mathbb{H}_0:=S$ and $\mathbb{H}_t:=\{ \mathbb{K}_t \times S\}$, $t \geq 1$, $h_t= (s_0,a_0,...,s_i,a_i,...,s_t)$ , and a control policy $\pi=\{\pi(t)\}$ is a special sequence of stochastic kerneles, what does that mean here? And what is this set of histories?
Comment: @Knight this is in reference to the ability for agents to change their environments and thus their policy on taking actions in space along time.
Comment: I don't know, It is complicated to understand these concepts.

Markov Chain question?


Segmetation fault error - Problema no código main para inserção de nodos em árvore binária

Question: Estou fazendo um programa que lê registros e salva estes registros em uma lista encadeada e em uma árvore binária.
Entretanto, eu não estou conseguindo salvar os nodos na árvore binária, aparecendo um erro de segment fault error.
Eu gostaria de saber por que aparece este erro e como concerta-lo.
Aqui está meu arquivo main.c:
int main(){

registro p1_main;
lista   p2_main;
nodo p3_main;
int escolha1 = 99, escolha2;

criarLista(&p2_main);
cria_arvore(&p3_main);
do {
    printf("Qual opção a seguir você deseja realizar?\n\n1-Adicionar Contato\n2-Apresentar nomes registrados\n\n");
    scanf("%d", &escolha1);

switch(escolha1){
    case 1:
        criar_registro(&p1_main);
        insere_ini(&p2_main, &p1_main);
        CriarNodo(&p1_main);
        insere_Arvore(&p3_main, &p1_main);
    case 2:
        imprime_nomes(&p2_main);
    }
}
while ( escolha1 != 0);

return 0;

}

Aqui está a estrutura.h dos códigos:
#include <stdio.h>
#include <stdlib.h>

typedef struct registro_st{         // sequência de objetos do mesmo tipo
    char login[50];
    char nome[50];
    float valor;
} registro;

typedef struct nodo_st{
    registro *dado;
    struct nodo_st *dir;
    struct nodo_st *esq;
} nodo;

typedef struct Lista_st{
    nodo *cabeca;
    nodo *cauda;
    int tamanho;
} lista;

nodo* CriarNodo(registro * p){
        nodo* n;
        n = (nodo*)malloc(sizeof(nodo));
        n->dado = p;
        n->dir = NULL;
        n->esq = NULL;
        return n;
}

void criarLista(lista *l){
    l->cauda = NULL;
    l->cabeca = NULL;
    l->tamanho = 0;
}

void insere_ini(lista *l, registro* dado){
    nodo* novo = (nodo*)malloc(sizeof(nodo));
        if(novo == NULL){
            return 0; //falta de espaço
        };

        novo->dado = dado;
        novo->dir = l->cauda; //antigo primeiro aponta para o próximo
        l->cauda = novo;        // novo nodo recebe ponteiro para começo
        l->tamanho = l->tamanho + 1;
        printf("\n\nEsse foi o registro de num: %d.\n", l->tamanho);
        printf("\nnodo implementado!!\n");
        return novo;
}

nodo* raiz;

//FUNÇÕES PARA UTILIZAR NO MAIN

void imprime_nomes(lista *l){            // função que imprime os valores
        nodo* p = l->cauda;
            while(p)
            {                                           // Usando while, não é necessário estabelecer um loop para percorrer toda lista.
            printf("Login eh: %s\n", p->dado->login);
            printf("Nome eh: %s\n", p->dado->nome);
            p = p->dir;
            }
}

void criar_registro(registro *p){                   //função para adicionar os contatos
    printf("Qual login para registro:\n");
    scanf("%s", &p->login);
    printf("Qual o nome do contato:\n");
    scanf("%s", &p->nome);
    printf("Qual valor para registrar:\n");
    scanf("%f", &p->valor);
}

nodo* raiz; //porque um ponteiro para um ponteiro?

nodo* cria_arvore(){                            //função para criar árvore
    nodo* raiz = (nodo*)malloc(sizeof(nodo));
    if(raiz != NULL)
        {
        return raiz;
        }
    }

void insere_Arvore(nodo **raiz, struct registro_st *registro)
{
    //o compilador faz sempre cast de void* para o tipo indicado, não sendo assim necessário
    nodo* novo = malloc(sizeof(nodo)); /*agora sem cast pois é desnecessário*/
    if(novo == NULL)
    {
        return; /* é void logo não pode ter tipo de retorno*/
    }

    novo->dado = registro; //o dado é o registro todo em si
    novo->dir = NULL;
    novo->esq= NULL;

    if(*raiz == NULL) //ver se o valor do ponteiro é null, logo arvore vazia
    {
        *raiz = novo;
        return;
    }

    nodo* atual = *raiz;
    nodo* ant = NULL;

    while(atual != NULL) //ciclo agora só para navegar até ao sitio correto
    {
        ant = atual;

        //o valor a ser inserido vem no próprio registro, com registro->valor
        if (registro->valor == atual->dado->valor)
        {
            free(novo);
            return; /* é void logo não pode ter tipo de retorno*/
        }

        if(registro->valor > atual->dado->valor)
        {
            atual = atual->dir;
        }
        else
        {
            atual = atual->esq;
        }
    }

    //após navegar é feita a inserção pelo no anterior.
    if (registro->valor > ant->dado->valor){ //se maior que o anterior fica a direita
        ant->dir = novo;
    }
    else { //senão fica a esquerda
        ant->esq = novo;
    }
}

Answer: A tua utilização da arvore não está correta de acordo com a tua ultima pergunta que eu respondi. No teu main tens:
int main(){
   ...
   nodo p3_main;

Quando a arvore deve de ser um ponteiro, para funcionar com as funções criadas, assim como ter o valor de inicio de NULL como eu tinha exemplificado. Dessa forma deveria então ser:
int main(){
   ...
   nodo *p3_main = NULL; //agora com valor inicial de NULL

Repara que é bem importante que tenha este valor de inicio caso contrario quando for feita a navegação no ciclo ele nunca irá parar:
...
while(atual != NULL)
...

Assim como nunca saberá se a lista está vazia:
...
if(*raiz == NULL) //ver se o valor do ponteiro é null, logo arvore vazia
{
   ...

Também não é necessária a função cria_arvore, porque a função de inserção na arvore chamada insere_Arvore já contempla o facto de a arvore estar vazia e então cria o primeiro nó individualmente, aqui:
if(*raiz == NULL) //ver se o valor do ponteiro é null, logo arvore vazia
{
   *raiz = novo;
   return;
}

E a chamada ao cria_arvore deve ser retirada:
int main(){
   ...
   nodo *p3_main = NULL; //agora com valor inicial de NULL
   ...
   /*cria_arvore(&p3_main); //agora sem o cria_arvore pois não é necessário*/

E estas pequenas alterações já irão fazer o programa funcionar
Comment: @Arduin O que não estas a visualizar é que a arvore é basicamente um conjunto de nós. Logo criar a arvore representa apenas criar o primeiro nó, que é algo que a função `insere_Arvore` já faz. É no entanto importante de mencionar que podia ser como tinhas feito, com uma função de criação do primeiro nó da arvore, mas para isso não era necessário o teste dentro da função `insere_Arvore`. Assim de cabeça não me vem à cabeça bom material de estudo, mas vou ver se vejo algum e logo indico.
Comment: Isac, eu pensava que eu precisava criar a árvore, igual como eu fiz com a lista encadeada, A função, realmente, já contempla este fato. Eu estou tendo bastante dificuldade na compreensão de ponteiros e estruturas, se souberes de algum material, link, pdf e etc e queiras deixar disponível aqui eu agradeço. No geral, muito obrigado pelo suporte que tens dado às minhas perguntas.


Convergence of the sequence $n ((ea)^{1/n} - a^{1/n})$ for positive $a$

Question: Suppose $a$ is positive. Consider the sequence
$$a_n=n\big((ea)^{\frac {1}{n}}- a^{\frac {1}{n}}\big) , n\geq 1$$
Then
A. $\displaystyle\lim_{n \to \infty} a_n$ does not exist
B. $\displaystyle\lim_{n \to \infty} a_n = e$
C. $\displaystyle\lim_{n \to \infty} a_n = 0$
D. None of above
On writing out few terms and taking arbitrary $a$, it seems answer is C, but I am not sure
Thanks
Answer: Consider the limit
$$\lim_{n \to \infty} n((ea)^{1 \over n} - a ^{1 \over n}) $$
$$ = \lim_{n \to \infty} n((e^{1 \over n}a^{1 \over n} - a ^{1 \over n}) $$$$ = \lim_{n \to \infty} n(a^{1 \over n}(e^{1 \over n} - 1)) $$
$$ =\lim_{n \to \infty} \frac{a^{1 \over n}(e^{1 \over n} - 1)}{1 \over n} $$
Substitute $x = {1 \over n}$
$$ =\lim_{x \to 0} \frac{a^{x}(e^{x} - 1)}{x} $$
Using L'Hospital's rule for $0 \over0 $ we get
$$ =\lim_{x \to 0} a^x(\ln(a)*(e^{x} - 1) +e^x) = 1 $$
Answer: $\begin{array}\\
a_n
&=n\big((ea)^{\frac {1}{n}}- a^{\frac {1}{n}}\big)\\
&=na^{\frac {1}{n}}\big(e^{\frac {1}{n}}- 1\big)\\
&=ne^{\frac {\ln a}{n}}\big(e^{\frac {1}{n}}- 1\big)\\
&\approx n(1+\frac {\ln a}{n}+O(1/n^2))\big(1+\frac {1}{n}+O(1/n^2)- 1\big)\\
&= n(1+\frac {\ln a}{n}+O(1/n^2))\big(\frac {1}{n}+O(1/n^2)\big)\\
&= (1+\frac {\ln a}{n}+O(1/n^2))\big(1+O(1/n)\big)\\
&=1+O(1/n)\\
&\to 1\\
\end{array}
$
Comment: So answer is None of the above(D)
Comment: Yep. Yup. Yap. Yip.
Answer: Notice that $\displaystyle\lim_{n \to \infty}a_n$ $= \displaystyle\lim_{n \to \infty}\dfrac{(ea)^{1/n}-a^{1/n}}{\tfrac{1}{n}}$ $= \displaystyle\lim_{x \to 0}\dfrac{(ea)^{x}-a^x}{x}$
$= \displaystyle\lim_{x \to 0}\left[\dfrac{(ea)^{x}-1}{x} - \dfrac{a^{x}-1}{x}\right]$ $= \displaystyle\lim_{x \to 0}\dfrac{(ea)^{x}-1}{x} - \lim_{x \to 0}\dfrac{a^{x}-1}{x}$,
provided that both of these limits exist. Can you compute these limits?
Hint: Think about the definition of the derivative.


KAM theory and the Ergodic hypothesis

Question: I have seen several authors mentioning that KAM theory contradicts the Ergodic hypothesis. Unfortunately, the authors do not elaborate on this. I have some background in KAM theory but very little in Ergodic theory. Could somebody explain the argument?
Answer: "KAM Theory contradicting the Ergodic hypothesis" really just means that in a typical nearly integrable Hamiltonian system with finitely many degrees of freedom - one of those systems for which the KAM Theorem holds, there can be no ergodicity. So KAM doesn't hold on ergodic systems, and the systems for which we can use KAM theory are not ergodic.
This seems as if it would be devastating to basically all of thermodynamics and statistical mechanics, as a number of topics studied in these theores assume that a nearly integrable hamiltonian system satisfies ergodicity if limited to potential energy hypersurfaces. Ergodicity however seems to be a reasonable assumption for very large n, though despite there not being a possibility of "true" ergodicity.
So why are these two domains disjoint? Well, KAM states that in a hamiltonial system with n degrees of freedom, there are typically n quasiperiodic tori with positive Liouville measure in every potential energy hypersurface. Since these tori are distinct, and they have positive measure in a hypersurface, this hypersurface can be decomposed into disjoint sets that are invariant and positively measured, so while the ergodic hypothesis would claim that a path spends time in this torus proportional to it's measure, it is quasiperiodic in some torus and therefore the time it spends in that torus is not proportional to the torus's measure.
Answer: Given an open subset $B$ of $\mathbb R^n$, let us consider on $B^n\times\mathbb T^n$ the symplectic form $$\Omega=\sum_{i=1}^ndq_i\wedge dp_i,$$ where $p=(p_1,\ldots,p_n)$ are coordinates on $B$, and $q=(q_1,\ldots,q_n)$ are the angular coordinates on $\mathbb T^n$.
Let us assign an Hamiltonian function $H(q,p)=H_0(p)+\varepsilon H_1(q,p)$, satisfying the non-degeneration condition
$$\det\left(\frac{\partial^2 H_0}{\partial q\partial q}\right)\neq 0$$
The associated Hamilton equations are $$\dot p=-\varepsilon\frac{\partial H_1}{\partial q},\quad \dot q=\omega_0(p)+\varepsilon\frac{\partial H_1}{\partial p}$$
where $\omega_0(p):=\dfrac{\partial H_0}{\partial p}.$

The un-perturbated case ($\varepsilon=0$) the Hamiltonian flow, on the invariant $n$-toruses $p=\mathrm{constant}$, is quasi-periodic with quasi-frequencies $\omega_0(p)$.
$$(t,(q,p))\mapsto(q+t\omega_0(q),p)\tag{*}$$
For any $p_0$ in a certain open everywhere dense subset $B_0$ of $B$, the components of $\omega(p_0)$ are $\mathbb Q$-linear indipendent, so each integral curve is dense on the invariant $n$-torus $p=p_0$, which is called non-resonant.
The pertubated case ($\varepsilon<<1$) Kolmogorov showed that, in the Lebesgue-measure theoretic sense, almost all the non-resonant $n$-toruses with the flow(*) are only slightly deformed.

Therefore the Hamiltonian flow on the energy hyperurface $H=\mathrm{constant}$ is not ergodic, while, between its ergodic components, there are almost all the invariant $n$-toruses.
All this is just a rewording of section 21 in Arnold, Avez, "Problemes Ergodiques De La Mecanique Classique".
Answer: Ergodic hypothesis more or less states the the Hamiltonian flow restricted to each energy surface is ergodic for the Liouville measure.
Now if you take an integrable Hamiltonian system with a 2n dimensional phase space, action angle coordinates theorem tells you that there exists n first integral of motions $I_i$ (such that dI_i are independent) and some angle coordintes $\theta_i$ defined on $S^1$ for i=1,...,n such that under the coordinate change $(x,p) \rightarrow (\theta(x,p),I(x,p))$ the Hamiltonian flow still satisfies the Hamilton-Jacobi equations for the new Hamiltonian function in these coordinates. But since $I_i$ are first integrals it means that $\frac{dI_i}{dt}=0$ (I will drop subscript i from now on) and if you look at the form of Hamiltonian equations than you get that the new Hamiltonian does not depend on $\theta$ but it depends on $I$. And so $I(t) = cnst$ and $\theta(t)= \theta(0) + I(0)t$.
Now note that one of the first integrals will be the energy say $I_1$. It is obvious that an integrable system does not satisfy the ergodic hyphothesis. This is because there is a subset of union of torii of positive measure inside $I_1 =cnst$ such that the union is invariant but has positive measure (not 1). But this is in itself not enough to say that ergodic hyphothesis will not hold for "all most all" systems since integrable systems can in theory be destroyed by small perturbations (and people in dynamical systems are interested in statements that hold generically but not for all examples). But the KAM theorem says that even if you do this perturbation, there will remain a positive measure set of invariant torii such that restricted to each Torus the hamiltonian flow is conjugate to an rationally independent translation. So you have an open set of Hamiltonian flows (dont remember what is the smoothness degree of the perturbation but lets say for simplicity in $C^{\infty}$ topology) where the ergodic hyp. fails.
In this case each torus represents a level set of the form $I=cnst$ and in particular is a subset of $I_1=cnst$. Therefore restricted to each energy surface the Hamiltonian flow is non-ergodic. Yet restricted to each $I=cnst$ the Hamiltonian flow is still ergodic since it is conjugate to rationally independent translation on the torus. Whether if this has any physical significance or not I have not understood yet. Also it is provocative to think that in action angle coordinates, constants of motion represent the momentum. Now since the new Hamiltonian $H$ only depends on $I$, then the level sets $I =cnst$ somehow represent energy surfaces in this new coordinates and somehow this seems to what Ergodic hyp. claims.
p.s: I must note that there is some finiteness problem of using Liouville measure directly. I think this makes more sense when there is a compact energy surface which you restrict to your self and then on this surface, using the Liouville measure, you can construct another invariant and finite measure that gives full measure to this energy surface (which is to no suprise called a microcanonical distribution).

KAM theory and the Ergodic hypothesis


UITableView is revealed only after it is scrolled upwards

Question: I have a storyboard with a UIView and a UITableView in it. The UITableView has custom cells (UITableViewCell with xib).
When I run the app, only the first row of the table is shown, the rest of the table is hidden.
The rows are not seen on the screen, but they respond to user interaction as expected.
The rest of the cells are revealed only after the table is scrolled upwards.
What could be the problem?
Here is the code for UIView with the table:
<code>@implementation EldersTableViewController
@synthesize items;
@synthesize tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    EldersDataHendler *edh = [[EldersDataHendler alloc]init];
    NSMutableArray *itemsFromPList = [edh dataForTableFrom:[NSDictionary         dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"eldersData"     ofType:@"plist"]]];
    self.items = itemsFromPList;
    [edh release];
    edh=nil;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||
            interfaceOrientation == UIInterfaceOrientationLandscapeRight);
}

- (IBAction)didPressBackButton:(UIButton *)sender {
    [self.view removeFromSuperview];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.items  count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath     *)indexPath
{

    SEObject *cellInfo = [self.items objectAtIndex:indexPath.row];
    EldersItemCell* cell = (EldersItemCell*)[tableView     dequeueReusableCellWithIdentifier:@"EldersItemCell"];
    if (cell == nil) {

        NSArray* topObjects = [[NSBundle mainBundle] loadNibNamed:@"EldersItemCell" owner:self options:nil];

        for (id obj in topObjects){
            if ([obj isKindOfClass:[EldersItemCell class]]){
                cell = (EldersItemCell*)obj;
                break;
            }
        }

    }
    [cell setObject:cellInfo];
    return cell;
}
#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    SEObject *cellInfo = [self.items objectAtIndex:indexPath.row];
    if (!eldersDetailsViewController){
        eldersDetailsViewController = [[self.storyboard     instantiateViewControllerWithIdentifier:@"elderDetailsVC"] retain];
    }
    eldersDetailsViewController.seObject = cellInfo;
    [self.view addSubview:eldersDetailsViewController.view];
}

- (void)dealloc {
    [eldersDetailsViewController release];
    [tableView release];

    [super dealloc];
}
@end
</code>
Thanks in advance,
Luda
Comment: What happens when you use the standard canonical code for cellForRowAtIndexPath using standard UITableCells rather that your custom views? It's just a way of eliminating whether the issue is with EldersItemCell or with your Storyboard.
Comment: UITableView may not be everyone's cup of tea, but surely not reviled?! ;) I suspect your cells are not "revealed".
Comment: No not reviled :), just not revealed :)
You are right! The problem must be with the custom cell, because the standard UITableCells shows fine.
Comment: Problem solved!
Thanks a lot dear arooaroo. There was something with the custom cell with the xib. So I've created a custom Table View Cell programmatically. Here is a nice tutorial:
http://jainmarket.blogspot.com/2009/05/creating-custom-table-view-cell.html
Comment: @Luda, just in case you're interested (since there are no direct messages here that I know of): the LinkedIn link in your profile is broken.
Comment: @FreeNickname, Thanks :) I'll fix it
Comment: @Luda, you're welcome :) I'm not a recruiter or anything, I was just curious :)
Comment: @FreeNickname, you are welcome to connect :)
Comment: @Luda, thanks) I don't have a real account there at the moment though, so it will have to wait)
Comment: @FreeNickname no prob :)
Answer: 1st just create an object class for your cell design,then import it in your .m file.then try like this and connect the table view delegate and data source properly
<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Displayfriendscell";
Displayfriendscell *cell = (Displayfriendscell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[Displayfriendscell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                  }
// Configure the cell...
[[cell viewWithTag:121] removeFromSuperview];
[[cell viewWithTag:151] removeFromSuperview];
friend *user = [sortedFriendsArray objectAtIndex:indexPath.row];
cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
//cell.nameLabel.text = user.contactNAame;
cell.nameLabel.text = user.friendName;
//cell.nameLabel.text =[[sortedFriendsArray objectAtIndex:indexPath.row] objectForKey:@"name"];
//user.friendName=[[sortedFriendsArray objectAtIndex:indexPath.row] objectForKey:@"name"];
NSLog(@"name is%@",cell.nameLabel.text);

return cell;

}
</code>
Answer: Problem solved! Thanks a lot dear arooaroo. There was something with the custom cell with the xib. So I've created a custom Table View Cell programmatically. Here is a nice tutorial


How to interpret this regression outcome

Question: Hello I hope someone can give me some valuable insight.
Prior to my analysis/regression, I checked the average market shares over a six year time period over different (countries) regions.
Region A: highest share
Region B: 2nd highest share
Region C: 3rd highest share
Region D: 4th highest share
Region E: 5th highest share
Region F: 6th highest share
In my regression I use the regions as dummies, and take Region A with the highest share as base and the shares (dependent variable) are transformed (log).
Now to my understanding I thought that Region B, which is the closest to Region A in terms of shares, would have the smallest negative coefficient and then followed by C, D, E, F. But this is not the case it goes from: B, E, C, F and D. Is my understanding wrong?
*btw: the number of countries in the regions are not equal, example Region D has 4 countries in my analysis and Region F has 11 countries for example.
Comment: I do not get this analysis, or I am missing something. If the six tiers of shares are just a binned (aggregated) version of the continuous share variable, what is the point? You already know the categorization scheme, why bother to test an apparent association? Also, the time variable is not considered in the analysis. Some countries could have existe in the analysis 6 times... That woul not be proper for regression.
Comment: Well I had to put the regions in my regression as control variables and after I got the output, my teacher looked at it and said: and are these results the same as in your figure with the average shares per region over that time period? So I made the assumptions that the results of my regression had to be somewhat similar (or logical) as in the figure.
Comment: So, if other variables are in the regression as well the two-variable association between share and region does not need to hold, because other variables in the model could have confounded the said association, which is to say your situation is not necessarily an anomaly.
Comment: So let $Y_i$ be the "market share" for region $i$. Let $y_i = \log Y_i$. Let $I_{B,i}, I_{C,i}, \ldots,  I_{F,i}$ be dummy variables for regions B through F respectively. You ran the regression $y_i = b_0 + b_B I_{B,i} + b_C I_{C,i}+ b_D I_{D,i}+ b_E I_{E,i}+ b_F I_{F,i}+ \epsilon_i$. Do I understand properly?
Comment: When you say region A has the highest average share, is this based upon an average of market share $\frac{1}{n_A} \sum_{i \in A} Y_i$ or the average of log market share $ \frac{1}{n_A} \sum_{i \in A}  y_i$?
Comment: @Penguin_Knight (love your name btw), yes in total I have six main drivers and 8 (including the regions) control variables. When I run the regression with only the regions I get the same results.
Comment: @MatthewGunn, hi thanks for your reply. Yes thats how I run the regression (but my regression has more variables than just the regions).
and yes with highest average share I mean the average of market share and not the average of log market share.
Comment: So your regression differs from taking the simple, arithmetic average of market share by region in two ways: (1) you're running the regression on the *logarithm* of market share and (2) you're adding some additional control $X$. Either of those two could explain why the ordering changes? If you regress market share $Y_i$ only on your dummies $I_B, \ldots, I_F$ your coefficients should be exactly as you say they are because that regression is estimating the mean market share conditional on region.
Comment: @MatthewGunn you're RIGHT! I regressed market share Y (not the log) only on the region dummies and it makes sense now!
Answer: Let $Y_i$ be the "market share" of country $i$. You're saying that region A has a higher market share than region B etc..., that is: $$ \bar{Y}_A < \bar{Y}_B < \ldots < \bar{Y}_F$$
where $\bar{Y}_R = \frac{1}{n_R} \sum_{i \in R} Y_i$ denotes the mean market share for region $R$.
What should follow your logic/intuition:
Let $I_{R,i}$ be a dummy variable for country $i$ being in region $R$.
If you ran the regression:
$$Y_i = b_0 + b_B I_{B, i} + b_C I_{C, i} + b_D I_{D, i} + b_E I_{E, i} + b_F I_{F, i} + \epsilon_i$$
the estimated coefficients would be exactly as you expect. $\hat{b}_0 = \bar{Y}_A$ and $\hat{b}_B = \bar{Y}_B - \bar{Y}_A$.
But this is the regression you're running:
$$\log Y_i = b_0 + b_B I_{B, i} + b_C I_{C, i} + b_D I_{D, i} + b_E I_{E, i} + b_F I_{F, i} + \mathbf{x}_i \cdot \mathbf{b} + \epsilon_i$$
So it's no longer the case that estimate $\hat{b}_B$ need be negative etc... for two reasons:

The logarithm is not a linear function.
You've added the control variable (or vector) $\mathbf{x}$.


Staging Server VM Setup out of existing Production Server

Question: We are rolling out a big change that affects many of our apps. We see that everything works perfectly in DEV.
In order to minimize downtime, we want to stage a go-live. For that, we will setup a Staging server where we will run scripts and copy the latest code.
In order to minimize setup, we want to Virtualize our Prod server into a Staging Server.
For that we have Virtualized a copy of the Prod Server.
I seek advice on best approach to turn this VM ON without causing issues such as server name and IP conflicts.
Should we run Sysprep on the VM before starting it up? If so, how does one boot a VM with Sysprep bootstrapped to it?
Comment: AFAIK, you can't Sysprep a machine pre-boot. You can disconnect the vNIC of this machine, boot it up and then run Sysprep.
Answer: I would suggest running it with the vNIC disconnected when you boot it. This would work if your app can run completely inside the VM.
If you need access to some external network resources, then configure the firewall at the hypervisor to only allow traffic to/from those specific hosts.  The more open the firewall, the greater chance there is for conflicts with your current prod system.  You should plan this very carefully using documentation of the app and its network dependencies.


Conectar banco de dados Sql Server ao Programa ios Swfit

Question: Existe alguma forma de usar o banco de dados sql server no ios ? eu uso a lib jtds no android e consigo fazer a conexão mas no ios?
Answer: Se você quer acessar um banco de dados externo diretamente do iOS, não será possível. Você precisa se comunicar com um web service, e este web service sim se conecta com o banco de dados para fazer as consultas/atualizações.
Já se você quer persistir dados localmente no device, você pode usar umas das soluções específicas, como Core Data ou SQLite.