Changing the suffix of .pdf causes it not to be opened correctly in windows

Question: My dilemma is that there is pdf file named 'P01111-AMFLIBL.pdf' , I want to append '.NOSUFFIX' after .pdf so the result will be like 'P01111-AMFLIBL.pdf.NOSUFFIX'.
I am trying to add by this line of code :
fileName = fileName + ".pdf" + ".NOSUFFIX";

It's working, but the problem is that pdf file is not directly getting opened into my system
Comment: If your system is Windows, it decides how to open the file by its extension. If you add the suffix, you're effectively changing the extension and the system won't know how to open it.
Comment: Is there anyway i can keep the file as pdf and still append the.NOSUFFIX at the end after .pdf extension in java ?
Comment: No. On Windows, the suffix determines the file type. You can do `file.NOSUFFIX.pdf`, but that's about it.
Comment: Why are  you doing this? What are you actually trying to accomplish?
Answer: On Windows, the extension (i.e. suffix starting at last .) determines the file type (and associated program). If you append another suffix, this appended .NOSUFFIX will become the file extension, and the original .pdf will become just a part of the file name.
Comment: If the file ''file.pdf.NOSUFFIX" is sent via sftp drop to linux then ?
Comment: Linux uses different method to determine the content type (based on content of the file), so it should treat it as PDF.
Comment: i have sent the file to Linux via sftp drop, file reach there in correct format , Thanks


How to store a List of classes in C#?

Question: In Java I am able to have a list of classes like:
List<Class>

But how do I do this in C#?
Comment: Do you actually mean a list of types, or a generic list?
Comment: `var list = new List();` ??
Comment: A list of Objects of calss `Class` or a list of actual Classes?
Comment: I'm pretty sure this question is asking for a .Net equivalent of `java.lang.Class`
Comment: yes that right so I can store a variety of classes
Answer: Storing the class types
If you mean a list of actual classes, not instances of a class, then you can use Type instead of Class. Something like this if you have instances of each class:
List<Type> types = new List<Type>();
types.Add(someClassInstance.GetType());
types.Add(someOtherClassInstance.GetType());

Or this if you know the actual classes:
List<Type> types = new List<Type>();
types.Add(typeof(SomeClass));
types.Add(typeof(SomeOtherClass));

More on typeof(...) vs ...GetType() here
Instantiating the types
To actually instantiate a class given a classes Type you can use Activator or reflection. See this post for information on that. It can get a little complicated however when the compiler doesn't know about the constructors/parameters and such.
// Create an instance of types[0] using the default constructor
object newObject = Activator.CreateInstance(types[0]);

Or alternatively
// Get all public constructors for types[0]
var ctors = types[0].GetConstructors(BindingFlags.Public);

// Create a class of types[0] using the first constructor
var object = ctors[0].Invoke(new object[] { });

Comment: @user1592512 That's not the question you asked.
Comment: I don't see that you can use GetType() on a non-instantiated class
Comment: @user1592512 updated with some info on instantiation.
Comment: @Allstar It looks like typeof(ClassName) will work.
Comment: Hi thanks for that, but how would I then instantiate an instance of one of the types added to the list?
Answer: The same basic syntax works in C#:
List<YourClass> list = new List<YourClass>();

This requires you to have using System.Collections.Generic; at the top of your file, which is the namespace which provides most of the generic collections.
If you are attempting to store a list of types, you can use List<System.Type>.  Instances of those types could then be constructed via Activator.CreateInstance (which accepts the type) as needed.
Comment: Java 5 was released in September 2004. .NET 2.0 was released in November 2005.
Comment: @JonSkeet Fixed - was being dumb ;)
Answer:     // Create the list
    List<ClassName> classList = new List<ClassName>();

    // Create instance of your object
    ClassName cn = new ClassName();

    // Add the object to the list
    classList.Add(cn);

How to store a List of classes in C#?


Auto Complete displaying wrong for non-admin users

Question: I've recently started a module that runs an autocomplete via the taxonomy. It's attached to a form textarea element:
$form['bb_occupation'] = array(
    ...
    '#autocomplete_path' => 'taxonomy/autocomplete/field_occupations_list',
);

My issue is as follows, The options returned from the auto complete display correctly for admin/logged in users:

Full size image
While, if a non-admin/non logged in user visits said site, they're greeted with this:

Full size image
Where the options appear well off screen. I did a little research on Drupal & Google and came up with these:
Autocomplete fields appear in wrong place for non-admins in...
Which lead to an answer that did the following sort of deal (taken from here):
$($input).parent().addClass('autocomplete-wrapper');

in the autocomplete.js and this:
.autocomplete-wrapper {
  position: relative;
}

to the system.base.css files. That didn't work for me, and I've been playing with positioning for practically the whole day now, do you guys have any suggestions as to how I can amend/fix this?
It is not related to anything like this:
(custom )Autocomplete won't work when the user is not logged
as it isn't a custom function doing the autocomplete, it's through the taxonomy.
It can't be a permissions error either because the menu with suggestions shows up, just not where it's supposed to.
Answer: I think anonymous user doesn't have a permission of autocomplete. Can you please visit permission tab of your site. May be you get some luck!
Hold on, you are using taxonomy right, then please check this module permission. I think that time you get some luck.
Comment: I couldn't find anything related to autocomplete in the permissions section. But it can't be that, because if it was the case, it wouldn't show up at all, yet it does show up, just not where it is supposed to.
Comment: I editted my answer, please check...
Comment: I've looked at all the possible permissions related to that and nothing.


what am i doing wrong with my while true try except else loop

Question: im trying to get my bot to go onto a website and if the website is down or not running properly for my bot to reload the page, and to loop that until it finds the clickable element by xpath, and then to continue on. im not sure exactly if im supposed to use "break" or "continue" and where their placed. if you can please answer with actual code instead of the way to do it, it would be amaizing. thanks
from selenium import webdriver
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
start_time = time.time()

path = "C:\Program Files (x86)\Common Files\Chromedriver.exe"
driver = webdriver.Chrome(path)

# open page
driver.get("https://www.usmint.gov/")
while True:
    progress = do_something(
try:
    element = WebDriverWait(driver, 4).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="navigation"]/div[3]/ul/li[2]/a')) #PRODUCT S
    )
except:# open page
driver.get("https://www.usmint.gov/")
else:
# product schedule
     driver.find_element_by_xpath('//*[@id="navigation"]/div[3]/ul/li[2]/a').click())
if progress is done
break:

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a')) #2020
    )
except:
else:
# 2020 product schedule
    driver.find_element_by_xpath('//*[@id="navigation"]/div[3]/ul/li[2]/div/div/ul/li[3]/a').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="cb0c26f755f49a3664c06800be"]/div/div/div[2]/div/div/a')) #birth set
    )
except:
else:
# birth set 2020
    driver.find_element_by_xpath('//*[@id="cb0c26f755f49a3664c06800be"]/div/div/div[2]/div/div/a').click()

    '''
try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="emailmodalclose"]')) #clear
    )
except:
else:
# clear email list stupidity
    driver.find_element_by_xpath('//*[@id="emailmodalclose"]').click()
     '''

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]')) #add to
    )
except:
else:
# add to bag
    driver.find_element_by_xpath("/html/body/div[1]/div[3]/div[2]/div[2]/form/div/div[5]/button[1]").click()# double qoutes?

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="mini-cart"]/div[3]/div[2]/div[3]/a')) #checkout
    )
except:
else:
# checkout
    driver.find_element_by_xpath('//*[@id="mini-cart"]/div[3]/div[2]/div[3]/a').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_login_username"]')) #login
    )
except:
else:
# login
    driver.find_element_by_xpath('//*[@id="dwfrm_login_username"]').send_keys("username")

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_login_password"]')) #Password
    )
except:
else:
# password
    driver.find_element_by_xpath('//*[@id="dwfrm_login_password"]').send_keys("password")

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="checkoutMethodLoginSubmit"]/span')) #checkout as
    )
except:
else:
    time.sleep(3)
# checkout as registered user
    driver.find_element_by_xpath('//*[@id="checkoutMethodLoginSubmit"]/span').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]')) #credit card scroll
    )
except:
else:
# credit card scroll
    driver.find_element_by_xpath('//*[@id="dwfrm_billing_paymentMethods_creditCardList"]/option[2]').click()  # .format?

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]')) #cc exp m
    )
except:
else:
    time.sleep(3)
# cc exp month
    driver.find_element_by_xpath('//*[@id="dwfrm_billing_paymentMethods_creditCard_month"]/option[2]').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]')) #cc exp y
    )
except:
else:
# cc exp year
    driver.find_element_by_xpath('//*[@id="dwfrm_billing_paymentMethods_creditCard_year"]/option[11]').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="dwfrm_billing_paymentMethods_creditCard_cvn"]')) #cvv
    )
except:
else:
# cvv
    driver.find_element_by_xpath('//*[@id="dwfrm_billing_paymentMethods_creditCard_cvn"]').send_keys("999")

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="checkoutContinuePaymentDelegator"]')) #continue to final
    )
except:
else:
# continue to final review
    driver.find_element_by_xpath('//*[@id="checkoutContinuePaymentDelegator"]').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="formAgreementLabel"]/span')) #terms of use
    )
except:
else:
# terms of use button
    driver.find_element_by_xpath('//*[@id="formAgreementLabel"]/span').click()

try:
    element = WebDriverWait(driver, 100).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="submitOrderButton"]')) #Place order
    )
except:
else:
# place order
    driver.find_element_by_xpath('//*[@id="submitOrderButton"]').click()
print ("time elapsed: {:.2f}s".format(time.time() - start_time))
driver.quit()
print("coin purchased")

#if __name__ == '__main__':
#   order(keys)

strong text
Comment: progress = do_something( Is kind of doing nothing.
Answer: There are several issues in your code and all seem similar.
This is a code part:
while True:
    progress = do_something(
try:
    element = WebDriverWait(driver, 4).until(
        EC.element_to_be_clickable((By.XPATH, '//*[@id="navigation"]/div[3]/ul/li[2]/a')) #PRODUCT S
    )
except:# open page
driver.get("https://www.usmint.gov/")

Issue 1
Your code does not run. On your image it is clearly visible where you should start fixing this code, Pycharm highlights the error with red, you opened a parentheses which you did not close. It seems like you wanted to set the try/except block as an argument, but progress = do_something( is not a complete statement, ) should precede the try block. You probably wanted to achieve something like this:
def action1():
    try:
        element = WebDriverWait(driver, 4).until(
            EC.element_to_be_clickable((By.XPATH, '//*[@id="navigation"]/div[3]/ul/li[2]/a')) #PRODUCT S
        )
    except:# open page
        driver.get("https://www.usmint.gov/")

Then you can progress = do_something(action1) or something.
Issue 2
Your indentation is incorrect in line 16 if I'm interpreting correctly what you may wanted to do. You can't just add new lines anywhere, "there are rules". If you want to nest a try/except block, inside a while loop, follow the indentation rules:
while condition:
    try:
        something()
    except Exception:
        continue

Issue 3
If you have a while True: block, you need to have a break with a condition somewhere else the loop will never end. It is unclear why is there a while loop there at all. There is a try block with a WebDriverWait where the code waits for an element, why would you want this to execute the same code multiple times? Shouldn't the code work for the first time?
Issue 4
The bare except is bad practice and not necessarily yields the result you would expect, also the indentation is incorrect. You won't have any information why the try part failed just the page will be opened. Worse if you put all this into a while loop and all you will see that the page will be reloaded again and again.
You probably don't want to catch all exceptions and probably you want to do different things when your xpath is broken versus the element isn't there versus a stale element exception versus the browser is not open. The right thing to do is:
try:
    something(this, that)
except AttributeError as ex:
    print(f'Oh no, an attribute error, values were: {this, that}')
    magical_attr_error_fix()
except ValueError as ex:
    print(f'Yikes, a value error, values were: {this, that}')
    raise ex

If you fix these kind of issues in your program it will probably start do something like you'd expect. Get rid of your while loops.


What makes a song a "rock" song?

Question: Sometimes I'm not completely sure when a song is a "rock song" or when it is from another music genre or even a "something-rock" song. How do you recognize it? Is it some bass rhythm? Some chord progressions? Some guitar picking pattern? The instruments? Some scale?
I find myself very confused with this. The rock in the 50's doesn't really have much to do with what people say it's rock in this days, and I even confuse some other genres with "rock" or "rock-something".
I liked a lot the music from Nirvana for example, and for me and a lot of people that was rock, until I discovered it was grunge which is a subgenre of a subgenre, inspired by other genres and so on...
Is there a way to recognize it by paying attention to some characteristic of the melody, or is it just the feel of it?
I looked in wikipedia and there are more than two hundred subgenres of rock, a lot of them mixed with other genres and stuff, so how do you know a song is a rock song, or that a group is a rock group?
Is there a simple or at least consistent way to know this?
Comment: Anything  that can't really be placed in any another genre and is played with a small ensemble and electric instruments can be called "rock".
Comment: Back in the '60s, if you could jive to it, it was rock'n'roll. If not, it wasn't.
Answer: Rock music is defined by rhythm, not melody. Rock is in 4/4 time with the heavy beats being 2 and 4.
Rock and roll in the '50s has exactly this in common with all of your "sub-genres" that you consider to be "rock" today. It's that simple.
I'm constantly amazed at how many people around the world today have essentially only listened to rock music all their lives and don't realize that there are many other kinds of music today and throughout history that don't use 4/4 time with the heavy beats on 2 and 4 at all.
The majority of Western music that is in 4/4 time, throughout history, has a different beat,  where the heavy beat is 1, while 2, 3 and 4 are weak beats. (Examples are the whole of European classical music, contemporary Mexican pop music, like banda and norteño, of which there is a lot in my neighborhood, and dances like the foxtrot or tango). There is also a great deal of music in the world that uses time signatures other than 4/4, such as the waltz, in 3/4, or the minuet, in 6/8.
If it is in 4/4 time and you clap along to it on the 2 and the 4, then it's rock music, or one of other related forms with a broader history such as the blues, jazz, country, R&B (rhythm and blues), or gospel. All of these forms come down to us from the rhythm of African-Americans, whose ancestors exported this rhythm from its birthplace in Africa when they were forcibly relocated to the New World.
Genres and sub-genres of "rock" notwithstanding, they all have this in common: the predominant rhythm is 4/4 with the heavy beats on 2 and 4. That is why all these sub-genres are called "rock".
Listen to other kinds of music that have nothing to do with rock, and you'll understand that the world of music is vast, but that rock is a very narrow genre with a very short history that just happens to be really popular in your particular culture in the present.
Comment: Then of course there is [progressive rock](http://en.wikipedia.org/wiki/Progressive_rock) where 4/4 might not be predominant. ;-P No rule without exception...
Comment: Indeed. But even prog rock and progressive metal use 4/4 with a rock beat often enough that it's clearly a defining characteristic. I am a huge lifelong fan of progressive rock!
Comment: There is also a lot of music in 4/4 with accents on 2 and 4 that is not considered rock music. I think there are also other factors defining rock music, e.g. chord progressions and the choice of instruments.
Comment: I agree with tomp. While 4/4 time with accents on 2 and 4 is a characteristic of rock music, it also is characteristic of jazz, classical and other genres. In addition to chords (power chords?), instruments (electric guitar, electric bass, drums), you also might consider song structure (32-bar, AABA) as a defining element.
Comment: "Rock is in 4/4 time" - tell that to Neal Peart (Rush) ! ;-) just pointoung out exceptions to a rule
Comment: Grateful Dead and many other "rock" bands use other time signatures besides 4/4.
Comment: Great answer!! I was afraid the question was deemed as subjective or something but I knew there was some theory behind this
Comment: Nice answer, although it'd be nice to clarify the difference between rock and jazz, blues, country, etc. I would say that jazz is usually swung, while rock is straight. Jazz also tends to use more piano and brass. Country uses more finger picking than rock (and maybe syncopation?), and banjos :D. I'm not very familiar with R&B and Gospel, but I'd say much slower beats, more focus on voice, vocal harmonies, religiosity, and slower melodies. Blues is more difficult, since it's a lot closer to Rock... um, slide guitar? Can be more swung and syncopated too.
Comment: naught101, that is really an old characterization of Country. I mean, yeah, in some corners there's a lot of that Chet Atkins stuff, but since the 90s Country music has sounded a lot like Rock music.
Comment: @VarLogRant: sure. I'm not a big country fan, so I'm not surprised that I'm way off. I was just supplying some examples, in order to prompt someone else into improving the answer. If I was more certain, I would have added it myself :)
Comment: BTW, the info for the rock-and-roll tag contains a description. See http://music.stackexchange.com/tags/rock-n-roll/info.
Comment: By this answer's definition this song is not a rock song, but it obvs is.
https://www.youtube.com/watch?v=xTgKRCXybSM&list=PLD0F66438C48D23C1&index=4&t=0s
Answer: This is really one of the most subjective areas in music, and one that individuals who follow a sub-genre get most militant about.
In my opinion, the only real way to do this is by comparison with other songs/bands in a particular genre. There are exceptions, for example Industrial - which has well defined descriptions based around the use of industrial noises sampled as percussion - but even this has a great deal of debate.
Even sites like rock.about.com have limited information on subgenres, and they use listings of bands in that subgenre as an indicator.
This image from Whitehotmagazine.com shows how complex the subgenre fields are:

tl;dr - don't worry about it. If you really need to know what genre a particular song is, find out who played it and try looking on their website, or asking a fan.
(For those who really want to know - Metaltech is Industrimental - bringing together classic rock, techno, industrial, funk and metal... :-)
Comment: Great diagram. Is there a higher res version somewhere? Some of it is pretty hard to read.
Comment: This one is a bit better (v2 of same diagram) - found by searching google images for  "Ward Shelly Rock Genres": http://www.wardshelley.com/paintings/pages/fullpics/rockgenres-v2%20copy.jpg   Original images seems to be  from this article : http://whitehotmagazine.com/articles/next-invitational-exhibition-emerging-art/1263
Comment: Your link to the whitehotmagazine image just loads their logo for me, I'm guessing they cache it for those who visited the page while those of us who see the hotlink are out of luck :P
Answer: Defining "rock" through a checklist of features (4/4 rhythm, guitars, beats on 2 and 4, guitarists who trash bathrooms) is a fools' errand. For every possible item on that list, there are counterexamples, and usually you can even find counterexamples within the canon of rock classics.
Personally, I find it is better to think of Rock as a loose tradition, rather than a genre. Rock has existed for almost 3/4 of a century now, of course it's changed in that time. You'd run into the same problem of vague genre definitions if you tried to define how "classical music" sounds. Every step on the way from Blues Rock and Rock&Roll to the huge landscape of rock and metal genres we have today is small enough to appreciate how we got from here to there, but overall, it's like comparing an expertly crafted hole in the ground with a skyscraper. Of course, they do not seem the same - time has passed between the two.
A better way to define Rock, in my opinion, is along the lines of "I know it when I see it". There are certain elements and signifiers that are common in Rock, and when a couple of them come together in a song, that song probably is Rock. In the absence of these signifiers, it probably isn't. Some of those elements are: a drum kit, an electric bass, at least one guitar, maybe an organ or later a synthesizer, a vocal line which is prominent in the song and provides a lot of the song's melodic interest, a structure of tense verses and resolved choruses, aggressive timbres and dynamics, heavy beats, extensive guitar solos which focus on technical craftsmanship, vocal techniques that range from fairly standard singing to high-pitched screaming (cf. "Child in Time", Deep Purple) or low-pitched growling (too much Death Metal to list it all), and quite often some spirit of rebellion, be it against "the establishment, or be it against prevailing trends in music. This list is definitely incomplete, and certain subgenres may value some of those points more than others.
While Rock is often associated with being harsh, and with being simple music for idiots, both of these clichés are patently untrue. Rock can be a very gentle and emotional genre (a lot of Clapton's work would come to mind), and it can be very complex at the same time (cf. Dream Theater, or the aforementioned "Child in Time", or the entirety of Pink Floyd's "The Wall").
We also have to acknowledge that the influence of Rock goes far beyond Rock itself: While Lady Gaga certainly isn't a rock musician, and wouldn't claim to be, she lists Iron Maiden's Bruce Dickinson as one of her influences as a singer. No surprise there, seeing how vastly popular and completely inescapable Rock has been for the last 70 years.
I realize that this reads as "you're asking the wrong question", but the point is, there is no neat, simple answer to this question. People love simple answers, and there have been some, but sadly, none of them really get down to the heart of the matter.
tl;dr: What is Rock? It's complicated. Don't try and put all music into neat little boxes, because music isn't made to fit into neat little boxes.
Answer: I used to think that Avril Lavigne was rock and that Coldplay was pop, but it's actually the opposite. Avril Lavigne uses lots of guitars on her songs, sounds very close to rock'n'roll, but it's pop. And Coldplay, sound too pop for me, with much more piano/acoustic guitar than electric guitar. But it's still considered a rock band.
Wheat Williams said that rock'n'roll is defined by RHYTHM, heavy beats on 2 and 4 in a 4/4 time signature, but I'm sure I've heard this backbeat in pop music as well. If you listen to a pop song called Don't Let Me Get Me by P!nk, you'll hear that empashis on 2 and 4, with guitar, but still, it's not considered a rock song. And I've heard a rock song that doesn't follow that pattern, which the emphasis are on 1 and 3.
Comment: I have made edits to your answer to try and make it fit. You should be aware that pop music can also be rock, or jazz, or pretty much anything. And as Ulf commented, there can be exceptions to any rule.
Comment: Genre is subjective and hard to define. I consider Don't Let Me Get Me to be a rock song, along with many others of Pink's songs, and I'm far from the only one (e.g. see [this Slate podcast](https://slate.com/podcasts/hit-parade/2023/03/pink-defined-her-own-r-and-b-to-rock-genre) discussing the song and its genre). I'd say (and Slate's commentators seem to be suggesting the same thing) genre is often defined more by who the artist is rather than the content of the product, and there's a reluctance to label Pink as rock primarily because she started in R&B.
Answer: I believe it needs to analyse not only the song, but also the artist, the context. Even Dave Grohl (Foo Fighters) compared Billie Eilish to Nirvana, stating that "rock n roll is not dead". Billie's songs are heavily influences by rap. Sometimes ppl include Elton John on rock lists.
There is not a specific rule. Electric guitar is common, but there are rock songs. Attitude is another strong characteristic of Rock songs, but Beatles started with Love Me Do, which is not rock's "attitude".
In short: does it have electric guitar + attitude? 99% chance it is rock.
Comment: Uh, ok.  So, after the drums and electric guitar come in on Stairway to Heaven, it is still absent of attitude?  That's incorrect.  However, if we look to Led Zeppelin III, and listen to That's The Way, the song is completely devoid of electric guitar and drums.  This particular song is not rock, but instead whatever you classify with acoustic guitars and vocals.
Comment: Stairway to Heaven does not have "attitude", whatever that means, and for large parts is played on an acoustic guitar, or on an extremely clean electric guitar trying to imitate the acoustic sound. Is it Rock? Well, obviously it is, but under your definition, it's very easy to claim it isn't.
Answer: Difference between pop and rock is that rock will have a few to many off beat chord changes through out the song, very simple. Those few or more changes happen between the 1, 2, 3 and 4 downbeats. Some bands like Styx may have a couple pop ballads for radio that are pop and have no offbeat chords or punches while the majority if their catalogue is rock with offbeat chords and punched. Although as some mention, the emphasis on beat 2 and 4 are a distinction, but the offbeat chords and punches are the key
Comment: So you came to a two-year-old-question for this blatantly wrong and overly simplified answer?
Comment: *Lot's* of rock songs only have chord changes on regular beats, or even only between measures or on the 3 beat. I'd say having chord changes at offbeat locations is more likely to push a song into a subgenre, e.g. alternative rock, to be honest.
Answer: Air Supply and Slayer are both categorized as Rock. Rock, as a term, is meaningless.
Comment: Air Supply and Slayer both perform songs in 4/4 time with the heavy beats being 2 and 4. That's why they are both rock bands.

What makes a song a "rock" song?


Setting html text to Description of VCALENDAR

Question: I want to set the html text in the description of the vcalendar.
How to do this?
Answer: Unfortunately Outlook doesn't support HTML in vCalendar/ICS event descriptions.
When using Outlook, rich text format can be used in descriptions. However when you try to export it, the formatting gets dropped and a hard coded wrapper (customized on the fly by the application logic) is added to fix the text encoding. The encoding can be changed through Outlook settings, oh thanks god ! =P


Squash commits before hash

Question: I have forked a quick-start repo and built an app on top of it. The quick-start repo contained ~30 commits. The last commit of their repo is, say, abcde and first commit of mine is, say, fghij. How can I squash all of the commits, from first to abcde, so that there is only one, big commit before fghij.
Could you please explain it line by line. I don't understand other answers under similar topics.
Example history tree of commits now:
klmno - Currently newest commit
.
.
.
fghij - Initial commit of mine
abcde - Last commit made by them
.
.
vwxyz - Initial commit of theirs

Example history tree of commits expected:
klmno - Currently newest commit
.
.
.
fghij - Initial commit of mine
prstu - Fresh X installation

Comment: When you say "forked", do you intend to keep pulling from the upstream repository? What about pull requests back, do you intend to do that?
Comment: No. I wrongly worded what I've done. I have cloned a repo locally and then changed the origin to be my repo. I will not pull from upstream (or the cloned repo, rather) and I won't be making any PRs
Comment: OK, then the answer provided by @RobinGreen should work just fine, let him know if you need more details about the process but interactive rebase is the way to go.
Comment: I will give it a try, but I am waiting for all PRs to be merged at my repo. Hopefully tomorrow I'll be able to test it. Thanks ;)
Answer: First enter git's interactive rebase mode - note that in this special case, you have to specify the special option --root to edit the root (first) commit, which is usually not allowed with the git rebase command:
git rebase -i --root

If you have not configured the EDITOR environment variable, you will be taken into git's default text editor, which I think is always vi. If you don't understand vi, type :q to exit and start the process again - this time, setting EDITOR to the name of a text editor you do know how to use.
In the interactive rebase file that git gives you to edit, change all the lines for the commits from the second commit to abcde to start with the word fixup instead of pick. Leave the lines for your commits, and the line for the very first commit, unchanged.
Save the file and exit the text editor. git will now perform the squashing of the original repository's commits into one commit.
Comment: Thank you for your answer. It is what I was lookin for, however I have encountered an error along the way:
"error: could not apply a2e009e... update readme with links to more guides and examples

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort".

Could not apply a2e009e5c1488c758e1a87410910c2daa03a88b5... update readme with links to more guides and examples"
Comment: I did not realise there were PRs to your repo - so the history is non-linear? Can you share a link to your fork so I can have a look at it?
Comment: First commit is here: https://github.com/quickwords/quickwords/commits/master?after=3800eac6aa7d243e398c9712c611c2cb53368850+279

It's the "Added package-lock file" with 98e576449c7293a3eecf0c91d0940426c1400647 hash
Comment: OK, makes sense. If you want to preserve the merges, do `git rebase --abort` and then try again by adding `--preserve-merges` to the command I gave in my answer. However, either way, you may encounter conflicts because git doesn't, by default, remember the solutions to merge conflicts when rebasing. So you'll most likely have to re-solve merge conflicts that you solved before.
Comment: It seems like it doesn't really work. Am I wrong, or should it be way easier for Git? I mean, it knows how files should look like in the end, so it shouldn't be that hard, right? Anyway, if you know how to fix that, it would be awesome. I have marked your answer as the best, with big thank you message attached. ;)
Comment: I agree, it should be easier for git. I suggest you ask a new question, similar to this one, that makes it clear that your repository contains many merges, and that this solution didn't work very well. I will then attempt to answer that question.

Squash commits before hash


Index was out of range. Must be non-negative and less than the size of the collection

Question: i have this code:
ArrayList list = new ArrayList();
foreach (DataRow dataR in prenume.Rows)
{
    foreach (var item in dataR.ItemArray)
    {
        if (item.Equals("  ")) continue;
        list.Add(item);
        if (input_string.Equals(item.ToString()) && list.Count > 0 )
        {
            label_hello.Text = "Hello, " + list[2];
        }
    }
}

When i'm trying to clear the text showed , i get an error which says:

Index was out of range. Must be non-negative and less  than the size
  of the collection.

Later edit:
        Solution found!I was too tired ... sorry for the question!

Answer: Well, you start off with an empty list, and then after adding a single item, you might execute (if input_string equals the first item in the first item array):
label_hello.Text = "Hello, " + list[2];

That's trying to access the third item in the list. It will fail when there's only one item. Why did you pick 2 here?
(As an aside, why are you using ArrayList? The generic List<T> type is preferred.)
It's not clear what you're trying to achieve - if you can give us more context, we have a better chance of helping you.
EDIT: From the comments, it looks like this should be
label_hello.Text = "Hello, " + dataR[2];

However, I suspect the loops are still not right... why would you want to iterate over every value in the table, rather than (say) in just one column?
Comment: Asking a guy who doesn't know how to use arrays and indexers why you didn't use `Generics` is like asking me, hmmm, a lot of things...
Comment: @EmilDumbazu: No it doesn't - look carefully at your code... you create a new list (so it's empty) and the if the input string is equal to the first item in the item array, it will go into that block and execute the failing statement when the list only has one element. It's not at all clear what you're trying to do, but that's why it's failing.
Comment: Because that's the element from the arraylist which i want to write.
Comment: @EmilDumbazu: But the list doesn't *have* three elements - the first time you get to this statement, the list will only have a single element. So how can the *third* element be the one you want?
Comment: The code executes when a text from textbox is changed. And the list has as many elements as characters....
Comment: Perhaps you meant do do: `dataR.ItemArray[2]` instead at that point?
Comment: I have a Datatable which contains rows like (id,name,password). What i want to do is that when the user has entered his password , a label message like "Hello "+name should be displayed.
Comment: @EmilDumbazu: So why are you using `list[2]`? Did you mean `dataR[2]`?
Comment: Yeah , thank you ! I'm too tired and now i realize how stupid i was. Sorry guys !
Answer: Ofcourse it will give an error.
label_hello.Text = "Hello, " + list[2];

is wrong.
You have only one element list[0] at that stage.
Comment: If it works exactly how you want it to work, why are you asking? If you *want* that exception, why are you asking about it?
Comment: If you want the second element, get your list[2] outside the foreach loop.
Answer: you're getting your error on the following line
label_hello.Text = "Hello, " + list[2];

The reason why you're getting that error is because there is no list[2]
Now, I can't tell exactly what you're trying to do, but I have a sneaky suspicion that you intend 'item' to be a string of some sort, and you want to access the third character in that string.
Even then, keep in mind that sometimes the user might try to input a string that is not 3 or more characters in length.
If you can give more details about what you're trying to do,  we can help you further.


Solve $\int \sqrt{7x + 4}\,dx$

Question: I need to solve the following integral
$$\int \sqrt{7x + 4}\,dx$$
I did the following steps:
\begin{align}
\text{Let} \, u &= 7x+4 \quad \text{Let} \, du = 7 \, dx \\
\int &\sqrt{u} \, du\\
&\frac{2 (7x+4)^{3/2}}{3}
\end{align}
The solution is: $\frac{2 (7x+4)^{3/2}}{21}$. I am having some trouble understanding where the denominator, $21$, comes from (is it because you integrate $du$ also and thus, $7 dx$ becomes $\frac{1}{7}$?). I believe this is some elementary step that I am missing. Can someone please explain to me this?
Thanks!
P.S Is it correct to say "solve the integral"?
Comment: You had $dx = \frac{du}{7}$, but you wrote only $du$.
Comment: Maybe "evaluate the integral" instead.
Comment: Solve the integral sounds okay to me.
Answer: I suspect that you mean "calculate the integral $\int\sqrt{7x+4}\,dx.$" Your method was fine, except you have $du=7dx,$ so $dx=\frac17du,$ whence $$\int\sqrt{7x+4}\,dx=\int\sqrt{u}\left(\frac17du\right)=\frac17\int\sqrt{u}\,du.$$
Comment: @gekkostate You can still use this method, since:
$$
\int \dfrac{\cos x}{\sin^2 x}dx = \int \dfrac{\cos x}{u^2} \cdot \dfrac{du}{\cos x}  = \int \dfrac{1}{u^2}du
$$
Comment: Ahh I see but for another question $\int \frac{\cos x}{\sin^2 x}$. The solution let $u = \sin x$ and $du = \cos x \, dx$ but then they didn't do $\frac{du}{\cos x} = dx$ how come? What's the difference?
Comment: Ahh! I see now. Thank you!
Answer: When you made the u-substitution, you took $u=7x+4$ and hence $du=7 dx$. You forgot this factor of 7! In particular, $dx=du/7$.
It helps to write out the $dx$ in the integral:
$$\int \sqrt{7x+4} dx=\int \frac{\sqrt{u}}{7} du.$$

Solve $\int \sqrt{7x + 4}\,dx$


How to hide roles from user_profil_form while keeping value?

Question: After loading user_profil_form form, I tried to hide the roles fields.
It worked fine, however after submitting the form, my user roles are removed and it's only linked to "authenticated user".
Is there a way hide this field but keeping the value ? I would not like to user the alter hook in order to keep the full form in the admin pages.
Thank you
Answer: In my experience, unsetting the field works fine to disallow access to a field while keeping values on update. For example:
<code>/**
 * Implements hook_form_alter.
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == 'user_profile_form') {
    unset($form['account']['roles']);
  }
}
</code>
Comment: I do not want this to affect the admin pages so I am trying to avoid using hook_form_alter.
Comment: I'm not too sure what you mean by "admin" pages but the if statement in the above code means that it will work on the user/add page and user/[uid]/edit page. If you don't want to hide this field for admins then you will need to apply that condition in your code. Preferably by writing your own custom permission through hook_permission and calling user_access with your permission as an argument.
Comment: Thank you, you're right using permissions and your code is the perfect answer in that case !
Answer: You should use the '#access' = 0 for the roles field appropriately to hide it from users
Comment: I thought so, however while logged with the administrator :
account '#access' = 0 hide the field and while saving, the roles are removed and "authenticated user" is the only one left


Exercise 1.3.16 in Hatcher

Question: I know this question has been asked before, but I couldn't find a satisfying answer so I hope to find it now.
Let $p:X\to Y$ and $q:Y\to Z$ be maps such that $q$ and $q\circ p$ are covering map and $Z$ is locally path-connected. Then $p$ is a covering map, too. So, I choose $y\in Y$ and choose $U_y$ a neighbourhood of $y$ such that $q|_{U_y}:U_y\to q(U_y)$ is a homeomorphism. Then, the set $\{q(U_y)\colon y\in Y\}$ covers $Z$. We see that $(q\circ p)^{-1}(q(U_y))=p^{-1}(U_y)$. Now, I that I only have to show that $p|_{p^{-1}(U_y)}$ is a homeomorphism. How can I do this, and where do I need locally path-connectedness?
Comment: See problem 16 here: http://www.math.uchicago.edu/~reidh/AT/Hatcher_Algebraic-Topology-Solutions.pdf
Comment: Why do we need path connectedness of $p(U)$?
Answer: Let us first observe that Hatcher's definition of a covering map is somewhat unusual because he does not require surjectivity. Compare this with the definition in Wikipedia. We come back to this point later.
What you have to show is that
(1) $p^{-1}(U_y) = \bigcup_{\alpha \in A} V_\alpha$ with pairwise disjoint open $V_\alpha$ (which are called sheets over $U_y$) such that each $p_\alpha : V_\alpha \stackrel{p}{\rightarrow} U_y$ is a homeomorphism.
This has nothing to do with showing that $p|_{p^{-1}(U_y)}$ is a homeomorphism. In general the latter will be false. Moreover, your approach cannot work because you do not use fact that $q$ is a covering map; you only invoke that $q$ is a local homeomorphism.
To prove (1), let $y \in Y$ and $W$ be an open neighborhood of $q(y)$ which is evenly covered by $q$ and by $q \circ p$. That is, $q^{-1}(W) = \bigcup_{\beta \in B} U_\beta$ with pairwise disjoint open $U_\beta$ such that each $q_\beta : U_\beta \stackrel{q}{\rightarrow} W$ is a homeomorphism, and $(q \circ p)^{-1}(W) = \bigcup_{\gamma \in C} V_\gamma$ with pairwise disjoint open $V_\gamma$ such that each $(q \circ p)_\gamma : V_\gamma \stackrel{q \circ p}{\rightarrow} W$ is a homeomorphism.
Let $\beta$ be the unique index with $y \in U_\beta$. Then take $U_y = U_\beta$. We get $p^{-1}(U_y) \subset (q \circ p)^{-1}(W)$, but it is not at all clear that $p^{-1}(U_y) = \bigcup_{\gamma \in C'} V_\gamma$ for some $C' \subset C$. Only if that is the case, we can conclude that for all $\gamma \in C'$ the map $p_\gamma : V_\gamma \to U_y$ is a homeomomorphism (because then $(q \circ p)_\gamma = q_\beta \circ p_\gamma$, i.e. $p_\gamma = q^{-1}_\beta \circ (q \circ p)_\gamma$).
So what can assure that for all $\beta$ there exists $C(\beta) \subset C$ such that $p^{-1}(U_\beta) = \bigcup_{\gamma \in C(\beta)} V_\gamma$? We shall see that this is true if $W$ is connected.
In fact, in this case the $V_\gamma$ are connected, that is, they are the components of $(q \circ p)^{-1}(W)$. This is a distinguishing feature of connected evenly covered $W$. No $V_\gamma$ can intersect more than one $p^{-1}(U_\beta)$ because otherwise we would get a partition of $V_\gamma$ into pairwise disjoint open sets. Therefore each $V_\gamma$ is contained in a unique $p^{-1}(U_{\beta(\gamma)})$. Since each $p^{-1}(U_\beta)$ is covered by the collection of all $V_\gamma$, we see that each $p^{-1}(U_\beta)$ is the union of suitable subcollection $\{ V_\gamma \mid \gamma \in C(\beta) \}$.
Which  assumption assures that each $z \in Z$ has a connected open neighborhhod which is evenly covered by $q$ and by $q \circ p$? This is that each $z \in Z$ has a neighborhood base consisting of connected open neighborhoods, i.e. the local connectedness of $Z$. This is a little weaker than local path-connectedness. So we can explicitly state

If $Z$ is locally connected, then $p$ is a covering map in the sense of Hatcher.

If we adopt the standard definition of covering maps (including surjectivity), then $p$ is not necessarily a covering map because it may lack surjectivity. An example is this. Let $Y = Z \times \{ 0 , 1 \}$ and $q$ be the projection onto the first factor, let $X = Z$ and $q = id$, $p(z) = (z,0)$. Then $q$ and $q \circ p = id$ are (surjective) covering maps, but $p^{-1}(Z \times \{ 1 \})$ is empty.
This shows that we need an additional assumption assuring that $p$ is surjective. A trivial solution is to simply amend the requirement that $p$ is surjective. A less trivial alternative is to assume that $Y$ is connected. See my answer to  $p:X\to Y$ covering space if $q\circ p:X\to Z$ and $q:Y\to Z$ covering spaces and $Z$ locally path-connected..

Exercise 1.3.16 in Hatcher


The role of $\gamma$ & $C$ in SVM

Question: I'm using support vector machine method with the Gaussian kernel. Is it true that $\gamma$ and $C$ are hyper parameters of SVM? What is their role exactly?
Answer: Support vector machines with RBF kernel have the following objective function:
$$
\min_{\alpha, b, \xi} \frac{1}{2} \underbrace{\sum_{i\in SV}\sum_{j\in SV} \alpha_i \alpha_j y_i y_j \exp\big(-{\color{red}\gamma} \|\mathbf{x}_i-\mathbf{x}_j\|^2\big)}_{\|\mathbf{w}\|^2} + {\color{red}C}\sum_{i\in SV} \xi_i
$$
$C$ is a regularization parameter, which is used to control the tradeoff between model simplicity (low $\|\mathbf{w}\|^2$) and how well the model fits the data (low $\sum_{i\in SV} \xi_i$).
The kernel parameter $\gamma$ is used to control the locality of the kernel function. It varies between 0 and $\infty$ (in these limits the kernel matrix becomes the one matrix and unit matrix, respectively). Good values are somewhere in between.
It is crucial to optimize these parameters to obtain a good model. You can do that using many techniques, including grid search or software packages like Optunity.

The role of $\gamma$ & $C$ in SVM


How to override configuration variables in settings.php

Question: I need to override configuration variables declared in the settings.php. How this can be possible? Any help me on?
Note: I am trying to override a custom configuration variable, not any default one.
Comment: Conf values in settings.php always "win"...they're supposed to be unconditional overrides, stuff that the programmer/site builder is saying to Drupal "don't change these, I need them to be exactly this for my site to work". So to override a var set in settings.php, you need to change it in settings.php (or change the way `variable_get` works)
Comment: @ Krishna Mohan Thanks. But using variable_set(), it will override the configuration variable to the function in which it is used. If we try get the value of config variable in another function it will displays it again from settings.php. I need to override this in such a way that, wherever we try to fetch that variable the value will be the new one.
Comment: Refer https://coderwall.com/p/tdoztq
Comment: @akm That's not possible without rewriting `variable_get`
Comment: @Clive Thanks. So there is no possible way to override it without editing the settings.php?
Comment: Clive is correct that if you set `$conf['myvariable']` in settings.php, it will win out, and cannot be changed. Usually, though, you want to change 'myvariable' because it controls something. Possibly a better question to ask is what you want to be able to change. Depending upon what that is, you may find there is an alternate strategy to change Drupal's behavior. But we'd need to know which variable you were changing.
Comment: I am trying to override a custom configuration variable, not any default one.
Answer: You can't overwrite the variables in settings.php.


If $f^{-1}[\{0\}]=g^{-1}[\{c\}]$ and $c$ is a regular value of $g$, is $0$ a regular value of $f$?

Question: I was wondering. Suppose $f: \mathbb R^{n}\rightarrow \mathbb R^m$ and $g:\mathbb R^{n}\rightarrow \mathbb R^k$ $(m, k<n)$ are two smooth functions such that $f^{-1}[\{0\}]=g^{-1}[\{c\}]$ and $c$ is a regular value of $g$. Is $0$ a regular value of $f$?
Answer: I think I got us a counter example. Let $f\colon \Bbb R^3 \to \Bbb R^2$ be the shifted projection $f(x,y,z) = (x-1,0)$. Then $${\rm D}f(x,y,z) = \begin{pmatrix}1 & 0 & 0 \\ 0 & 0 & 0 \end{pmatrix}$$is never surjective. Also, let $g\colon \Bbb R^3 \to \Bbb R$ be the same projection, in some sense: $g(x,y,z) = x$. Then $g^{-1}(1) = f^{-1}(0)$, $1$ is a regular value of $g$ because $\nabla g(x,y,z) = (1,0,0) \neq {\bf 0}$ always, but $0$ is not a regular value of $f$.


Evaluate the integral $\int \cot(x) \cos(x) \ dx$

Question: I am asked to integrate
$$
\int \cot(x) \cos(x) \ dx
$$
How ca I do that? Using the trig substitution
$$
\cos^2(x) = \frac{1}{2} \left( 1+\cos(2x) \right)
$$
doesn't get me any further.
Thank you.
Answer: Observe that $$\int \cot(x) \cos(x) \, dx  = \int \frac{\cos^2(x)}{\sin(x)} \, dx = \int \frac{1- \sin^2(x)}{\sin(x)} \, dx = \int [\text{cosec}(x) - \sin(x)] \, dx.$$
Using the standard integral $$\int \text{cosec}(x) \, dx = -\ln(\text{cosec}(x) + \cot(x)) + C,$$ it should now be quite simple to find your answer.
Comment: Great, thank you. Best Regards!
Answer: my answer:
$\int \cot x\cos x\ dx$
$=\cot x\int \cos x\ dx-\int\ \left(\frac{d}{dx}(\cot x)\int \cos x\ dx\right)dx$
$=\cot x\sin x-\int (-\csc^2x)\sin x\ dx$
$=\cos x+\int \csc x\ dx$
$=\cos x+\ln(\csc x-\cot x)+C$
Answer: $$\int  \cot  (x)\cos  (x)dx=\int  \frac { \cos { \left( x \right)  }  }{ \sin { \left( x \right)  }  } \cos  (x)dx=\\ =\int { \frac { 1-\sin ^{ 2 }{ \left( x \right)  }  }{ \sin { \left( x \right)  }  }  } dx=\int { \frac { dx }{ \sin { \left( x \right)  }  } -\int { \sin { \left( x \right) dx }  }  } =\\ =\int { \frac { \sin { \left( x \right) dx }  }{ \sin ^{ 2 }{ \left( x \right)  }  }  } +\cos { \left( x \right) =-\int { \frac { d\cos { \left( x \right)  }  }{ 1-\cos ^{ 2 }{ \left( x \right)  }  }  }  } +\cos { \left( x \right) = } \\ =-\frac { 1 }{ 2 } \left[ \int { \frac { d\cos { \left( x \right)  }  }{ 1-\cos { \left( x \right)  }  } +\frac { d\cos { \left( x \right)  }  }{ 1+\cos { \left( x \right)  }  }  }  \right] +\cos { \left( x \right) = } \\ =-\frac { 1 }{ 2 } \ln { \left| \frac { 1+\cos { \left( x \right)  }  }{ 1-\cos { \left( x \right)  }  }  \right| +\cos { \left( x \right)  } +C } $$
Comment: You can use $\begin{align}$ with $\end{align}$ and &= to align your equals signs. It would make your solution easier to read.
Comment: @Mattos,thank for advise,i can't write it as you sias  ,but i will learn)
Answer: $$
\begin{align}
\int\cot(x)\cos(x)\,\mathrm{d}x
&=\int\frac{\cos^2(x)}{\sin(x)}\,\mathrm{d}x\\
&=-\int\frac{\cos^2(x)}{\sin^2(x)}\,\mathrm{d}\cos(x)\\
&=\int\left(1-\frac1{1-\cos^2(x)}\right)\mathrm{d}\cos(x)\\
&=\cos(x)-\frac12\int\left(\frac1{1-\cos(x)}+\frac1{1+\cos(x)}\right)\mathrm{d}\cos(x)\\
&=\cos(x)+\frac12\log\left(\frac{1-\cos(x)}{1+\cos(x)}\right)+C\\[3pt]
&=\cos(x)+\log\left|\frac{\sin(x)}{1+\cos(x)}\right|+C\\[3pt]
&=\cos(x)+\log\left|\tan\left(\frac x2\right)\right|+C
\end{align}
$$
Answer: You can use IBP:
Let $u = \cot x$ and $dv = \cos x dx$
$$\int \cot x \cos x \ dx$$
$$ = uv - \int [v] [du]$$
$$ = (\cot x) \left[\int \cos x dx \right] - \int \left[\int \cos x dx \right]\left[\frac{d}{dx} \cot x dx \right]$$
$$ = (\cot x) \left[\sin x \right] - \int \sin x \left[\frac{d}{dx} \cot x\right] dx $$


Find the metric on sphere induced from the embedding

Question: Currently, I started reading a book "Riemannian Geometry, Peter Petersen". In this book, Example 3 on page 3 explains the Euclidean sphere of radius $r$.
$$S^n(r) = \{x \in R^{n+1} : |x| = r\}$$
The authors said that the metric induced from the embedding $j:S^n(r) \to R^{n+1}$ is the canonical metric on $S^n(r)$. The embedding is given by an inclusion.
I want to find the metric on the sphere induced from the given map. Since the embedding is given, we can construct a Riemmanian metric on $S^n(r)$ by pulling back the canonical metric on Euclidean space.
$$g_{S^n(r)}(v,w) = g_{R^n}(Dj(v),Dj(w))$$
for $v,w \in T_pS^n.$
Since $j$ is an inclusion map, $Dj=Id$, so I think
$$g_{S^n(r)}(v,w) = g_{R^n}(Dj(v),Dj(w)) = g_{R^n}(v,w).$$
Then, is the metric $g_{s^n(r)}$ the same as the metric $g_{R^n}$?
Edit: For $v,w \in T_pS^n$,
$$g_{S^n(r)}(v,w) = g_{R^n}(Dj(v),Dj(w)) = g_{R^n}(v,w)$$
as mentioned above. Take an orthonormal basis $\{e_1, e_2, \cdots, e_n\}$.
Then $v= \sum v^i e_i$ and $w= \sum w^i e_i$ for some $v^i$ and $w^i$.
I want to calculate $$g_{S^n(r)}(v,w).$$
At first, I thought
$$g_{S^n(r)}(v,w) = g_{R^n}(v,w) = v^i w^i$$
because $g_{R^n}$ is an identity matrix. However, I caught my mistake that $v=v^ie_i$ and $w=w^i e_i$ in the Euclidean space $R^{n+1}$. I cannot proceed further. How can I evaluate $g_{S^n(r)}(v,w)$ correctly?
Comment: It's right, but of course $v$ and $w$ must be tangent to the sphere (at the same point).
Comment: @TedShifrin Thank you. Could you see my edit?
Comment: To proceed, you should choose a chart on $\mathbb{S}^n$, and use the induced basis on $T_x\mathbb{S}^n$ to compute the metric tensor
Comment: @Caffeine To compute the metric tensor, could I choose one specific chart on $S^n$? (e.g., using Streographic projection or using monge patch)
Comment: Suggestion: Compute the pullback of the $2$-tensor $\sum dx^i\otimes dx^i$ by the inclusion map. Start with $n=1$ and $n=2$.
Answer: Petersen recommends using Lee's Introduction to Smooth Manifolds in the preface, so let's just unravel his definitions to see what we get for the differential of a smooth map between smooth manifolds $F : M \to N$. Take coordinate charts $(U, \phi)$ around $p$ and $(V, \psi)$ around $F(p)$ and note that for any $v \in T_pM$ we have, for $f \in C^\infty(U)$:
\begin{align}
\text DF(v)(f) &= v(f\circ F) = \sum_{i=1}^m v_i \frac{\partial}{\partial x^i} f\circ F \circ \phi^{-1}\big|_{x = \phi(p)}
\\
&=\sum_{i=1}^m v_i \frac{\partial}{\partial x^i} [(f \circ \psi^{-1}) \circ(\psi \circ F \circ \phi^{-1})]\big|_{x = \phi(p)}
\\
&=\sum_{i=1}^m v_i \sum_{j = 1}^n\frac{\partial}{\partial y^j} (f \circ \psi^{-1})\big |_{y = \psi(F(p))} \cdot \frac{\partial [\psi \circ F \circ \phi^{-1}]_j}{\partial x^i}\big|_{x = \phi(p)}
\\
&=\sum_{j = 1}^n\left(\sum_{i=1}^m v_i  \frac{\partial [\psi \circ F \circ \phi^{-1}]_j}{\partial x^i}\big|_{x = \phi(p)}\right)\frac{\partial}{\partial y^j} (f \circ \psi^{-1})\big |_{y = \psi(F(p))}
\end{align}
In particular, on basis elements:
$$
\text DF\left(\frac{\partial}{\partial x^i}\right)(f) = \sum_{j = 1}^n\frac{\partial [\psi \circ F \circ \phi^{-1}]_j}{\partial x^i}\big|_{x = \phi(p)}\frac{\partial}{\partial y^j} (f \circ \psi^{-1})\big |_{y = \psi(F(p))}
$$
since we want to find the components of the induced metric, it suffices to evaluate it on the tensor product of basis elements
\begin{align}
g_{M}\left(\frac{\partial}{\partial x^i}, \frac{\partial}{\partial x^j}\right) &=\sum_{k,r = 1}^n\frac{\partial [\psi \circ F \circ \phi^{-1}]_k}{\partial x^i}\big|_{x = \phi(p)}\frac{\partial [\psi \circ F \circ \phi^{-1}]_r}{\partial x^j}\big|_{x = \phi(p)}g_N\left(\frac{\partial}{\partial y^k} (f \circ \psi^{-1})\big |_{y = \psi(F(p))},\frac{\partial}{\partial y^r} (f \circ \psi^{-1})\big |_{y = \psi(F(p))} \right)
\\
&=\sum_{k,r = 1}^n\frac{\partial [\psi \circ F \circ \phi^{-1}]_k}{\partial x^i}\big|_{x = \phi(p)}\frac{\partial [\psi \circ F \circ \phi^{-1}]_r}{\partial x^j}\big|_{x = \phi(p)}[g_N]_{kr}
\end{align}
where $[g]_{kr}$ are the local coordinate components of the metric $g$. In particular, we can take the canonical metric on $N = \Bbb R^n$ to reduce $[g_N]_{kr} = \delta_{kr}$ if $F$ is the embedding $S^{n-1}\hookrightarrow \Bbb R^n$. Moreover, the chart $\psi$ is given by the identity and so the above equation yields, for your preferred parametrization  $\phi$ of the sphere:
\begin{align}
[g_{S^{n-1}}]_{ij}
&=\sum_{k = 1}^n\frac{\partial [\phi^{-1}]_k}{\partial x^i}\big|_{x = \phi(p)}\frac{\partial [\phi^{-1}]_k}{\partial x^j}\big|_{x = \phi(p)}
\end{align}


If a transformation of a random variable preserves its mean and variance, can it change the covariance with another random variable?

Question: Let $X$ and $Y$ be two real-valued random variables in $L^2$, and let $f:\mathbb R\to\mathbb R$ be a deterministic function such that $\mathbb E[f(X)] = \mathbb E[X]$ and $\mathrm{Var}(f(X)) = \mathrm{Var}(X)$.
Does
$$\mathrm{Cov}(f(X),Y) = \mathrm{Cov}(X,Y)$$
hold necessarily?
Comment: I would guess the answer is no
Comment: No to the title, or no to the equality of covariances? Sorry for the confusion.
Answer: No. Take $$X=Y \sim \mathcal{N}(0,1), \quad f(x)=-x.$$ It has the requested properties (since also $-X \sim \mathcal{N}(0,1)$), but
$$ \text{Cov}(X,Y)=\text{Var}(X)=E[X^2] - E[X]^2 \neq -E[X^2] + E[X]^2 = \text{Cov}(-X,Y).$$
Comment: Cheers! Thanks.


How to display Rate module widget by php

Question: I'm using the Page Manager (Panel) to customize the node layout, and the Rate module to rate them.
How to print the rating widget of the current node using php ?
I've tried to use this code but no result.
<code><?php  print rate_embed($node, 'page_rating', RATE_FULL);  ?>
</code>
Comment: resolved ``
Answer: print $node->rate_NAME['#markup'];
Replace NAME by the widget's machine readable name.
Answer: print rate_embed($node, 'plus1', RATE_FULL);
Here, first parameter($node) is the entity where you want to vote
'plus1' is the type of widget that you want to add
RATE_FULL is the display type of widget . Either it can be full or mini.
Try by passing $node =node_load(10). Where 10 is id of some node that exists in the site
Hope it will help


Existence of a sequence converging to $0$

Question: Let $(G,+,\le)$ be a partially ordered group (with identity $0$) and suppose that for each positive $g \in G$ there exists $g^\prime \in G$ such that $0<g^\prime<g$.
Is it true that there exists a sequence $(g_n)_{n\ge 1}$ of positive elements of $G$ such that $\inf \{g_n\}=0$?
Comment: Your constraints being that no $g_n$ is allowed to be 0?
Comment: You're right :)
Comment: The condition you give i believe forces isomorphism with the rationals.
Answer: Let $G\subseteq{^{\omega_1}\Bbb Z}$ be the set of $\omega_1$-sequences $\langle x_\xi:\xi<\omega_1\rangle$ of integers such that $\{\xi<\omega_1:x_\xi\ne 0\}$ is finite; the operation is coordinatewise addition. $G$ is linearly ordered by the lexicographic order.
Let $\left\langle x^{(n)}:n\in\Bbb N\right\rangle$ be a sequence of positive elements of $G$. For $n\in\Bbb N$ let $$S_n=\left\{\xi<\omega_1:x_\xi^{(n)}\ne 0\right\}\;,$$
and let $S=\bigcup_{n\in\Bbb N}S_n$. Then $S$ is countable, so there is $\alpha<\omega_1$ that is greater than any element of $S$. Define $x\in G$ by
$$x_\xi=\begin{cases}
1,&\text{if }\xi=\alpha\\
0,&\text{otherwise}\;;
\end{cases}$$
then $0_G<x<x^{(n)}$ for each $n\in\Bbb N$, so $\inf\limits_{n\in\Bbb N}x^{(n)}>0_G$.


What are the pros and cons of using S3 as a data access server?

Question: I need to manage some configuration files. The files can be stored on AWS S3 and retrieved via the URL. The alternative is to use an application server and store the JSON content to a database and exposing an API to retrieve the data.
What are the pros and cons of each approach?
Comment: You may want to rework your post into how to use S3 as a configuration management system.  As it is worded, I think we will end up with a debate about configuration management - which would be off topic.
Answer: This is a pretty open-ended question, and as jeffatrackaid stated in his note above, this could just end up turning into a debate.  But having said that, here are my two cents as I see it, having managed a decent sized environment spanning multiple AWS regions for the past couple years.
If all you need is to host static content then S3 is by far the easiest way to go.  You just create a bucket, enable web access, upload your files, and you're done.  If you're expecting a lot of traffic you can even leverage Amazon's CloudFront CDN very easily.  The only potential downside, which may not really matter, is that the domain name will be in the format of (bucketname).(region).amazonaws.com.  If you're only using HTTP then you could always set up a CNAME to point to that so you can use your own domain.  If you want to use HTTPS then you'd either have to stick with the amazonaws.com DNS name, or live with SSL mismatch errors if you want to use your own domain name (or use CloudFront and pay a small fortune to support a custom SSL cert on it).
The biggest advantages of setting up an EC2 instance to serve up your content would be if the content was dynamic in nature and/or if you wanted to use a custom SSL certificate (for a lot less than the cost of using one in CloudFront).
The biggest downside to spinning up your own EC2 instance(s) is that you need to be aware that EC2 is designed in such a way that you need to prepare for the eventuality that your server might die, need to be rebooted, etc.  So you'll want to keep your entire server configuration backed up somehow (possibly by just building an AMI, or Amazon Machine Image).
When you have an EC2 instance that is running it is running on a physical server.  Unlike environments like VMWare it can't be migrated to another physical server while it's running. So if there is a hardware failure, Amazon decides to upgrade or retire the hardware your server is running on, etc. then they will schedule a reboot of the server to move it to new hardware.


jQuery handle any user action

Question: I'm trying to implement logic of automatic redirect to homepage after some amount of time without user activity.
So now I simply creating timeout instance and listening for pack of events on document (swipe tap scroll keypress etc...), but this approach do not works propertly.
UPD: this must work on tablet device.
Answer: Please try this to act for any user action
<code>function actTimer() {
    var time;
    const idleTime = 7200;

    window.onmousemove = resetTimer;
    window.onscroll = resetTimer;

    function resetTimer() {
        clearTimeout(time);
        time = setTimeout(redirect, idleTime);
    }
}

actTimer();
</code>
Comment: While helpful, looks like you missed the relevant part of the question: *without user activity*
Comment: ok. I just realized question again and updated my answer. please try that for user activity.
Comment: I think you could just apply any user event to window and redirect with setTimeout function.

jQuery handle any user action


Why do I still get errors using a switch statement with strings in Java SE7 on Lion?

Question: I am running Mac OSX lion and have a Java project in netbeans where I would like to use string switch statements. I downloaded and installed the OpenJDK7 and I think I have configured the project to use the Java 1.7 properly.
In the Project Properties I have set JDK 7 to the platform:

It is showing up as JDK 1.7 in the Libraries section in the Projects Window.

However, I still get a compilation error saying that switch with strings is not supported in 1.6

Am I missing a step here?
Answer: To fix this, I followed the very comprehensive tutorial from the netbeans website found here:
http://netbeans.org/kb/docs/java/javase-jdk7.html
Specifically I had forgotten to set the Sources/Binary Format to JDK 7. You can do this in the bottom right of the Sources section of the Project Properties window.
Answer: If it's anything like Eclipse, the string case is a language feature, not a library feature.
 Eclipse uses its own internal compiler by default and I suspect NetBeans is similar.
So you have to ensure you're using a JDK7 compiler. From a cursory search, the project settings should allow you to set an external compiler.
Answer: Are you using 7.0.1 or greater?

NetBeans 7.0.1 provide a hint if you have a chained if-else statement to take advantage of the JDK7 features. Have you downloaded it yet ? Check out screencast #35 highlighting Project Coin features in NetBeans. NetBeans 7.0.1 provide complete tooling around JDK7 and GlassFish 3.1.1 allow you to leverage JDK7 features in your Java EE 6 applications.

http://blogs.oracle.com/arungupta/entry/totd_168_string_switch_statement
Answer: Here are some steps:

Select the project you want to change source settings for.
Got to File > Project Properties...
Select the Sources Category.
Change the Source/Binary Format dropdown to whatever format you want to use.

Viola!


How do I get the ID of a particular class using jQuery?

Question: I have some div elements having class name hover, these div elements have parent divs having class name hoverparent but the id's of these parent elements are different.
Is it possible to get the ID of respective .hoverparent element while hovering on my .hover div elements?
I tried to get this by:
$('.hoverparent').attr('id')

But it gives the same first parent id every time.
Structure is like:

ABC

DEF

Answer: You need to use the parent or closest functions to traverse up the DOM tree to find the "parent" element you are looking for:
$(".hover").hover(function() {
    var $parent = $(this).closest(".hoverparent");
    alert($parent.attr("id"));
});

The difference between parent and closest is that the first will only work if the .hoverparent element is the immediate parent of the .hover element; closest will  search upwards through all ancestors to find it.
Answer: try $(this).parent().attr('id') , in your hover callback.
Answer: $('.hover').mouseover(function() {
    $(this).parent().attr('id');
});

Answer: don't call your class hover. this should work
$(".hover").hover(
  function () {
   var id =  $(this).parent().attr('id');
  });

Answer: Add each loop like this :
$(".hoverparent").each(function(){
    var id=$(this).attr("id");
    alert(id);
 });

Answer: Use the parent method in the handler for the hover event:
$('.hover').hover(function(evt){
    var par = $(this).parent().attr('id');
    //Now do with ID what you need
},
function(evt){
    //presumably you don't need anything for mouseout
});

Answer: You can try the parent() method.
Like this:
$('a').click(function(){
  var parentId = $(this).parent('div.hoverparent').attr('id');
});

Answer: $(".hover").hover(function(){

console.log($(this).closest(".hoverparent").attr("id"));
});

here is the fiddle http://jsfiddle.net/9dJJ9/1/show/
Answer: Try the following:
$('.hover').hover(function() {
    var parentID = $(this).parent().attr('id');    alert(parentID);
});


Tricks and techniques for memorising songs

Question: I've been googling and, unfortunately, coming up short in search of techniques, methods, systems or just simple tricks for how to memorise songs. I'm currently on a writing spree (I play the guitar and sing over it) and have found that it can be hard to keep everything in order in my head.
So what I'm looking for is any and all tips on how to learn multiple songs, but also how you can efficiently go about learning each of them.
Answer: It will be beneficial to learn some music theory. In that way you'll be able to identify repeating patterns (like the II-V-I chord progression). It is easier to memorize larger chunks, so learning how to identify patterns by e.g. chord function should make it easier.
Answer: Someone asked about a good way to remember song lyrics in this thread :
Good way to remember lyrics when covering songs?
I shan't repeat everything written there ..  if you're playing an instrumental some of the techniques may still help!
I've found that just listening to a song a lot so it's settled in your head works very well. Also there's a kind of quantum jump after listening to a song off and on for a week or so.. maybe it's subjective but for me after several days it kind of sits more deeply in the mind and I can get to grips with it more easily.
The other option is to have some cues written on a card, maybe just the structure of the song etc.
That brings me to another point which is to try and visualise the "landscape" of the song - eg is it verse chorus verse chorus wird bit chorus (repeat to fade haha) .. or something more unusual ?
hope this helps.
Answer: My cello teacher suggests this method for memorizing sheet music:
1) memorize the music in your mind, as sound
2) memorize the music as written on the page
3) memorize the physical motions (in my case, bowing and fingerings)
4) merge the three memorizations.
This may not apply directly to lyrics, but it's worth a shot.
Answer: What I do is:

Compose the song
Play it some times, so to be able to play it without much thinking
write it down (as tab/notes whatever) (this helps me if I forget something after some time)
Play it again and again on a daily basis.

I think the last part is the most useful of all. You just have to play the song(s) over and over and over to remember them. This will take some time, but it will work.
If you have a lot of songs and you get them mixed by mistake when you play, start off by writing them down and then for a few days just play 3-4 of them. Then for some days play some other songs etc.
Also, it might help to remember a pattern of the song. Like a small drawing that your fretting hand is doing while playing the song. This has helped me memorize songs as well
Answer: I like to write down my music in tab notation software such like Guitar Pro or Tuxguitar. Over time the collection of your own stuff will grow, and if you can browse through your songs simply by playing them back, it's a pretty good solution for me.
Comment: I agree, having a playable catalogue is convenient. I usually just record a play through of the song either with the webcam or just with sound and keep the recording with the lyrics.
Answer: I've found that using a different notated representation can help. In particular, sheet music often makes it hard to see the wood for the trees; the amount of detail can obscure larger patterns (repeated or trivially different phrases, elements of form, etc.) in lyrics, melody and harmony.
The act of actually creating one or more "song maps" at coarser levels of detail helps me to notice these patterns if I haven't already. Then using them in rehearsal along with the sheet music helps me to remember them afterwards.
I'll see if I can dig up an example of one I've made before and add it later.
Answer: Practice.
Not trying to be snarky, that's really just what needs to happen.
Additionally, I find it helpful to try to dispense with sheet music as soon as possible.  Playing songs as quickly as you can (even ones that are meant to be slow) helps force internalization.  But the main thing is practicing.  There's no substitute for that.


TortoiseSVN reverter a uma versão anterior

Question: Tanho um código e estou usando o controle de versão Tortoise. Iniciei da versão 1 e agora estou na versão 10. Mas percebi que tenho um problema e preciso voltar o meu código para a revisão 6.
Vou nas propriedades e solicito para reverter para tal revisão. Até ai tudo bem.
Mas a partir desse ponto, eu gostaria de utilizar esse ponto do código para continuar a programar. Chamar essa revisão 6 de 11 e continuar a partir dela. Porém quando tento dar um commit recebo uma mensagem de erro, que minha versão do código não está atualiza e eu preciso atualizar ela primeiro (ou seja atualizar para a versão 10). Mas o que eu quero é justamente não atualizar ela, para não utilizar as partes que eu quero descartar.
Como então, enviar o nova versão do código para o servidor?
Obrigado
Answer:
Faça um branch desta versão 6. Dê um nome fácil de identificar;
Faça suas modificações no branch, realize commit;
Se assim desejar, volte para o trunk e faça um merge vindo do seu branch.

Pode ser necessário mais algumas modificações manuais e resoluções de conflitos.
Comment: @AntonioRafaeldaSilvaFilho Sim, isso acontece porque o SVN trabalha de maneira incremental. Apenas revertendo uma revisão cria-se um problema de consistência entre os arquivos. Isto ocorre porque o SVN não guarda os arquivos inteiros, e sim porções modificadas que são usadas para remontar o arquivo no momento em que você realiza um Checkout ou um Update.
Comment: Para concluir. Se eu usar a opção "revert to this revision" quando tempo para retornar para uma revisão mais antiga, ele não permite que eu faça o "commit". Para funcionar eu preciso selecionar todas as revisões que quero descartar simultaneamente, e marcar um "revert changes from these revisions". Ai sim eu consigo dar um novo "commit" baseado em uma revisão antiga.


Policyd-spf with Postfix returns 550 spf fail - not authorized

Question: This has me rather confused. I've checked my dns, postfix configurations etc...and it all seems fine. And, it works. I can send to gmail etc... and my spf, dkim and dmarc records all pass.
The issue is this:
smtpd_recipient_restrictions = permit_sasl_authenticated, permit_mynetworks, permit_auth_destination,
reject_unauth_destination, check_policy_service unix:private/policyd-spf

works fine. Because policyd-spf doesn't check any emails from my domain. But let's say I want it to check all emails so I set it up as:
smtpd_recipient_restrictions = reject_unauth_destination, check_policy_service unix:private/policyd-spf

that's when I get the spf fail - not authorized issue.
But...if I set it up as:
smtpd_recipient_restrictions = reject_unauth_destination

Postfix has no problems sending emails from my domain and sending to gmail etc...works as
expected.
I read through https://www.rfc-editor.org/rfc/rfc7208.html trying to figure it out, and thought maybe it was the helo as when I send using outlook the helo defaults to my account name. So in /etc/postfix-policyd-spf-python/policyd-spf.conf I added HELO_reject = No_Check
as per https://manpages.debian.org/testing/postfix-policyd-spf-python/policyd-spf.conf.5.en.html
And that didn't fix it. My mx record is:
@               IN  MX        10      mail.example.com.

My spf record is:
@                IN        TXT   ( "v=spf1 ip4:255.255.255.255 -all" )

And in postfix main.cf I have:
smtpd_banner = $mydomain ESMTP (Ubuntu)
mydomain = example.com
myhostname = mail.example.com
myorigin = $mydomain

because the machinename is just example
Maybe I'm just missing the obvious here?
Here's what the log says:
policyd-spf[2599481]: Config: {'debugLevel': 5, 'HELO_reject': 'No_Check', 'Mail_From_reject': 'Fail', 'PermError_reject': 'False', 'TempError_Defer': 'False', 'skip_addresses': '127.0>
policyd-spf[2599481]: Cached data for this instance: []
policyd-spf[2599481]: skip_addresses enabled.
policyd-spf[2599481]: _get_resultcodes: scope: mfrom, Reject_Not_Pass_Domains: None, helo_policy: No_Check, mfrom_policy: Fail
policyd-spf[2599481]: Scope mfrom unused results: ['Pass', 'None', 'Neutral', 'Softfail', 'Temperror', 'Permerror']
policyd-spf[2599481]: mfrom policy true results: actions: {'defer': [], 'reject': ['Fail'], 'prepend': ['Pass', 'None', 'Neutral', 'Softfail', 'Temperror', 'Permerror']} local {'local_>
policyd-spf[2599481]: spfcheck: pyspf result: "['Fail', 'SPF fail - not authorized', 'mailfrom']"
policyd-spf[2599481]: Fail; identity=mailfrom; client-ip=10.0.0.1; helo=accountname; firstname.lastname@example.com; receiver=<UNKNOWN>
policyd-spf[2599481]: Action: None: Text: None Reject action: 550 5.7.23

Is it rejecting it because my ip differs from that of the server? Which would make sense in a way. But if that is the case then is it even possible to check the spf record for mail from your domain when one of your users sends an email? Because if(as I'm sure almost everyone does) connects to the mail server from their home ip, which will obviously be a different one then the mail server has, the spf check looks up the domain, gets the ip of the authorized servers, and then compares those to your ip, which fails?
A weird edge case I'm sure.
Answer: As you can see from the logs, your mail is seen by policyd as
originating from private IP address 10.0.0.1.
Obviously, this address fails the SPF check for domain example.com (or
whatever the real domain is).
This is as expected.
What is the point of SPF? On your server, you use it to check
authorisation of incoming mail. The client IP must be authorised to
send mail for the envelope sender domain.
It does not make sense to check SPF for outgoing mail. Mail submitted
on your server usually originates from a local or private IP address,
which would never pass the SPF check for your domain.


Metropolis sampling with different proposals

Question: I implemented a metroplis sampler for a 1D gaussian mixture, the target distribution looks like this:

I use a 1D normal distribution as propsal, that is each candidate is sampled from a normal distribution centered around the last accepted sample with a certain standard deviation.
If I use a small variance for the proposal distribution my samples are distributed according to the target distribution although it takes a significant number of samples to achieve a good coverage.
If I increase the variance of the propsal distribution my acceptance ratio rapidly drops which was expected, but also my 10^6 samples are not distributed according to the target distribution. Especially the difference between the number of samples generated for each mode of the distribution vanishes:

I could see why this happens in the case for a proposal distribution with small variance but I don't really understand the behaviour of the sampler in the case for $\sigma = 10$ or $100$.
Could anyone explain this behaviour to me?
for i=1:n
while 1>0
    candidate = normrnd(x_curr,sd_prop);
    p_candidate =  eval_mixture_pdf(candidate);
    if p_candidate > p_curr || rand() < (p_candidate / p_curr)
        samples(i) = candidate;
        x_curr = candidate;
        p_curr = p_candidate;
        break;
    end
end
end

Comment: In both cases, the convergence is slower, which means that 10⁶ iterations is presumably not sufficient to reach it.
Comment: I tried 10^8 iterations with $\sigma = 10$ and it doesn't chance anything (I can not attach a third image, sorry). Of course this does not proof that it's not due to the convergence but it definitely feels more like systematic bias ...
Comment: There is no mistake in your code if this is the MC core and there is no reason for "systematic bias" when running it...
Comment: @Maximal Have you tried overlaying the true density on the plots. In my experience, sometimes aspect ratios and perspectives play with our eyes.
Answer: I tried to replicate your results and here is what happened. I think I guessed the mixture distribution almost correctly:
$$.3* N(0, 2) + .7*N(10, 2)\,. $$
I implemented the scenarios that you demonstrate. Here are my various settings:

Monte Carlo samples of $N = 10^4$ and $N = 10^6$
Four $\sigma$s: .1, 1, 10, 100
Two starting values: 0 and 10

Here are the results from $N = 10^4$. Black line is the true density. Things are a little crazy here, but I don't see what you see.

Now here is the more stable $N = 10^6$. Again, I don't see what you see, and rather at $\sigma = .1$ things are a little weird, rest are all ok.

So I am not sure why you are seeing a weird behavior. It may be a starting value issue, but I doubt it. Your algorithm looks correct, so there might be a  problem with how you're storing the Markov chain (maybe?). Here is the R code for these plots (that is the only language I know).
set.seed(100)
## Evaluates the mixture density
eval_dense <- function(x)
{
  f_x <- .3*dnorm(x, mean = 0, sd = 2) + .7*dnorm(x, mean = 10, sd = 2)
  return(f_x)
}

# Samples and plots
plot_MC <- function(sd, N = 1e6, start = 0)
{
  out <- numeric(length = N)
  accept <- 0
  out[1] <- start

  for(i in 2:N)
  {
    cand <- rnorm(1, mean = out[i-1], sd = sd)
    # Calculate ratio
    ratio <- eval_dense(cand)/eval_dense(out[i-1])
    if(runif(1) < ratio)
    {
      out[i] <- cand
      accept <- accept+1
    }else{
      out[i] <- out[i-1]
    }
  }

  x <- seq(-10, 20, length = 10000)
  truth <- eval_dense(x)
  plot(x, truth, type = 'l',
       main = paste("N =", N, ", Sigma = ", sd,", Accept = ", accept/N,  ", Start = ", out[1]),
       ylab = "density (red is MCMC)")
  lines(density(out), col = "red")
}

png("mix_mh_4.png", height = 1000, width = 800)
par(mfrow = c(4,2))
plot_MC(sd = .1, start = 0, N = 1e4)
plot_MC(sd = .1, start = 10, N = 1e4)
plot_MC(sd = 1, start = 0, N = 1e4)
plot_MC(sd = 1, start = 10, N = 1e4)
plot_MC(sd = 10, start = 0, N = 1e4)
plot_MC(sd = 10, start = 10, N = 1e4)
plot_MC(sd = 100, start = 0, N = 1e4)
plot_MC(sd = 100, start = 10, N = 1e4)
dev.off()

png("mix_mh_6.png", height = 1000, width = 800)
par(mfrow = c(4,2))
plot_MC(sd = .1, start = 0)
plot_MC(sd = .1, start = 10)
plot_MC(sd = 1, start = 0)
plot_MC(sd = 1, start = 10)
plot_MC(sd = 10, start = 0)
plot_MC(sd = 10, start = 10)
plot_MC(sd = 100, start = 0)
plot_MC(sd = 100, start = 10)
dev.off()

Comment: hello from 4 years later! what would be a sensible approach to make the similar simulation using Gibbs Sampler? I am trying to sample from mixture of two bivariate normals where I know the mixture distribution similar to your answer above. I am having hard time to find the appropriate conditionals. Thanks!!


Convert object with arrays to array of objects using Ramda or Lodash

Question: Example input:
const obj = {
  paths: ['path1', 'path2'],
  thumbnails: ['thumb1', 'thumb2'],
  sizes: [ // may not always be presented
    [100, 200],
    [120, 220],
  ],
};

Expected output:
const result = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
    size: [100, 200],
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
    size: [120, 220],
  },
];

Bonus points for:
const result1 = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
    width: 100,
    height: 200,
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
    width: 120,
    height: 220,
  },
];

// without sizes

const result2 = [
  {
    path: 'path1',
    thumbnail: 'thumb1',
  },
  {
    path: 'path2',
    thumbnail: 'thumb2',
  },
];

How would I achieve this with Ramda or Lodash?
Answer: Updated answer
Here we extract the fields we care about into arrays, turn that into a multidimensional array (number of records by  number of elements in an array), transpose that array, and then zip it back together as an object.
We use the same list of field names for the extraction and for reconstituting an object.  It looks like this:

const inflate = (names) => (obj) =>
  map (zipObj (names)) (transpose (props (names) (obj)))

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}

console .log (inflate (['paths', 'thumbnails', 'sizes']) (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

For your extended version, just run a subsequent map over the results:
const inflate = (names) => (obj) =>
  map (zipObj (names)) (transpose (props (names) (obj)))
    .map (({sizes: [width, height], ...rest}) => ({...rest, width, height}))

A specification-based approach
Ori Drori's answer challenged me to find a specification-based version that lets us declare that paths becomes path and the first element of sizes becomes width.  Here is one rather nasty version of that idea.  I'm out of time to clean it up, but you can see at least the skeleton of an interesting idea in this:

const regroup = (spec, names = uniq (values (spec) .map (x => x.split ('.') [0]))) => (obj) =>
  map (applySpec (map (pipe (split ('.'), path)) (spec))) (map (zipObj (names)) (transpose (props (names) (obj))))

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}
const spec = {path: 'paths', thumbnail: 'thumbnails', width: 'sizes.0', height: 'sizes.1'}

console .log (regroup (spec) (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

Original answer
(I originally misread and thought you wanted something like the Cartesian product of the elements, not the matched indices one.  I'm leaving it here as it does answer what to my mind is a more interesting question.)
TLDR
Below we discuss several  implementations.  A configurable one written in Ramda looks like this:
const inflate = pipe (map (unwind), pipeWith (chain))
// ...
inflate (['paths', 'thumbnails', 'sizes', 'sizes']) (obj)

A powerful, but less flexible vanilla one looks like this:
const inflate = (obj, _, __, field = Object .entries (obj) .find (([k, v]) => Array .isArray (v))) =>
  field ? field [1] .flatMap ((v) => inflate ({...obj, [field [0]]: v})) : obj
// ...
inflate (obj)

Ramda implementation
Ramda has a function dedicated to this: unwind.  It takes a property name and returns an array of values, one for each element of the array at that name.  We can then simply pipe these together with chain, like this:

const inflate = pipeWith (chain) ([
  unwind ('paths'),
  unwind ('thumbnails'),
  unwind ('sizes'),
  unwind ('sizes')
])

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}

console .log (inflate (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

If pipeWith is unfamiliar, this is equivalent to
const inflate = pipe (
  unwind ('paths'),
  chain (unwind ('thumbnails')),
  chain (unwind ('sizes')),
  chain (unwind ('sizes'))
)

where the chain calls are acting here similar to Array.prototype.flatMap.
More abstract Ramda implementation
But this calls out for a further abstraction.  We can make that more declarative by extracting the list of paths we want to expand, so that we can simply call inflate (['paths', 'thumbnails', 'sizes', 'sizes']) (obj).  This is an implementation:

const inflate = pipe (map (unwind), pipeWith (chain))

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}

console .log (inflate (['paths', 'thumbnails', 'sizes', 'sizes']) (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

Powerful, but less flexible vanilla implementation
But perhaps we don't want to specify the fields.  If we just want to supply the object and expand all arrays, including nested ones, then we probably want to write a recursive version.  At this point, Ramda would probably be a distraction.  We can write a simple vanilla JS implementation like this:

const inflate = (obj, _, __, field = Object .entries (obj) .find (([k, v]) => Array .isArray (v))) =>
  field ? field [1] .flatMap ((v) => inflate ({...obj, [field [0]]: v})) : obj

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}

console .log (inflate (obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

This is powerful.  It works with any array properties, even if they're multidimensional.  But it is inflexible.  You cannot choose not to expand certain array properties.  Whether this is good or bad will depend upon your circumstances.
We could use Ramda in the same manner.  Here's a partial conversion to using Ramda functions:
const inflate = (obj) => call (
  (field = pipe (toPairs, find (pipe (last, is(Array)))) (obj), [k, v] = field || []) =>
    field ? chain ((v) => inflate (assoc (k, v, obj))) (field [1]) : obj
)

And we could continue to pull things out until we were totally point-free, but I think we'd slowly be losing readability here, unlike with the earlier Ramda versions, where we ended up with fairly elegant, readable implementations.
Names
None of these versions (in the original or updated answers) does name changes.  We don't try to convert "sizes" to "size" or "paths" to "path".  If you have control over the input format, I would suggest that you simply switch it there.  If not, I would probably do that as a final step.  You can do that using Ramda's applySpec or perhaps using something like renameKeys from Ramda's Cookbook.  While it might be possible to fold this key renaming into the functions above, I would expect it to be less robust than simply doing a second pass.
Comment: Spec-based approach is neat. Also running `Ramda implementation`, `More abstract Ramda implementation` and `Powerful, but less flexible vanilla implementation` didn't produce an intended result. `sizes` property is of type `number` and property names are off
Comment: Right, as I said, I originally misread the question, but kept them here as the answer to a somewhat related question.  The only ones close to your actual requirements are the first two.
Answer: You'll need to pass a mapping of old keys to new keys, use R.props to get the value using the old keys, transpose, and then zip back to an object using the new keys (the values of the mappings object):

const {pipe, props, keys, transpose, map, zipObj, values} = R

const fn = mapping => pipe(
  props(keys(mapping)), // get an array props by keys order
  transpose, // transpose them
  map(zipObj(values(mapping))) // map back to an object with the same order
)

const obj = {paths: ['path1', 'path2'], thumbnails: ['thumb1', 'thumb2'], sizes: [[100, 200], [120, 220]]}

console.log(fn({ paths: 'path', thumbnails: 'thumbnail', sizes: 'size' })(obj))
.as-console-wrapper {max-height: 100% !important; top: 0}

Comment: Nice, I considered doing such a mapping, but chose to go in another direction.  An interesting extension would be using a specification such as `{path: 'paths', thumbnail: 'thumbnails', width: 'sizes.0', height: 'sizes.1'}`,
Comment: Updated my answer to include a version with that sort of specification.
Comment: I like your solution, very clean
Answer: You specifically want to do this using ramada only ?
Coz this can be achieved with vanilla as follows.
for expected output -
obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], size: obj.sizes[i] }))

for bonus output -
obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], width: obj.sizes[i][0], height: obj.sizes[i][1] }))

size array can be empty ie. [] -
obj.paths.map((e, i) => ({ path: obj.paths[i], thumbnail: obj.thumbnails[i], width: obj.sizes[i] !== undefined ? obj.sizes[i][0] : '', height: obj.sizes[i] !== undefined ? obj.sizes[i][1] : ''}))

Comment: thanks! just updated the question, `sizes` property may not be always presented as a whole
Comment: thanks, though vanilla js solution is mostly trivial I'm looking for a ramda way of doing this specifically for the sake of our code base style
Answer: With vanilla Javascript, we can handle with indices easily, but Ramda.js does not have them, so you can use R.forEachObjIndexed to handle your case.
const obj = {
  paths: ['path1', 'path2'],
  thumbnails: ['thumb1', 'thumb2'],
  sizes: [ // may not always be presented
    [100, 200],
    [120, 220],
  ],
};

const result = []
R.forEachObjIndexed((value, index) => {
  const currentData = {
    path: value,
  }
  if(obj.thumbnails && obj.thumbnails[index]) {
    currentData.thumbnail = obj.thumbnails[index]
  }
  if(obj.sizes && obj.sizes[index]) {
    const [width, height] = obj.sizes[index]
    currentData.width = width
    currentData.height = height
  }
  result.push(currentData)
}, obj.paths)

console.log(result)

You can try out with the playground here


Why can distributions be completely defined as probability measures on $\mathbb{R}$?

Question: In my textbook, it states that
"Part of the beauty of distributions comes from the fact that two statisticians, who are in different parts of the world working on completely different problems with completely different probability spaces, may both find the same distribution extremely useful; they can even discuss this distribution together in the common language of probability measures on $\mathbb{R}$, without worrying about whether they have completely different $\Omega$'s."
I am a bit confused by this statement because I don't get how one can have different $\Omega$'s without changing the problem at hand. Is there a trivial way to see why this is true?
Comment: [This section (10.2) from the book by Loeve](https://books.google.com/books?id=_9xWBlvUEuIC&pg=PA172&hl=en#v=onepage&q&f=false) seems relevant.
Answer: It means that there is no difference in observable outcomes whether you flip a coin or roll a die with three heads and three tails - two different $\Omega$'s, same distribution of outcomes.
ETA: For example, while you can construct $X\sim B(1,1/2)$ on a single coin, you can't construct a pair of independent identically distributed $X,Y$ random variables on the same underlying $\Omega$ - you need to expand your underlying $\Omega$ to two coins or one four-sided die. The whole "probability space" shebang is a mathematical machinery to rigorously justify something experienced naturally (for example what it means for observations to be independent). That's why you have theorems showing that there actually exist probability spaces and random variables that have given distributions.
After we hide the probability space, we you no longer speak of convergence a.s. or convergence in probability - only of convergence in distribution. This is useful because in physical reality we don't really have access to the actual source of randomness ($\Omega$) - only to observables/outcomes and their (empirical) distributions.
Comment: Can I ask what you mean by hiding the probability space? Why is it that we only have convergence in distribution?