How do you loop through a web page for content using Python Selenium

Question: I am quite new to using Selenium (Python). I have just scraped some data off a website in exactly the way I wanted to but the code only pulls off the first 10 records. It doesn't proceed to pick up the entire content by looping through the other pages. Would you happen to know why the script fails to open the proceeding pages? Any help would be greatly appreciated. If you find the """This is for navigation to next page""" I think this is the incorrect area.
Code:
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoSuchWindowException
import time
from openpyxl import Workbook
"""This is to collect links that associate with all the profiles present in Allen Overy website"""
def get_links(driver, target, upper_datetime_str, lower_datetime_str):
"""This part allows me to filter on date so I'm not having to pull back all the data each time it's run"""
if upper_datetime_str == '' and lower_datetime_str == '':
    time_constrain = 0
else:
    time_constrain = 1
    upper_datetime = time.strptime(upper_datetime_str,'%d/%m/%Y')
    lower_datetime = time.strptime(lower_datetime_str,'%d/%m/%Y')

"""This is to search for news that present in Freshfields website"""
"""Go to page that contains news list"""
driver.get(target)

isbreak = 0
list_links = []
while True:
    try:
        """Get links that associate to news in each page"""
        list_ppl_link =  driver.find_elements_by_xpath('//div[@class = "srch-Title3"]')
        for item in list_ppl_link:
            rel_date = item.find_elements_by_xpath('//div[@class = "srch-Metadata2"]')
            if time_constrain == 0:
                rel_link = item.find_element_by_tag_name('a').get_attribute('href')
                list_links.append(rel_link)
            else:
                input_datetime = time.strptime(rel_date,'%d %B %Y')
                if input_datetime < lower_datetime:
                    isbreak = 1
                    break
                elif input_datetime >=lower_datetime and input_datetime <= upper_datetime:
                    rel_link = item.find_element_by_tag_name('a').get_attribute('href')
                    list_links.append(rel_link)

        """This is for navigation to next page"""
        next_b = driver.find_element_by_xpath('//div[@class="srch-Page srch-Page-bg"]')
        if next_b.get_attribute('class') == 'srch-Page-img':
            next_b.click()
        else:
            break

        if isbreak == 1:
            break

    except KeyboardInterrupt:
        break
    except NoSuchWindowException:
        break
    except:
        raise

return list_links

def get_news_content(driver, link):
    driver.get(link)
try:
    rels_date = driver.find_element_by_class_name('ao-rteElement-H4').text
except NoSuchElementException:
    rels_date = ''

try:
    headline = driver.find_element_by_class_name('ao-rteElement-H1').text
except:
    headline = ''

try:
    content1 = driver.find_element_by_class_name('ao-rteElement-introText').text
except NoSuchElementException:
    content1 = ''
try:
    content2  = driver.find_element_by_id('ctl00_PlaceHolderMain_main__ControlWrapper_ExtendedRichHtmlField').text
except NoSuchElementException:
    content2 = ''
content = '\n'.join([content1, content2]).strip()

return {'news_date':rels_date ,\
        'news_content':content, 'news_headline':headline}

def extract_data(adict):
return [adict.get('news_date', ''),
        adict.get('news_headline', ''),
        adict.get('news_content', '')]

===============================================================================================================
if name == "main":
    """Highlight the file variables such as file name and headers for columns with a date stamp of==="""
    printout = time.strftime('%y%m%d_%H%M%S', time.localtime()) + '_allenovery_news.xlsx'
    header = ['Firm Name','Date', 'Headline Title', 'News Content']
wb = Workbook()
ws = wb.active
ws.append(header)
log = open('test.txt', 'w')

"""Identify target link where the data is stored"""
target = 'http://www.allenovery.com/search/Pages/results.aspx?k=*&v1=-write&s=NewsAndDeals&r=aolanguage%3d%22AQdFbmdsaXNoCmFvbGFuZ3VhZ2UBAV4BJA%3d%3d%22'

"""Engage Chrome Driver"""
chromeOptions = webdriver.ChromeOptions()
prefs = {"profile.managed_default_content_settings.images":2}
chromeOptions.add_experimental_option("prefs",prefs)
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()

"""Time format : dd/mm/yyyy"""
"""Select your timeframe below should you wish. Otherwise leave fields blank '' """
upper_datetime_str = ''
lower_datetime_str = ''

print('Collecting news links')
list_ppls = get_links(driver, target, upper_datetime_str, lower_datetime_str)
driver.quit()

"""Engage Chrome Driver"""
driver = webdriver.Chrome(chrome_options=chromeOptions)
driver.set_page_load_timeout = 120
driver.maximize_window()

total_link = len(list_ppls)
idx = 0
while idx < total_link:
    try:
        print(idx + 1, 'in', total_link, list_ppls[idx])

        """Append client name to data"""
        ws.append(['Allen and Overy'] + extract_data(get_news_content(driver, list_ppls[idx])))
        idx += 1
        if not(idx%100):
            wb.save(printout)
            driver.quit()
            time.sleep(10)
            driver = webdriver.Chrome(chrome_options=chromeOptions)
            driver.set_page_load_timeout = 120
            driver.maximize_window()

    except KeyboardInterrupt:
        break
    except NoSuchWindowException:
        break
    except:
        driver.quit()
        time.sleep(10)
        driver = webdriver.Chrome(chrome_options=chromeOptions)
        driver.set_page_load_timeout = 120
        driver.maximize_window()
        continue

wb.save(printout)
log.close()
driver.quit()

Comment: Could you be more succinct? Just share exact lines of code which are the cause of your problem and provide short issue description, exception log (if you got any)
Comment: Target = 'http://www.allenovery.com/search/Pages/results.aspx?k=*&v1=-write&s=NewsAndDeals&r=aolanguage%3d%22AQdFbmdsaXNoCmFvbGFuZ3VhZ2UBAV4BJA%3d%3d%22'
My coding pulls off the data for that link but just the first 10 records on page 1. The coding that is stopping the programme from looping through is;
"""This is for navigation to next page"""
            next_b = driver.find_element_by_xpath('//div[@class="srch-Page srch-Page-bg"]')
            if next_b.get_attribute('class') == 'srch-Page-img':
                next_b.click()
            else:
                break
Answer: You're trying to handle wrong element (driver.find_element_by_xpath('//div[@class="srch-Page srch-Page-bg"]') is not what you actually need). Try to implement below code:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

try:
    time.sleep(1)
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "SRP_NextImg"))).click()
except TimeOutException:
    break

This should allow you to get next page until "Next" button (>) is available
Comment: Thanks for getting back to me. I incorporated your suggestion into the script and got the following error "Element is not clickable". Could I share the script with you?
Comment: I got the same error. It may be a glitch in another area of the script. I am so close to making it work but just can't seem to get this last bit right.
Comment: Show the complete exception log
Comment: It doesn't seem to be allowing me to take a screen shot of my anaconda prompt window. I don't have any other logs
Comment: I mean `Element is not clickable` full log
Comment: It reads like this; Message: unknown error: Element is not clickable at point (750, 777). Other element would receive the click <div id="cookiewarning" style="display": block; height
Comment: Updated. check again
Comment: selenium.common.exceptions.WebDriverException: Message: unknown error: Element is not clickable at point (750, 777). Other element would receive the click: ...
Comment: Are there any forums where I could share the whole script as it would be probably easy for someone to pinpoint the issue?
Comment: ok.... seem that developer has good sense of humor :)) try ti use just `time.sleep(1)` as on updated answer
Comment: Here on `SteckOverflow` you might ask for a solution of particular issue. I don't know where you can post the whole script for someone to analyze it...
Comment: Still no joy at all. It may be one to park for today :-(
Comment: Thanks for all your help anyway. Much appreciated


expand the menu for web help generated by madcap

Question: I know this might be a long shot but i have been Google and reading the javascript code generated for days now without any result.
I'm looking to have the menu expand for the web help generated by madcap when you going directly to a specific subject in the help by a link. This seems to work fine if you use the tool provided by madcap but if you look at the page in a web browser the menu don't expand.
The javascript code is over 10 000  lines of code so skipped to post it.
Answer: I couldn't find a answer how to change the javascript to get this to work but i did find a option in the generation to solve this.
"You can customize your output so that users can always see where the current topic belongs in the table of contents (TOC), even if they did not access the topic via the TOC. This can be done by selecting the "Automatically Synchronize TOC" option in the Skin Editor. When users navigate from topic to topic in the output, the TOC automatically changes accordingly, highlighting the topic that is open."


How do NPCs heal our Pokémon?

Question: In various Pokémon games, there are scenarios where we come out of a big fight (usually a boss fight) and an NPC heals our Pokémon for us. I know that Pokémon are healed in Pokémon Centers using special machinery, but is there any in-universe explanation to how these NPC can heal them at a seconds notice without any help?
Answer: This is never addressed in games. You can imagine it being a vast supply of Max Revives, Max Restores, and Max Ethers if you want.
Comment: I was actually playing Pokémon Sun, and there the NPC (Lille) usually remarks that she carries a ton of above said items. So I imagine this is probably correct.
Comment: @IsmailHafeez If you have found an ingame source, feel free to post your own answer as well.
Comment: This is even more confusing in *Sword* and *Shield*, because IIRC they also heal all of the pokemon in your boxes... which as of *Sword/Shield*, you can access from anywhere at any time (except in battle). So just how many items are we expected to believe they used, exactly?
Comment: Something pointing towards this answer is that the usual sound effect when an NPC heals your Pokémon is that of an item (such as a Full Restore) being used, rather than the sound effect you get in a Pokémon Centre. Some NPCs do mention the methods they use, though - a channeler in Lavender Tower has enchanted the floor, the lady in Silph Co lets you rest in beds, etc.

How do NPCs heal our Pokémon?


Air vent on the wall big gap

Question:
Hi I have a huge gap between my air vent and to my wall and I can't screw jt into the wall because there is brick there. Is there a way I can seal it and paint it... thanks
Comment: I take it this is an outside wall you're talking about here?  Can you gain access to the ductwork from below?
Comment: Haven't looked at it and the vent is inside the kitchen and the outside wall is behind it
Answer: Get a 1x2 or just some molding from your home store and make a frame and attach it to the wall. Then slide the vent up against it and caulk it a paintable caulk. Then paint it to match the wall or the trim, whatever floats your boat. Good luck.
Comment: Thanks I'll give it a try

Air vent on the wall big gap


My ASP .NET MVC 3 project starts in Windows Phone 7 emulator?

Question: Here's a screenshot of how it looks before I press the green "debug" button.

However, the project still attempts to start using the Windows Phone Emulator. It's really bad.
Is this a problem you've encountered before? How can I solve it?
Edit 1 In my project file, I see something strange:
<code>  <PropertyGroup>
    ...
    <OutputType>Library</OutputType>
    ...
  </PropertyGroup>
</code>
Is it supposed to be like that for that given project?
Edit 2 It should probably be noted that one of the projects in the solution is in fact a Windows Phone 7 application.
Comment: Try right clicking your MVC3 **project** and open a new debug instance from there. What happens?
Comment: That works as expected, but with no debugging. Breakpoints don't work at all, and there's no debug information attached.
Comment: Wow, I knew I should never install the WP SDK :-)
Comment: Ok, now try this. Select another project in your solution as the default starting project. Then **reselect** your MVC3 project. Press F5 and see if it's now fixed.
Comment: I noticed something weird in the project maybe. I added an edit to the post.
Answer: I made a workaround. Unloading the Windows Phone 7 project from the solution temporarily as I work on the ASP .NET MVC site seems to work just fine.


json.parse gives Uncaught SyntaxError: Unexpected Token (Django json serialized queryset)

Question: I am experiencing the error Uncaught SyntaxError: Unexpected Token when trying to parse the json data
This is my ajax code (json2.js):
       $.ajax({
            type: 'POST',
            url: '/best_choose/invoice/item_search.json/',
            data: jsonQuery,
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',

            success: function(data){
                    var parsed = JSON.parse(data);
                    //do stuff
             }});

my view:
    json_serializer = serializers.get_serializer('json')()
    serialized_q = json_serializer.serialize(queryset, ensure_ascii=False)

    return HttpResponse(
                serialized_q, mimetype='application/json'
            )

from debug serialized_q is a unicode string containing valid json u'valid_json'
Answer: When you set dataType to json, jQuery parses the data for you. So you don't need to put it through JSON.parse, you can just refer to data as a normal Javascript object.


Neutral and ground in outlet *slightly* hot when either of two other breakers switched on

Question: Our house was built in 1996, and everything that I've encountered electrically in it so far seems to have been done correctly.
Today, I was replacing a worn out 15A 3-prong receptacle.
I used my normal 3-prong plug in outlet tester, and my son watched it over radio coms while I was down in the basement, switching what seemed to be the correct breaker, #12.  My son reported that the lights on the outlet tester turned off.
I came back up and confirmed, and as one last sanity check, I used my non-contact voltage tester to make sure nothing was hot, but it fired on the outlet.  Not just on the hot side either, but also on the neutral and ground ports.
We then went through what felt like a ridiculous comedy of errors over radio as we tried to figure out where this voltage was coming from.
We eventually narrowed it down to breakers #22 and #25.  While #12 would make the 3-prong tester lights turn off, having either #22 or #25 on would cause both neutral and ground on the outlet to have some voltage, but no other breakers in the house would cause voltage.
With all three breakers turned off, I pulled the outlet out of the wall so I could inspect the wiring.  It looked totally fine, with a single strand of white Romex entering the junction box, and nothing leaving, and the outlet connected correctly.
Now that I could see the wiring, my son and I did some more radio-linked testing, while I probed each wire individually.  #12 would produce voltage only on the black wire.  But either #22 or #25 or (both together) would produce voltage on the white and bare/ground wires.
The outlet tester isn't complaining about the outlet, and various appliances have always worked okay using that outlet.
I wasn't quite sure how to test this mysterious voltage with my multimeter (since I'd usually put red in hot and black in neutral to measure 120V AC), but with either #22 or #25 on, I seemed to be measuring a volt or two between neutral/white and bare/ground.
Furthermore, measuring between black/hot and white/neutral showed 119.2V AC whether or not #22 or #25 was on (as long as #12 was on).
Finally, my non-contact voltage probe does not fire when inserted into the neutral or ground ports of other outlets elsewhere in the house, even with all breakers on.
Comment: It sounds like phantom voltage.  If the wires from the three breakers pass close to each other part way, they can induced some voltage(without amps) in the wires.  Sometimes you can get quite high(70 to 90v) readings, but connecting a load(light) they go away.
Comment: But would a no-contact tester really pick this up?

Lots of wires pass close to each other (they are literally touching inside the panel, and come out in what are essentially bundles), but I don't seem to have this issue elsewhere in the house.

Or maybe very long parallel runs are needed for induction to really kick in?  So maybe #12, #22, and #25 share such a long run together?
Comment: The breaker to cut is the large breaker with the 200 on the handle.  The little dance of trying to cut only the individual circuit is a) lots of work and b) fraught with danger. Doing that I  nearly got bit on a panel I 100% rebuilt myself - well 99%, unbeknownst to me the neutral-ground bond was not good, and the neutrals had all floated to 120V.  Now why are you replacing the outlet? sloppy fit or gone dead?
Comment: @Harper-ReinstateMonica  I have heard that main breakers to not do as well as branch breakers to be turned off and on.  I have also had a main breaker(1978 panel) fail to turn on doing this.  I was lucky that the electrician was still here to pull the meter and replace.  Would not turning off all the branch breakers be safer for the main?
Comment: "measuring a volt or two between neutral/white and bare/ground" is not unusual. "would a no-contact tester really pick this up?" yes. MM and NCVs are BS when it comes to what matters which is *potential*. For that you need a(n incandescent) light bulb or real test equipment: if it doesn't vibrate a Wiggy then go nuts. [27 questions linked to/from Electric shock - was I stupid, unlucky, or a combination of both?](https://diy.stackexchange.com/questions/linked/47613?lq=1)
Comment: NCVs more often give you a false positive then they do anything useful, which is the preliminary check of if it's still live, *not* of if it's dead. For that you need a solenoid voltage tester that gives you physical feedback that not only will this kill you, it will hurt the whole time you're dying. If you're amateur enough to have a NCV scare you... then you should be.
Comment: It was a cheap outlet (probably one of the 50 cent ones) and after 27 years of heavy use (main hallway outlet for weekly vacuum plugging), the contacts inside weren't making good contact anymore, and plugs had a very loose fit (they would fall out easily).  You had to jiggle a plug for the appliance to turn on.
Comment: @Mazura Can you explain what you mean by "potential"? You seem to be using the word to mean something like "voltage with a low enough impedance to drive a load," but I've never seen it used to mean anything other than "voltage relative to some irrelevant common point."
Comment: I meant *current*. Voltage does nothing w/o some amperage behind it, except trigger false positives on NCVs and MMs. Not sure why they hammered home *potential* so much considering it just means voltage anyway. Maybe they meant potential potential; the ability to do *work*, and w/o either an insanely high voltage at low amps, or a moderate amount of amps w/ w/e voltage, it does nothing. - The only thing voltage tells me is how close not to touch it; spark gap is 1 kV per mm, so w/e. That being said, I don't do 440v....
Answer: Summarizing the helpful comments from Mazura, crip659, and others:
Both non-contact voltage testers and digital multimeters can sometimes read phantom voltages in wires that don't actually have dangerous voltages in them.  This can be caused via induction between the wire in question and other hot wires that run close to the wire for long stretches (for example, if two wires from different circuits travel together in the same conduit).
The suggested "real test equipment" is a Wiggy---which is the genericized name taken from the original inventor/manufacturer---also known as a solenoid voltage detector.
These are battery-free devices that move a magnet with a coil based on the amount of voltage present, resulting in a bar moving on a physical meter.  For AC voltage, they also vibrate and make a noise.  By holding the device while testing, you can actually feel the presence of voltage, without even looking at the device.  Because substantial current must flow through the device for this to happen, they won't react to phantom voltages, which can't drive much current.
Doing additional research online, it seems like the best solenoid voltage detectors available are the Knopp K-60 and the Ideal Vol-Test or Vol-Con, which are both still being manufactured, and apparently still made in the USA.
These are relatively simple and primitive-looking devices, but apparently, many professional electricians still use them on a daily basis for "go/no-go" testing before handling AC wires.


How to concat 2 values inside a loop thymeleaf

Question: I have some problems concatenating 2 values in thymeleaf
I do the following:

...
...
...

This is how the page looks like
As you can see this is not dynamic because if p.preferencias size is bigger than 2 this will be a problem and the same if is less than 2
this what i tried :

...
...
...

This is what i got:
And got this
As you can see the second value move to email :(  then i thought in concat the values and try this :

...
...
...

And this is the result:
Result 3
I dont know how to concat the values and keep those in one cell
How can i execute the loop to get all the values inside p.preferencias variable ?
EDIT:
post wrong image in result 3 now is the correct image
Answer: Finally solve the problem the tag td stay open thats why the secon value in the each iteration fill the next cell solve it using a span tag and iterate inside

    ...

         arcd.index}? ', ':'')">

    ...

Output


Ubuntu 17.10 GDM Auto-Login not working

Question: I have selected the setting 'Automatic Login' from within the default Gnome 3 Ubuntu 17.10 control panel app, but it keeps resetting to 'off' after every restart and does not allow me to automatically login.
Any ideas?
Comment: The problem is the captial letter in the word True in the gdm3 custom.conf
Comment: "AutomaticLoginEnable=true" instead of "AutomaticLoginEnable=True"
Comment: Are you using nvidia drivers?
Comment: If not using nvidia drivers (on a desktop machine, laptops should be fine) post the contents of `/etc/gdm3/custom.conf` also note that the setting in Settings > Details > Users acts like a cover, i.e. whatever you uncover is enabled, what you cover up is disabled.
Comment: I'm using it, this is my [`custom.conf`](https://gist.github.com/elect86/eaae9fbf73fce4ac0f28256be8750085)
Comment: I have tried using nvidia drivers but I am now using the open source drivers.
Comment: I have not touched the custom.conf
Comment: Custom.conf can be found here: [custom.conf](https://pastebin.com/3ruPW6zK)
Comment: Currently using the nouveau drivers
Comment: Can u pls finally tell me which answer solved your problem?  Because I have the same things.  Thanks.
Answer: I had to force the loging screen to use xorg and not wayland (not yet supported by nvidia drivers).
Edit as root the file /etc/gdm3/custom.conf.
sudo nano /etc/gdm3/custom.conf

Change the line
#WaylandEnable=false

to
WaylandEnable=false

Comment: Thanks a lot, this works for me in combination with:  AutomaticLoginEnable = true
AutomaticLogin =
Answer: I think i've found the problem, try to edit /etc/gdm3/custom.conf
and write AutomaticLoginEnable=true
instead of AutomaticLoginEnable=True in my case
(full lowercase for the word "true")
or uncomment this line if it is...
Comment: Unfortunately, even for me this solution worked, @Pöl Halbert... I uncommented, because it was `true`. But, switching in Details > Users panel, it turns `True`and `False`. Even changing `True`to `true`, autologin didn't work.
Comment: I don't think it's necessary because my `/etc/gdm3/custom.conf`is already "AutomaticLoginEnable=true" but it was commented. I just uncommented it.
Comment: In mine it was written AutomaticLoginEnable=True and I had never edited it manually.... Maybe it cal help some people if not you ;)
Answer: For those who are desperate because it continues failing and failing despite using x11 and writing the proper configuration, are you using a docking station?
I figured that under X11, the docking station forces a login: it doesn't load the gdm automatic login settings. Surely a bug.
A workaround is to use the following config instead at /etc/gdm/custom.conf below the [daemon] section:
TimedLoginEnable=true
TimedLogin=<your_username>
TimedLoginDelay=0

It's not as handy as using Automatic Login but at least it works.
You can indeed keep the AutomaticLogin configs if that's already there, those will be loaded and used whenever the docking station is not plugged.
It's interesting to notice that Wayland behaves differently: AutomaticLogin does work with Wayland + docking station, but not with X11.
If you choose Wayland, beware that Wayland does not support the "share screen" button in many common video-call softwares.
EDIT: add some precisions following commentary.
Answer: Same issue. I've originally changed the "/etc/gdm3/custom.conf" and simply enabled the "AutomaticLoginEnable=True". This was the whole issue: I didn't notice that "True" has to be lowercase.
EDIT:
I was wrong. My autologin works because I'm NOT using the gnome-xorg (the default option for ubuntu) but the gnome classic session.
I can't manage to get the gnome-xorg session to work properly unless I setup a timedlogin which is a little unpleasant.
EDIT 2:
Ok, I finally got enough of this issue, since it's getting ignored. To solve my issue, since I don't care the least about gdm but I still want to use chrome, I've installed lightdm and changed the autologin in the user settings.
In other words:
sudo apt install lightdm

followed by the usual change in the user settings for the autologin.
Answer: I can confirm that it's a bug in Settings app. When changing the 'Automatic Login' flag under Details->Users it writes True/False values for AutomaticLoginEnable in "/etc/gdm3/custom.conf".
After manually writing the value AutomaticLoginEnable=true the auto-login works.
Comment: This doesn't work for me.
The AutomaticLoginEnable=true was remarked out in the file, but activating it, didn't change anything.
Comment: This solution didn't work for me, @Julius and @SimonRigét, not regarding if it's `true`or `True`, the result is the same: nothing works. These two statements are present in `/etc/gdm3/custom.conf`: `AutomaticLoginEnable` and `AutomaticLogin`
Comment: @SimonRigét - as you already wrote in your answer, both variables are required for auto-login:  `AutomaticLoginEnable` and `AutomaticLogin` with username. The Settings app writes both variables, but the bug is that it writes True/False with capital letters.
Comment: And 2 years later this is still an issue...
Answer: I had to set two variables, to make it work:
$sudo gedit /etc/gdm3/custom.conf

And insert the lines:
AutomaticLoginEnable = true
AutomaticLogin = <my user name>

The settings app is buggy, to an extend where it's getting useless as of 11.2017. Hopefuly that will change :)
Answer: I just had problems with GDM 3.28.3 auto login with 18.04 minimal and gnome-core only. GUI froze completely on boot with the error A start job is running for Hold until boot process finishes up and after long research I accidentally found a solution by disabling the boot splash screen:
# disable splash screen on boot
sudo sed -i 's/splash quiet//g' /etc/default/grub
sudo update-grub

Note: To enable the splash again: sudo gedit /etc/default/grub and make sure splash quiet is again within the quotation marks of GRUB_CMDLINE_LINUX_DEFAULT e.g. GRUB_CMDLINE_LINUX_DEFAULT="splash quiet". Apply the new settings with sudo update-grub.
I hope this saves other people's time. If anyone has an idea why this worked for me please let me know.

Ubuntu 17.10 GDM Auto-Login not working


how to resize elements in interface builder?

Question: I was working my project with XCOde and interface builder, but the little dots around the elements  in interface builder are not showing up anymore. I am not able to resize anything. I created a second xib file and they show up on that one, how is that possible ? I feel that i'm stuck now and that i have to create a new project... or is it a settings that "hides" the bounding boxes of all elements in a xib ?
Thank you
Answer: I just recreated the project, it seems that it was a damaged XIB file .  Next time i'll do backups of my whole project every now and then ( i guess i should have used a SVN )


Do I get to keep all of my collectibles from Mass Effect 2?

Question: Last night while working finishing up ME2, I made a trip to my cabin to swap out an armor mod, and it got me thinking: do all of the various collectibles in my cabin in ME2 make a reappearance in ME3?  By collectibles, I mean my space hamster, my fish, my prothean relic, my N7 helmet, etc.
Answer: The ship models and hamster are all there, but you have to find them strewn about the ship.
Someone, Kelly Chambers I think, takes care of your fish for you.  If you find her on the Citadel she gives them all back.  Be careful as you have no one to feed them for you.  You have the options of purchasing new ones if you want.
As for the orb,the helmet, and any other collectibles, they haven't shown up for me yet.
Answer: The helmet you find in me2 when you're doing the Normandy quest. It's on the right side of the cliff's edge, when you're running/walking up to the cliff where the destroyed galaxy map is at.


Why does APT want to upgrade my package?

Question: I need nginx compiled with a special flag, so I grabbed the source from the nginx stable PPA (apt-get source), changed debian/rules, built it and packaged it with debuild/dpkg-buildpackage, and installed the necessary .debs -- so far so good.
Only now APT wants to switch my local package with the one from the repository. This is a little puzzling since both packages have the exact same version:
$ dpkg -l nginx-full
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                    Version                                 Description
+++-=======================================-=======================================-==============================================================================================
ii  nginx-full                              1.2.1-0ubuntu0ppa1~precise              nginx web/proxy server (standard version)

and
$ sudo apt-get upgrade -s
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages will be upgraded:
  nginx-full
1 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Inst nginx-full [1.2.1-0ubuntu0ppa1~precise] (1.2.1-0ubuntu0ppa1~precise Stable:12.04/precise [amd64])
Conf nginx-full (1.2.1-0ubuntu0ppa1~precise Stable:12.04/precise [amd64])

Why exactly is this happening, and what's the best way of stopping it? Ideally, APT should offer to upgrade my package only with a strictly newer version, which would be a cue for me to rebuild my patched version with the newest source.
I've come across this bug report which looks pretty relevant, but since it contained no satisfactory work-around, I'm leaving the question open.
Comment: I assume you are trying to install from your local repository. am i correct?
Comment: The package has been installed directly from a .deb, using dpkg -i. Don't know if you would consider that a local repository.
Comment: I have no idea. trying to see what is happening
Comment: If the proposed package name has ppa1 in it, as all versions shown above do, it isn't in one of the main repositories. Have you added anyone else's PPA to work on this problem? The next version from the main repository will be 1.2.1-0ubuntu0, or higher.
Comment: @JohnSGruber: Yeah, I've added the ppa:nginx/stable PPA, so I could get the newest source package. This added both a `deb` and a `deb-src` entry. If I comment out the `deb` entry apt-get stops offering to upgrade my package, and I can still fetch the newest source, but I won't get notified when a new version is uploaded to the PPA.
Comment: So is this what you installed by hand with dpkg -i, or did you tailor it further?
Comment: I added a line to debian/rules to make it compile an additional module, that's about it.
Answer: You manage what gets updated by what using the version number, which is set from whatever is the top line in debian/changelog in the source package when the package is built into a deb. If you want a different version from what is in the PPA you need to set your own version number greater than what is in the PPA.
As a word of caution, note that 1.2.3-1ppa1~2 is less than 1.2.3-1ppa1, so apt-get upgrade would upgrade to 1.2.3-1ppa1. (There's magic in the "~", it is less than anything, including the end of the version number. I see you and the PPA have this symbol in your package version number.
Comment: This is the approach I ended up taking. Coming from a non-Linux/Debian/Ubuntu background, I found it interesting the changelog file wasn't purely descriptive, but actually parsed and used in the build process. For completeness' sake, I'll mention I used `dch -v ` to update the change log. Also an interesting tidbit about the special "~" sign, thanks for that. :)


unable to see my anything in database pycharm

Question: I really am at a loss here. I am using Pycharm 5.0.4 and running a virtual env with Python3 and Django 2.0.1.
I am trying to get my database up and running for my project, but no matter what I do I cannot seem to get anything to show up in the database tool window drop down in Pycharm. I have 'ENGINE': 'django.db.backends.sqlite3' set in my settings.py, and in Pycharm i am going to:
 Create New -> Data Source -> SQlite(Xerial).
I then makemigrations and migrate but nothing shows up in the database. I can even go to the project website and succesfully add/create models in the admin site. But I cannot figure out where they are or see them...
It was working at one point but I deleted my database because I was getting some errors and now I am trying to recreate it.
Answer: you do not need to go to Create New -> Data Source -> SQlite(Xerial).
if your setting.py database config is as is ('ENGINE': 'django.db.backends.sqlite3')  the database is autogenerated when you run makemigrations  then migrate.
to recreate the database (you said you deleted):

remove previous migrations (delete all files in your app's migration folder except the init.py)
Ctrl+Alt+R (or tools -> run manage.py)
then in the manage.py terminal run makemigrations andmigrate`

a new database will be created and migrations applied......... you dont have to worry about seeing the entries in the database directly.
If you're able to create superuser and login to the admin site and manipulate model data, then you're up and running
Comment: hello, i tried this several times. I agree that my database is somewhere, but why can i not see it in the side panel like i used to be able to?
Comment: so i right clicked on the database that Pycharm shows in the project directory (assuming that is the auto generated one) and selected `As Data Source..`, then clicked yes a couple of times and the database showed up in the "Database" panel with the correct tables
Comment: Oh.... You must have accidentally closed the database view.     good to know you're up and running now


JavaScript: How do I fire an event when a user has accessed the page via back/forward buttons?

Question: There is a number of threads here on StackOverflow concerning how to catch the back/forward button, but that's not what I want to do. I want to fire a method each time a page is loaded by pressing the back/forward button. So not on the page, where the user clicked back/forward, but on the page that the user got to after clicking back/forward.
I also tried looking at events using Chrome and I haven't found any event that is firing when coming back or going forward to a page.
Comment: Probably using a cookie is your best bet? There doesn't seem to be anything about that in the [request header](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers), and I'd imagine not all browsers would implement that (if it exists?) consistently anyway.
Comment: the cookie itself doesn't trigger an event. So your idea would be setup an interval for that?
Comment: This really depends on your front-end architecture and how your code handles History API events. Your *target* page won't get an event; it won't be able to tell if it was loaded by the "back" or "forward" button or by somebody clicking a bookmark, unless you have an architecture that can infer what's happening from custom headers or something. The History API in my experience is difficult to deal with if you want it to do things it doesn't want to do.
Comment: I never suggested that a cookie "triggers" anything. Cookies, being the only 'state management' that traditionally HTML has, have always been used to track users (and users' movements across your site). *Does that not sound related to what you're trying to do?*
Answer: You can use https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event

The popstate event will be triggered by doing a browser action such as a click on the back or forward button (or calling history.back() or history.forward() in JavaScript).

First you can save the info that user has navigated to localStorage or cookie, and then you can check if that localStorage entry or cookie exists on the next page load event.
If it exists, user has navigated to that page using back/forward buttons, you can do whatever you need to do, and clear the localStorage entry/cookie.


How to aggregate variable by time period for time series plot in R using ggplot2

Question: I would like to create a time series plot using ggplot2 in which the variable plotted over time. However, for each time period, I would like to plot the cumulative count for that period. For example:
set.seed(123)
frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE))
table(frame$year, frame$y)
ggplot(frame, aes(x = year, y = y)) + geom_point(shape = 1) # Not right

I would ultimately like it to generate a plot like this:
count<- table(frame$year, frame$y)[,2]
plot(2000:2005, count, type = "l")

I'm new to ggplot and any pointers would be greatly appreciated. Thanks.
Comment: what is your expected output
Answer: You are essentially missing a single line from your program.  You want a dataframe that returns the sum of the y variable for the year.
set.seed(123)
frame <- data.frame(id = sort(rep(c(0:5), 5)),year = rep(c(2000:2005), 5), y = sample(0:1,30, replace = TRUE))
table(frame$year, frame$y)
newFrame <-aggregate(frame$y, list(frame$year),sum)
ggplot(frame, aes(x = newFrame$Group.1, y = newFrame$x)) + geom_point(shape = 1) # Better
Answer: Try:
library(ggplot2)
library(dplyr)
frame %>% group_by(year) %>% summarise(sum = sum(y)) %>%
ggplot(aes(x = year, y = sum)) + geom_line()


I can't get my outgoing-only mail server working on 17.04

Question: I followed this tutorial:
I am using a container purchased on vultr.com: link
For the system mail name in step one, I used the domain name I have pointing to the ip, without any subdomians i.e. mydoimain.com
Got to step 3, and nothing is appearing in the mailbox I specify in the command.
echo "This is the body of the email" | mail -s "This is the subject line" firstname.lastname@example.com

What do I do now?
In /var/log/mail.log I see:
Apr 20 08:04:14 guest postfix/smtp[7023]: connect to gmail-smtp-in.l.google.com[2404:6800:4008:c03::1b]:25: Network is unreachabl

Answer: According to the message in /var/log/mail.log your Postfix tries to forward your test mail to one of Google's mail servers via IPv6. The message Network is unreachable means there is no IPv6 connectivity between the two. Since IPv6 mail delivery to Googlemail works generally fine the problem will be with your container.
Possible solutions:
a) Fix your IPv6 connectivity. vultr.com should be able to help you with this.
b) Limit Postfix to IPv4. This can be done by setting
inet_protocols = ipv4

in /etc/postfix/main.cf.
Note: There's more to running an outgoing mailserver than just setting up Postfix to deliver mail to servers on the Internet. You have to make sure you have IP addresses from a range that's allowed to send outbound mail, set up proper forward and reverse DNS for the server and preferably an SPF record for the domain you're sending from, create and monitor an abuse address, and monitor your server's reputation. Otherwise the next error message will be some variant of "550 5.7.1 Sender blocked".
Comment: Interesting, I am getting:

* added output to the main post


How can I position the link to the top right area? (Absolute positioning with a header as a relative)

Question: I'm trying to get the Anime Link to the top right area but can't. Only managed to do it like this but its maximum position is until the bottom of the other header. I'm an absolute newbie in this.
What I managed to do

#Header {
        position:fixed;
        background-color:#FFFFFF;
        width: 100%;
        height: 8%;
        top:0px;
    }
    #Header h1{
        margin-top:0px;
        position: relative;
    }
    #Header a{
        color:rgb(255,0,0);
    }
    #Header h3{
        position:absolute;
        top: 0px;
        right: 0px
        margin-top:0px;
    }

imsmoothlikebutter

 Anime

Answer: I think you forgot a semi-colon on line 18.

#Header {
        position:fixed;
        background-color:#FFFFFF;
        width: 100%;
        height: 8%;
        top:0px;
    }
    #Header h1{
        margin-top:0px;
        position: relative;
    }
    #Header a{
        color:rgb(255,0,0);
    }
    #Header h3{
        position:absolute;
        top: 0px;
        right: 0px; /* You forgot a semi-colon on this line */
        margin-top:0px;
    }

imsmoothlikebutter

 Anime

Comment: Well that's embarrassing! Thanks you so much!


Calling installed application method in another application

Question: I want to create an application that extracts text from .docx and .pptx files. Am using poi libraries. When I tried compiling it, it throws error of having too many methods.
In order to bypass this error (cause I need this poi libraries to effectively achieved this), after so many search on the internet, I observed that I can only do this by splitting the application into two applications. But the two applications will need to communicate among them. Especially, I would like to call some methods from one of the application in the second one. Can someone help me on how to achieve this?
Comment: Read about `Intent`.
Answer: There are several ways of doing this.
Check the answer on the stack overflow link.
android communication between two applications
But if you are getting

When I tried compiling it, it throws error of having too many methods.

while compiling your application, then you can add the following in build.gradle in order to bypass the error
<code>android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}
</code>
Please refer the documentation here
https://developer.android.com/tools/building/multidex.html
Comment: is there a reason you cannot update the ADT version? Also Multidex lib is a part of Android support library.
Comment: OK. Am gonna update it. If it works, I mark the question as answered. Thanks.


Retrofit + Instagram API returns error 400 when requesting for access token

Question: New to retrofit and am trying to consume Instagram API using retrofit. Below is the setup.
First I define the Interface for communicating with the Instagram API
public interface API {
    @POST("oauth/access_token")
    Call<AccessToken> getAccessToken(@Body TokenRequest tokenRequest);
}

Below is my Implementation
public class APIPresenter implements Callback<List<APIResponse>> {

static final String BASE_URL = "https://api.instagram.com/";

public void startI(String code){
    Gson gson = new GsonBuilder()
            .setLenient()
            .create();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    API r = retrofit.create(API.class);

    Call<AccessToken> call = r.getAccessToken(new TokenRequest("CLIENT_ID", "CLIENT_SECRET", "authorization_code", "redirecturi", code));
    call.enqueue(new Callback<AccessToken>() {
        @Override
        public void onResponse(Call<AccessToken> call, Response<AccessToken> response) {
           // Log.i("WORKING", response.body().access_token + " " + response.body().user.getUsername());
            Log.i("WORKING", String.valueOf(response.code()));
        }

        @Override
        public void onFailure(Call<AccessToken> call, Throwable t) {
            t.printStackTrace();
        }
    });
}

TokenRequest
public class TokenRequest {
    private String client_id;
    private String client_secret;
    private String grant_type;
    private String  redirect_uri;
    private String code;

    public TokenRequest(String client_id, String client_secret, String grant_type, String redirect_uri, String code) {
        this.client_id = client_id;
        this.client_secret = client_secret;
        this.grant_type = grant_type;
        this.redirect_uri = redirect_uri;
        this.code = code;
    }
}

AccessToken model
public class AccessToken {

    @SerializedName("access_token")
    @Expose
    public String access_token;
    @SerializedName("user")
    @Expose
    public User user;

}

Problem is that when I try to output the contents of the response in the onResponse method, I get a null. I'm not sure what I'm doing wrong
Update
I'm getting the following error message

{"code": 400, "error_type": "OAuthException", "error_message": "You must provide a client_id"}
Answer: I managed to solve this issue, issue was Instagram doesn't support sending the parameters as URL parameters, they must be sent in the body content of the POST.
The content type should be set to "application/x-www-form-urlencoded".
This is how you you accomplish it with the code above
You have to add @FormURLEncoded annotation before the POST method, this will only work @Field annotation, hence the @Body content shall be replaced with the following @Field annotation.
public interface API {
@FormURLEncoded
@POST("oauth/access_token")
Call<AccessToken> getAccessToken(
        @Field("client_id") String client_id,
        @Field("client_secret") String client_secret,
        @Field("grant_type") String grant_type,
        @Field("redirect_uri") String redirect_uri,
        @Field("code") String code);
}

This is how you will send the details to your getAccessToken method on the Interface
 Call<AccessToken> call = r.getAccessToken("CLIENT_ID", "CLIENT_SECRET", "authorization_code", "redirecturi", code);

This should work perfectly!
Answer: You are posting client_id and other fields in the wrong way. Look how it is implemented in similar project:
public static String requestOAuthUrl(final String clientId, final String redirectUri, final Scope... scopes) throws URISyntaxException {
        final StringBuilder urlBuilder = new StringBuilder();
        urlBuilder.append("response_type=").append("token");
        urlBuilder.append("&client_id=").append(clientId);
        urlBuilder.append("&redirect_uri=").append(redirectUri);
        if (scopes != null) {
            final StringBuilder scopeBuilder = new StringBuilder();
            for (int i = 0; i < scopes.length; i++) {
                scopeBuilder.append(scopes[i]);
                if (i < scopes.length - 1) {
                    scopeBuilder.append(' ');
                }
            }
            urlBuilder.append("&scope=").append(scopeBuilder.toString());
        }
        return new URI("https", "instagram.com", "/oauth/authorize", urlBuilder.toString(), null).toString();
    }

It is taken from https://github.com/wearemakery/retrogram
Comment: Thanks, but this solution wont work with my project as it was build on retrofit 1.6.1. I have however fixed the issue, you can check my answer.


surface(2d) fit in MATLAB with anonymous function

Question: I want to use fit in MATLAB for two dimensions.
I defined function separately and then called it with fittype
x has two columns!
f=fittype('@(x)myfun(beta1, beta2,beta3, x)')

and then customize in options my start point and algorithm.
then use [results, goodness]=fit(x, zdata,f, options), but I have a error
??? Too many inputs to FITTYPE function.
Error in ==> fit at 443
                errstr = handleerr( errid, errmsg, suppresserr );
I also tried with [results, goodness]=fit([x(:,1), x(:,2)], zdata,f, options),
and still have the same problem.
I used fit -all
XDATA must be a matrix with one to two columns.
Error in ==> fit at 115
    errstr = handleerr('curvefit:fit:xDataMustBeColumnVector', ...
for me sounds meaningles , since I have my x in two columns!!!!
and then which fit -all
/Applications/matlab/MATLAB_R2010a.app/toolbox/curvefit/curvefit/fit.m
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/@ProbDistUnivParam/fit.m  % ProbDistUnivParam method
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/@NaiveBayes/fit.m         % NaiveBayes method
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/@gmdistribution/fit.m     % gmdistribution method
could you please help me to use fit and fittype to fit my 2 dimension data?
{please don't introduce me meshgrid and other commands.}
Comment: just in a simple way, could you tell me how to define  anonymous function for surf fit with fit type?
Answer: You need to add the parameter 'numindep' = 2 which indicates that your fit is for a surface (i.e has two independent variables).
Here's an example using your function with the Franke data using a string:
load franke
ft = fittype('myfun(beta1, beta2, beta3, [x, y])', 'numindep', 2)
[results, goodness] = fit([x, y], z, ft)

Here's an example using your function with the Franke data using an anonymous function:
load franke
ft = fittype(@(beta1,beta2,beta3, x, y)myfun(beta1, beta2,beta3, [x, y]), 'numindep', 2)
[results, goodness] = fit([x, y], z, ft)


Comparison string in jinja

Question: how to compare the data from database to compare with value in html with jinja?
I try gender value from db is Male
                {% set gender=user.gender  %}
                {% if gender == 'Male' %}
                {%  set check = "checked"  %}
                {% else %}
                {%  set check = "unchecked"  %}
                {% endif %}

but the output is Male unchecked and Female also unchecked
Comment: The logic for your code is correct. Have you checked your variables `user`, and is it possible that the "Male" you passed is in lowercase?
Comment: Yeah, user gender value is 'Male'. The user value is from an ontology and the datatype is string. But in jinja how to check datatype?
Answer: I cannot reproduce the issue so it probably means your user variable is not defined as you expect:
import jinja2
t=jinja2.Template('''         {% set gender=user.gender  %}
                {% if gender == 'Male' %}
                {%  set check = "checked"  %}
                {% else %}
                {%  set check = "unchecked"  %}
                {% endif %}
''')
for gender in ['Male', 'Female']:
    m = t.make_module(vars = {'user': {'gender': gender }})
    print(m.check)

prints:
checked
unchecked

Comparison string in jinja


How to align LI vertically middle

Question: I've HTML UL LI tags arranged as mentioned below:

A

B

<input type="submit" name="one" id="one" value="one">

Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. SamplText here. Sample Text here. Sample Text here. Sample Text here. Sample Text here.

   C

<input type="radio" name="optia" value="a" id="optia">A

Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here. Sample Text here.

   C

It gives output as mentioned below:

How Can i Align RADIO Boxes and Text "C" in the last column vertically middle with the LI ; along RED Line Drawn?
Comment: @j08691 ; Sorry I didn't get you? What is Ug? [Inline CSS are added in above post just to give look and feel of UI, in real code CSS are external]
Comment: Ug is me throwing my hands in the air trying to debug this.
Answer: By Adding TOP & BOTTOM PADDING ; i managed to align radio button vertically centered with LI. I don't think this is fool-proof solution; But as a work-around it works.
Answer: Your going to want to add a vertical-align: bottom; to align it to the red line.  But I would really avoid using inline CSS as it will muck up your html from looking clean and crisp.
style="vertical-align: bottom" // add to your li for the C

Comment: I added vertical-align: bottom to LI for C ; but it's now working. [In read code CSS is external]

How to align LI vertically middle


scaling data between -1 and 1 centred on zero

Question: Apologies in advance for any incorrect wording. The reason I am not finding answers to this might be because I am not using the right terminology.
I have a dataframe that looks something like
0        -0.004973    0.008638   0.000264     -0.021122   -0.017193
1        -0.003744    0.008664   0.000423     -0.021031   -0.015688
2        -0.002526    0.008688   0.000581     -0.020937   -0.014195
3        -0.001322    0.008708   0.000740     -0.020840   -0.012715
4        -0.000131    0.008725   0.000898     -0.020741   -0.011249
5         0.001044    0.008738   0.001057     -0.020639   -0.009800
6         0.002203    0.008748   0.001215     -0.020535   -0.008368
7         0.003347    0.008755   0.001373     -0.020428   -0.006952
8         0.004476    0.008758   0.001531     -0.020319   -0.005554
9         0.005589    0.008758   0.001688     -0.020208   -0.004173
10        0.006687    0.008754   0.001845     -0.020094   -0.002809
...

For each column I would like to scale the data to a float between -1.0 and 1.0 for this column's min and max.
I have tried scikit learn's minmax scaler with scaler = MinMaxScaler(feature_range = (-1, 1)) but some values change sign as a result, which I need to preserve.
Is there a way to 'centre' the scaling on zero?
Comment: I see you have negative and positive values. You want to keep the 0 point? In that case just divide the negative numbers with the minimum of the df (or row, or column whichever you want to normalise) and the positives with the maximum.
Comment: I'm only showing a sample of the dataframe, all columns have both positive and negative values
Comment: thank you @GáborErdős that might just do the trick!
Answer: Have you tried using StandardScaler from sklearn ?
It has with_mean and with_std option, which you can use to get data you want.
Comment: But that would results in the occasional value bigger (smaller) than 1 (-1). Perhaps using `StandardScaler` followed by a `MinMaxScaler`?
Comment: if we use 4*sgima = 1, then with_std = `1/4`. then i believe it will no cross 1 to -1 boundary that much
Comment: Could work I guess, dunno if that will be good enough for the OP.
Comment: thank you @kppatel, could you clarify how I would use `4*sgima = 1` and `with_std = 1/4` ? the latter is used as argument to standard scaler but the former?
Comment: if you take `4*sigma`  = 1, that means your 99.9999998% of your observation will fall under -1 to 1
Answer: The problem with scaling the negative values to the column's minimum value and the positive values to the column's maximum value is that the scale of the positive numbers may be different than the scale of the positive numbers. If you want to use the same scale for both negative and positive values, try the following:
def zero_centered_min_max_scaling(dataframe):
    """
    Scale the numerical values in the dataframe to be between -1 and 1, preserving the
    signal of all values.
    """
    df_copy = dataframe.copy(deep=True)
    for column in df_copy.columns:
        max_absolute_value = df_copy[column].abs().max()
        df_copy[column] = df_copy[column] / max_absolute_value
    return df_copy


want to rotate my cube. how could i do that

Question: I want to rotate my cube and add 4 buttons to speed up speed down move up and move down. Could you help me? The color is yellow. 4 buttons under cube.cube should rotate about y axis.
<code>public class MyGLRenderer implements Renderer {
Context context;

Cube cube;

public MyGLRenderer(Context context) {

    this.context = context;

    cube = new Cube();
}

// Call back when the surface is first created or re-created
@Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
    // clear-value for color and depth, enabling depth-test, etc.
    gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set color's clear-value to black
}

// Call back after onSurfaceCreated() or whenever the window's size changes
@Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
    if (height == 0)
        height = 1;
    float aspect = (float) width / height;

    // Set the viewport (display area) to cover the entire window
    gl.glViewport(0, 0, width, height);

    // Select projection matrix: projection matrix or model-view matrix
    gl.glMatrixMode(GL10.GL_PROJECTION);
    // Reset projection matrix
    gl.glLoadIdentity();

    GLU.gluPerspective(gl, 45, aspect, 0.1f, 100.f);

    // Select model-view matrix
    gl.glMatrixMode(GL10.GL_MODELVIEW);
    // Reset
    gl.glLoadIdentity();

}

// Call back to draw the current frame.
@Override
public void onDrawFrame(GL10 gl) {
    // Clear color and depth buffers using clear-value set earlier
    gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

    // Reset model-view matrix
    gl.glLoadIdentity();
    // Translate into the screen
    gl.glTranslatef(0.0f, 0.0f, -5.0f);

    // Draw cube
    cube.draw(gl);
}
</code>
}
Answer: this is what you are looking for: https://www.opengl.org/sdk/docs/man2/xhtml/glRotate.xml and you have to place it  in front of glTranslatef


Are there any vehicles or mounts in The Secret World?

Question: In The Secret World, are there any mounts or vehicles?
If not, are there any abilities that give increased movement speed?
Answer: No, there are no mounts or vehicles.
However, you can purchase upgrades to your Sprint speed from a vendor at your factions HQ. For the Illuminati at least, he's labelled as the Mobility and Tactics Trainer. These upgrades are called Quickened Anima. They come in +62.5%, +75% and +100% speed varieties (non-cumulative), are locked to faction rank and can be purchased at ranks 2, 4, and at a cost of 100,000, 500,000 and one million Pax Romana respectively.
Comment: Possible exception is the snowmobile you spend one part of the A Dream To Kill quest riding.
Answer: As of patch 1.11.3 (June 03, 2015), "Custom Sprints" have been added to the game.
These are different animations / models for sprinting - and include (in this patch - more to come, we're told) the "Franken-Chopper" (a motorbike). The new custom sprints have new categories, including:

On Foot
Classic
Extraordinary

The patch notes for this addition follow:

NEW!!
  Custom Sprints
  Further customize your character with all new custom sprint effects! A new collection UI houses all of your custom sprint options, and you'll be able to select which you'd like to use primarily or let the game choose a random sprint effect upon use. Additionally, Sprint VI will be purchasable through your Faction's Advanced Faction Fixer, providing a 150% boost. The custom sprints that will debut with this feature are the Franken-Chopper motorbike, The Athlete, Fleet of Flame, and Dead Fast.


pandas: round up to closet float number defined by user

Question: I have one array which contains continuous values. I need to round up those values to the closet float value. ex: 32.25 to 32.50 , 30.29 to 30.50, 33.75 to 34.00. In short: if it is from .1 to .49 round up to .50 and if it is from .51 to .99 round up to .00. How can I do it. Thank you in advance.
array([32.5 , 32.49, 32.48, 32.47, 32.46, 32.45, 32.44, 32.43, 32.42,
       32.41, 32.4 , 32.39, 32.38, 32.37, 32.36, 32.35, 32.34, 32.33,
       32.32, 32.31, 32.3 , 32.29, 32.28, 32.27, 32.26, 32.25, 15.75,
       15.76, 15.77, 15.78, 15.79, 15.8 , 15.81, 15.82, 15.83, 15.84,
       15.85, 15.86, 15.87, 15.88, 15.89, 15.9 , 15.91, 15.92, 15.93,
       15.94, 15.95, 15.96, 15.97, 15.98, 15.99, 16.  , 16.01, 16.02,
       16.03, 16.04, 16.05, 16.06, 16.07, 16.08, 16.09, 16.1 , 16.11,
       16.12, 16.13, 16.14, 16.15, 16.16, 16.17, 16.18, 16.19, 16.2 ,
       16.21, 16.22, 16.23, 16.24, 16.25, 16.26, 16.27, 16.28, 16.29,
       16.3 , 16.31, 16.32, 16.33, 16.34, 16.35, 16.36, 16.37, 16.38,
       16.39, 16.4 , 16.41, 16.42, 16.43, 16.44, 16.45, 16.46, 16.47,
       16.48, 16.49, 16.5 , 25.25, 25.5 , 25.51, 25.52, 25.53, 25.54,
       25.55, 25.56, 25.57, 25.58, 25.59, 25.6 , 25.61, 25.62, 25.63,
       25.64, 25.65, 25.66, 25.67, 25.68, 25.69, 25.7 , 25.71, 25.72,
       25.73, 25.74, 26.  , 26.01, 26.02, 26.03, 26.04, 26.05, 26.06,
       26.07, 26.08, 26.09, 26.1 , 26.11, 26.12, 26.13, 26.14, 26.15,
       26.16, 26.17, 26.18, 26.19, 26.2 , 26.21, 26.22, 26.23, 26.24,
       26.25, 26.26, 26.27, 26.28, 26.29, 26.3 , 26.31, 26.32, 26.5 ,
       26.49, 26.48, 26.47, 26.46, 26.45, 26.44, 26.43, 26.42, 26.41,
       26.4 , 26.39, 26.38, 26.37, 26.36, 26.35, 26.34, 26.33, 28.5 ,
       28.51, 28.52, 28.53, 28.54, 28.55, 28.56, 28.57, 28.58, 28.59,
       28.6 , 28.61, 28.62, 28.63, 28.64, 28.65, 28.66, 30.5 , 30.49,
       30.48, 30.47, 30.46, 30.45, 30.44, 30.43, 30.42, 30.41, 30.4 ,
       30.39, 30.38, 30.37, 30.36, 30.35, 30.34, 30.33, 30.32, 30.31,
       30.3 , 30.29, 30.28, 30.27, 30.26, 30.25])

Answer: Did you not experiment with this?  numpy is built for experimentation.
array = (array * 2 + 0.4999).round() / 2

Comment: This isn't exactly right. Try `0.6` for instance. Your code will round it down to `0.5`
Comment: not getting correct result.. @Tim Roberts
Comment: @TimRoberts I have one issue that if 25.5 goes to 26 but I want 25.5 as it is. Same for if it 26. 0 then it should be as it is. If it is greater than 25.51 then it should round up as 26. How can I do it?
Comment: You're right, I forgot to round up.
Comment: @NuriTaş --  You surely cannot be suggesting that `1.0` when rounded to the nearest 1/2 should be `1.5`.
Comment: Using `np.ceil` would be simpler than the "add `0.4999` and then round" approach. (And more correct, too: you really want `2.00001` to round to `2.5` rather than `2`.)
Answer: Another solution:
import math
[math.modf(item)[1] + 0.5  if (0.1 <= ( item % 1) <= 0.5) else math.modf(item)[1] for item in array]

Answer: use the below code
round_off_values = np.round_(array, decimals = 1)


How to tabularize with delimiter of groups of spaces in Vim

Question: I have some lines like this
abc  defg  hijklmnopq
abc    defghi  jklmn opq
abc  defgh  ijklmno pq

I want them to be tabularized into at most three columns with at least 2 spaces in between columns, i.e.
abc  defg    hijklmnopq
abc  defghi  jklmn opq
abc  defgh   ijklmno pq

What Tabularize command should I use in Vim?
Answer: Given your input and output samples, the following command should do it.
:Tab /\s\+\zs\s/l1c0

You can abbreviate :Tabularize to :Tab to save a few keystrokes. The regular expression relies on a property of your data, namely that there is more than one space character separating the columns; otherwise it would be impossible to know which text belongs to which column.
We choose the final space as the delimiter character and then align the text left with a padding of 1. The \s serves as the second padding space.
In the future, and as always, please consider the :help. :help tabular has extensive and very readable documentation that describes in detail all of the above.


Can I close a node readStream before end?

Question: I am dropping a fs.createReadStream onto a large file.
Can I stop the stream part way through?
I don't see one in the doco, and tried calling stream.end() but it still processes the whole file, and stream.close() is undefined.
Any help would be great, thanks.
Comment: What node version? `close()` works for me
Comment: As @vkurchatkin says, `close()` should do what you want, which is close the underlying file so no more data is read. What are you seeing that contradicts that?
Comment: I have to get back to this once I get more time to test things out.
Comment: possible duplicate of [How to close a readable stream?](http://stackoverflow.com/questions/19277094/how-to-close-a-readable-stream)
Answer: stream.destroy() might be what you want. More details here.
Answer: According to How to close a readable stream (before end)?, it is possible, you can call close() on a readStream and it will close before end. I write a simple script to test it:
var fs = require('fs');

var l = 0

var rs = fs.createReadStream("some large file")
    .on("data", function(data){
        console.log("got data");
        l += data.length;
        if (l > 655360) {
            rs.close();
            console.log("close");
        }
    })
    .on("end", function(){
        console.log("shouldn't be logged");
    });

output:
got data
got data
got data
got data
got data
got data
got data
got data
got data
got data
got data
close
got data
close

Though close is printed twice, it does end the readStream.
Answer: Edit:
It is not possible at this time by design as can be seen by the code comments: https://github.com/joyent/node/blob/master/lib/_stream_readable.js#L884
A possible solution according to the docs is to use offsets: http://nodejs.org/api/fs.html#fs_fs_createreadstream_path_options

An example to read the last 10 bytes of a file which is 100 bytes
  long:
  fs.createReadStream('sample.txt', {start: 90, end: 99});
Comment: I am not looking to read predetermined bytes lengths or offsets; I am doing other logic based on content.  Thanks for the answer though.
Comment: Can you just iterate over the stream until you find what you are looking for? i.e read a certain amount of bytes. If its not there, change the offset and try again?
Comment: I would prefer to do as the question asks: close an open stream.
Comment: You won't be able to do that with a stream. A stream is an all or nothing IO process. It knows nothing pre-determinant about the data you are looking at. In the case of the offset for example it is going to scan the file to determine length and then retrieve the byte(s) you want. Thus stopping a stream "in the middle" leaves you with corrupt data that is useless.
Comment: It isn't useless if I already pulled out what I need.  What about the scenario where I am in non-flowing mode and instead of calling read when I am ready for data, I say we are never going to be ready for that data, just stop streaming data.  Can you find in docs where a stream is designed to be an, "all or nothing IO process"?
Comment: It does look it is designed to always read the whole content: https://github.com/joyent/node/blob/master/lib/_stream_readable.js#L884
Comment: I had not found it in the documents; A stream is a construct across all coding languages. I am glad you found that though.
Comment: Other languages allow streams to be closed prior to completion though: http://msdn.microsoft.com/en-us/library/aa328800(v=vs.71).aspx, and Java has one too
Comment: If you want to modify your answer to say that it isn't possible at this time by design I will accept this answer.  If you want to toss in the alternative approach of using the byte offsets it will make a complete answer.
Comment: Java uses a form of byte blocking and buffering to allow this. Looks to be the same for .NET. You can break off after each block. I also updated the answer with your code reference.
Comment: @Shawn Line 884 is saying that the `end` event will never fire if there is still data to be read, which is true. You can still use `.close` to close the stream early, it will just never fire `end`.


How to test memory advance pattern?

Question: I am new learner in Ubuntu. I want know about how to execute memory advance pattern test? Is there any ubuntu command or c++ program?
Comment: Why exactly do you want to do this test? As already answered, memtest is usually performed from the boot menu, is there any particular reason you want to do it specifically from a booted system?
Answer: If you are dual boot on startup when grub appears choose the memtest option. If not dual boot while system is booting hit shift and choose the memtest option.
Comment: Memory can not be test while running any OS it just does not work that way.
Comment: Thanks for answering. But i need any c++ program or any ubuntu package or that can test it without any boot

How to test memory advance pattern?


POST extra values in an HTML

Question: I have a simple form which passes the value of an <input /> element:
<form action="updaterow.php" method="POST">
    <input type="text" name="price" />
</form>

How can I post extra values along with the <input /> value? For example, an arbitrary string, or a variable inside the current PHP script.
I know this is possible with GET:
<form action="updaterow.php?foo=bar" method="GET">
    <input type="text" name="price" />
</form>

or:
<form action="updaterow.php?foo=<?=htmlspecialchars($bar)?>" method="GET">
    <input type="text" name="price" />
</form>

but I need POST.
Answer: You can include a hidden form element.
<input type="hidden" name="foo" value="bar" />

Comment: is having hidden elements a bad practice at all?
Comment: @Abdul No. In fact, it's the only way to solve this particular problem!
Answer: You can simply use a hidden field. Like so:
<input type="hidden" name="your-field-name" value="your-field-value" />

This field will then be available in your PHP script as $_POST['your-field-name']
Answer: As mentioned already, using hidden input fields is an option, but you can also use a session. That way you don´t have to post anything, the variables remain on the server and are not exposed in the html.

POST extra values in an HTML


start Apostrophe markdown editor from comand line

Question: I installed Apostrophe markdown editor to my Ubuntu. I have an icon on my desktop which opens a markdown file with Kate editor.
This is the command I use: /usr/bin/kate <path-to-file>.md. This works fine.
But now, I would like to open the file with Apostrophe. How to start Apostrophe from the command line?
When I start the app from the main menu, then I can see that the following processes appear:
ps axu | grep apostr

user        5380  0.3  0.0   3768  1788 ?        S    23:57   0:00 bwrap --args 31 apostrophe
user        5381 12.7  1.2 102450484 101460 ?    Sl   23:57   0:01 python3 /app/bin/apostrophe
user        5390  0.0  0.4 102363952 38164 ?     S    23:57   0:00 python3 /app/bin/apostrophe
user        5391  0.0  0.4 102363952 38132 ?     S    23:57   0:00 python3 /app/bin/apostrophe
user        5396  0.0  0.0   9368   660 pts/0    S+   23:57   0:00 grep --color=auto apostr

But I am not able to start it with the same command.
What is the proper command to start it and open a given file automatically?
Comment: Find the parent process of the `python3 /app/bin/apostrophe` by entering `ps -ef|grep apostr` . The third column is the parent process ID. Do a grep for that, and so on, until you reach the top level command.
Comment: Perhaps related: [Running a .desktop file in the terminal](https://askubuntu.com/questions/5172/running-a-desktop-file-in-the-terminal)
Answer: Use this command:
flatpak run org.gnome.gitlab.somas.Apostrophe <your file>


How prove this $\sum_{k=1}^{m-1}\dfrac{(-1)^{k+1}}{C_{m}^{k}}=\dfrac{(-1)^{m}+1^m}{m+2}$

Question: prove that
$$\sum_{k=1}^{m-1}\dfrac{(-1)^{k+1}}{C_{m}^{k}}=\dfrac{(-1)^{m}+1^m}{m+2}$$
where $C_{m}^{k}=\dfrac{m!}{(m-k)!k!}$
This problem is my frend ask me,I think we can prove by case$:m=2n,m=2n+1$
Thank you everyone can nice methods.
Comment: oh.Thank you ,I have edit
Comment: If $m$ is odd, note that the summands for $k$ and $m-k$ cancel.
Comment: Thank you,But for $m$ is even,I can't prove it.
Answer: Since
$$\frac{1}{C^m_k}=(m+1)\frac{\Gamma(m-k+1)\Gamma(k+1)}{\Gamma(m+2)}=(m+1)B(m-k+1,k+1),$$
the sum can be rewritten as
\begin{align}
&(m+1)\int_0^1\left(\sum_{k=1}^{m-1}(-1)^{k+1}\left(\frac{x}{1-x}\right)^k\right)(1-x)^mdx=\\
=&(m+1)\int_0^1\left[x(1-x)^m+(-1)^m(1-x)x^m\right]dx=\\=&(m+1)\left(1+(-1)^m\right)B(2,m+1)=\\
=&\frac{1+(-1)^m}{m+2}.
\end{align}
Here $B(p,q)=\frac{\Gamma(p)\Gamma(q)}{\Gamma(p+q)}$ denotes Euler beta function, and the summation over $k$ was performed using geometric series.
Comment: It's very nice.Thank you


Why static class fields don't collide with other method variables (named with same name)

Question: I have a question related to the following class, and why it doesn't give a compilation error. Usually I would expect that java compiler to complain about variables being defined twice but it doesn't.
public class Whiz {
    static int x = 4;
    static String a = "my static string";

    public static void main(String[] args) {
        for (int x = 5; x < 10; x++) //no name collision with static int x
            x++;
        //out of for loop
        System.out.println(x--); //prints 4

        String a = "whoaaaa....no collision"; //no name collision with static String a

        System.out.println(Whiz.a);
        System.out.println(a);
    }
}

Comment: read about the scope of variables
Comment: https://dzone.com/articles/variable-shadowing-and-hiding-in-java
Comment: @Jens, I didn't found anywhere an explanation for this. A class field is having highest scope as they can be accessed from any method or block in that class and from out side of the class with qualified name. I would expect a collision between a class field and a method variable with same name.
I checked: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html
Answer: The example you posted defines variables in different scopes – one defined on the class, one defined as a local variable inside a method. It is not relevant that one of them is static. It doesn't (and shouldn't) produce a compilation error.
You can however generate a compilation error if you define two variables in the same scope, but this should be an obvious programming mistake:
public class Example {
    int x = 0;
    int x = 1; // error: Variable 'x' is already defined in the scope
}

For (much) more detail, take a look at the following sections of the Java Language Specification:

Scope of a Declaration
Shadowing and Obscuring


Quadratic Equations in two-variables.

Question: Determine the number of ordered pairs $(x, y)$ of positive integers satisfying the
equation $x^2+y^2-16y=2004$.
My solution:
$x^2+y^2-16y=2004$
$\Rightarrow x^2=2004-y^2+16y$
$\Rightarrow x=\sqrt{2004-y^2+16y}$
Now, plugging in integers on the R.H.S. for $y=1$ to $53$ (since both $x$ and $y$ are positive integers, and for $y>53$, $x$ is imaginary), (on Excel);
I do not get any pair of $x$ & $y$; where both are positive integers.
Answer : $0$
Is this solution correct?, and is there a smarter way to solve this problem?
Comment: Thank you @Parcly Taxel...
Answer: Zero is correct, but a much faster way follows. Complete the square first:
$$x^2+y^2-16y+64=2004+64$$
$$x^2+(y-8)^2=2068=4×11×47$$
$11\equiv3\bmod4$ and it appears only once in the prime factorisation, so no pair $(x,y)$ satisfies the given equation by the sum of two squares theorem.
Comment: Thank You very much for the solution...Greatly appreciated.

Quadratic Equations in two-variables.


Coupling methods

Question: Distance between probability measures
Let $(X,d)$ be a compact metric space, and let $\mu$ and $\nu$ be two probability measures on $X$. We can define the Wasserstein distance between $\mu$ and $\nu$ in the following way.
Let $\mathcal{P}_{\mu, \nu}$ be a the set of probability measures on $X \times X$ whose first marginal is $\mu$ and second marginal is $\nu$. Then:
$$W_1 (\mu, \nu) = \min_{\pi \in \mathcal{P}_{\mu, \nu}} \int_{X \times X} d(x,y) \pi (dx,dy).$$
Distance between compact spaces
Let $(X,d)$ and $(X',d')$ be two compact metric spaces. We can define the Gromov-Hausdorff distance between $\mu$ and $\nu$ in the following way.
Let $\mathcal{D}_{d, d'}$ be a the set of distances on $X \coprod X'$ whose restriction to $X \times X$ is $d$ and whose restriction to $X' \times X'$ is $d'$. Then:
$$d_{GH} ((X,d), (X',d')) = \inf_{D \in \mathcal{D}_{d, d'}} D_H (X,X'),$$
where $D_H$ is the Hausdorff distance in $X \coprod X'$ for the distance $D$.
Generalizations ?
These two distances are defined in a similar way. To create a distance between two objects $X$ and $Y$, we realize them simultaneously into a larger object, and quantify their distance in the larger object. Then, we take the infimum.
They also have the same kind of "universal" definitions. The Wasserstein distance between two probability measures can be defined as a minimum over all couplings between these probability measures (without specifying the base space). The Gromov-Hausdorff distance can be defined as a minimum over all isometric embeddings of the compact metric spaces.
In addition, these definitions or sort of compatible, in that it is possible to define a Gromov-Hausdorff-Wasserstein distance between probabilized compact metric spaces (see e.g. here).
From here, I have two questions:
1) Why does the definition of the Wasserstein distance uses a product, and the definition of the Gromov-Hausdorff distance a coproduct? I suspect it has to do with the fact that measures are naturally pushed forward and distances are naturally pulled backward (this is also what the .pdf I linked to suggests), but that's little more than a hunch.
2) Are there other examples of this kind of construction, where we define a distance between two structures by realizing them simultaneously, taking the distance in some way in this realization, and then taking the infimum over all such realizations? I was thinking in particular of algebraic structures, but anything goes.
Answer: In regards to question 2, in graph theory there is the notion of a cut metric.
Suppose we are given graphs $G, H$ with the same number of vertices. For any subsets of vertices $U,V$, define $e(U,V)$ to be the number of edges between $U$ and $V$. Now for any bijection $f: G \rightarrow H$, we may compute
$$ \max_{U,V \subseteq G}{\frac{|e(U,V) - e(f(U),f(V))|}{|U| |V|}}. $$
Then the cut metric $\delta_{\square}(G,H)$ is defined to be the minimum over all bijections $f$, of the above quantity.
This metric is useful because if you generate $G,H$ randomly by independently picking each edge with some fixed probability, the distance between them will be small. Moreover, the well known Szemeredi regularity lemma is equivalent to the statement that the completion of the space of graphs under the cut metric is compact (one needs to extend the metric to graphs with different numbers of vertices).
Anyway, this notion seems analogous to the Gromov-Hausdorff distance.
Answer: You may be interested in the fact that there exists a "Gromov-Hausdorff-Wasserstein" distance and also a "Gromov-Hausdorff-Prokhorov" distance, each between two metric measure spaces. You'll find some insight in:

Gromov-Wasserstein distances and the metric approach to object matching. F. Mémoli. Foundations of Computational Mathematics. 11(4), August 2011, pp. 417-487(71).
The space of spaces: curvature bounds and gradient flows on the space of metric measure spaces, Karl-Theodor Sturm. See also the YouTube video "K.-T. Sturm: Geometric Analysis on the Space of Metric Measure Spaces" uploaded by the Hausdorff Center for Mathematics.

I may also shamelessly point to two of my blog posts:

Comparing shapes: From Prokhorov/Wasserstein over Hausdorff to Gromov-Hausdorff metrics
Comparing shapes: metric measure spaces
Answer: Part 1:
The probability measures $\mu$ and $\nu$ are defined on the same metric space. The difference is only on the measures that we consider which usually is $\mu\neq \nu$. To answer how much? we can simply define a metric of type $$d_{TV}(\mu,\nu)=\sup_{A\in\Omega}|\mu(A)-\nu(A)|$$ which is the total variation. This metric also has a coupling characteristic $$d_{TV}(\mu,\nu)=\inf\{P(X\neq Y): X, Y\, \mbox{random variables s.t.}\,\,\mathcal{L}(X)=\mu,\,\mathcal{L}(Y)=\nu\}$$
When we are interested in the distance between the compact metric spaces, both the metric $d$ as well as the metric space $X$ are possibly different from $(d^{'},X^{'})$. The question to be answered is how much far away are these metric spaces from being isometric to each other. I think the concept is fairly different and this also plays a role why in this case we are looking for the distance over the sets instead of probability measures. The difference is basically at the definition of isometry.
If $(X,d)$ is isometric to $(d^{'},X^{'})$ one should be able to find a mapping $f:X\mapsto X^{'}$ such that $d^{'}(f(x_0),f(x_1))=d(x_0,x_1)$ for all $x_0,x_1\in X$. If this is not true, then a metric should give the amount of discrepency. What one can do is to consider isometric mappings $f$ and $g$ and a metric space $M$ however in this new metric space, the former metric spaces $(X,d)$ and $(d^{'},X^{'})$ are coupled. On $M$, their distance properties are preserved but after embedding $d_H(f(X),g(X^{'}))$ is something new to compare. If one makes it for all $M$ as well as for all $f,g$, we will have various numbers. Among all the minimum should determine the discrepency.
Part 2:
Yes there are several metrics with the minimum or maximum property as you defined. For example as I wrote about Total variation metric. Levy metric,Prokhorov metric and discrepency metric are the others. Here is an almost complete list of such distances.
Comment: Actually, the Wasserstein distance also makes sense for two probability measures defined on different metric spaces.

Coupling methods


APT. Delete package "Dependencie", without deleting package "Needed"

Question: I want to delete nautilus, but I have a cool script named Folder Color, that has in his dependencies nautilus.
Can I mark in apt keep package folder-color and delete nautilus?
Comment: And what will you do with folder-color package?!? There is no any reason to keep it as long as it [change a color for a folder used only in Nautilus](https://launchpad.net/folder-color)...
Comment: it works with Nemo as well.
Comment: I think you are wrong: *[Just Ubuntu ;) It'll use Nautilus and the Humanity theme](http://foldercolor.tuxfamily.org/)*... But there is a workaround [here](http://ubuntuportal.com/2014/05/folder-color-make-your-folder-icon-in-nautilus-and-nemo-colorful.html) which will work only if you have Nautilus installed.
Comment: It works for Nemo. All that need's to be done is to change Nautilus for Nemo in script, that's all.
Comment: Yes, that's all as long as you have Nautilus installed :)
Comment: amm... No. I saw script and there is nothing that hardly set to work only with nautilus...
Answer: It seems that Folder Color only works with nautilus. So, if you want to use Folder Color, you're stuck with nautilus. It may exist for other file managers (the site I linked to states it works with Nemo if you mess around with it a bit), so look into that.
Comment: it works with Nemo as well. And I'm using Nemo and Folder Color for some time.


Which is better, NSSet's containsObject or fast enum?

Question: I need to determine whether an object is included in a Core Data to-many relationship (which is an NSSet), and I'm trying to decide which of two solutions is better:
Solution 1)
if ([managedObject.items containsObject:itemOfInterest])
    return …

Solution 2)
for (NSManagedObject *item in managedObject.items)
    if ([item == itemOfInterest])
        return …

Solution 1 is more concise, but the NSSet Class Ref says fast enumeration performs better than NSSet's objectEnumerator. Does it also perform better than containsObject?
Comment: I may be missing something here but why do you need to search at all? If you already have both objects on each side of a relationship you already have the info you need. Is this a many-to-many relationship or a one-to-many without a reciprocal?
Comment: @TechZen: A fetch is made per user's search criteria. The results are displayed in a table. The user makes a subselection of these results via the table. There is another table with members of the to-many relationship, presented with checkboxes. The checkbox states must be set according to whether all, none, or some of the selected objects contain their item. There can be a lot of objects involved, so it is important to use the most efficient method. Thanks to the advice of Messrs Raybould and Napier, I feel confident that containsObject is the way to go.
Answer: Neither. You should use an NSFetchRequest with a predicate. Your patterns can accidentally fault the entire relationship, which is very expensive and not needed just to check for whether it contains one object. There are ways to be careful and not fault the entire relationship, but it's fragile (small changes to your search lead to huge changes in performance) and so it's better to be in the habit of using NSFetchRequest rather than the collection for searching. I like to set my fetchLimit to 1 in these cases so once it finds it, it stops looking.
For convenience, you may want to create a -containsFoo: method on your managed object so you don't have to write the fetch logic all over the place.
Your two solutions above are subtly different. The first one tests whether there is an object in the collection that isEqual: to itemOfInterest. Your second solution tests whether there is an object in the collection at the same memory location as itemOfInterest. For objects with custom isEqual: logic, these can return different results. This means that solution 2 might be slightly faster for non-core data collections, but it's because you're actually testing a different thing, not because of object enumeration. (In reality, this is only true for small collections; see below.)
Why do you believe that solution 1 uses -objectEnumerator?
As @James Raybould points out, you generally should not try to rewrite the built-in methods for performance reasons. If an isEqual: version of Solution 2 were faster than Solution 1, wouldn't you think Apple would have implemented -containsObject: using the code in solution 2?
In reality, the underlying CFSet is implemented as a hash, so checking for containment is logarithmic rather than linear. Generally speaking, for large sets with reasonable hash functions, solution 1 will be faster. See the code for it in CFSet.c. Look for CFSetContainsValue(). CFSet's implementation isn't guaranteed to stay the same, of course, but it's useful for understanding how performance concerns are generally addressed within Cocoa.
Comment: Ignore my comment - this is easily one of the best answers I've ever read!
Comment: Thanks for your in-depth response. I learned a lot from it.
The search in question is performed on a selection of managed objects in a table, the contents of which are themselves the result of a particular fetch request. So I really do need to work with cached objects, rather than running another fetch. (I do use a fetch with a "predicateWithFormat:@"ANY items == %@", itemSelected" when pulling objects out from the store based on this to-many relationship.)
Comment: Your situation sounds reasonable, and `containsObject:` is your best bet here as James notes. You're correct that you shouldn't fetch *again*. And `containsObject:` uses `hash` and `isEqual:` which are documented to not fault (you should never override these methods for an `NSManagedObject`).
Answer: I'd always go for option 1.
Its more concise, I can tell exactly what your trying to do with the code and chances are that the containsObject contains some pretty nifty optimisations.

Which is better, NSSet’s containsObject or fast enum?


Django change the way date field is displayed in django admin

Question: That's it i want to change the way its displayed cause it says "noon" or "midnight" and i want i to display the exact hour
I've got this code on the field
date = models.DateTimeField(auto_now_add=True, default=datetime.date.today())

Answer: You have 3 options.

Override DATETIME_FORMAT, read here: datetime format
Use a form for your model and in the date attribute have some like this(
in input format, put whatrever you want):
date = forms.DateTimeField(input_format="%b %d %Y %I:%M%p")
Or just change the way you render your datetime field in the template:
{{ your_model.date_field|date:'Y-m-d H:i' }}


I want to use curl into curl-php

Question: I used below code to fetch all links from given url. It works well but I want to fetch all mailto link and
 tags for each link. can I use curl into curl? I don't know much about curl. How to do this?
<?php
        $request_url ='http://example.com';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $request_url);    // The url to get links from
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // We want to get the respone
        $result = curl_exec($ch);

        $regex='|

Comment: DOMmmmmmmmmmmm with cURL, not cURL into cURL
Comment: i can't understand your question. can you explain more! as i see, you allready have all the links just check them against another regular expression and retrive mailito links!
Comment: it fetches all links but i want all links and for each link i wan to fetch  tags and tags.
Answer: you need to parse the returned html (dom) for the links, not another curl request

I want to use curl into curl-php


Addition, Add Multiple textbox using Javascript function

Question: I have this problem that I add 8 textbox and it works fine but when i add more textbox like 16 textbox it doesnt add the last textbox. does anyone encoutered this problem? Thanks in Advance.
Live Link: JAVASCRIPT.
function sum() {

        var basicpay = document.getElementById('basicpay').value;
        var overtime = document.getElementById('overtime').value;
        var regularholiday = document.getElementById('regularholiday').value;
        var specialholiday = document.getElementById('specialholiday').value;
        var allowanceday = document.getElementById('allowanceday').value;
        var others = document.getElementById('others').value;
        var grosspay = document.getElementById('grosspay').value;
        var monthpay13 = document.getElementById('monthpay13').value;
        var absent = document.getElementById('absent').value;
        var tardiness = document.getElementById('tardiness').value;
        var sss = document.getElementById('sss').value;
        var pagibig = document.getElementById('pagibig').value;
        var philhealth = document.getElementById('philhealth').value;
        var cashadvances = document.getElementById('cashadvances').value;
        var withholdingtax = document.getElementById('withholdingtax').value;
        var others = document.getElementById('others').value;

        var result =

        parseInt(basicpay) +
        parseInt(overtime) +
        parseInt(regularholiday) +
        parseInt(specialholiday) +
        parseInt(allowanceday) +
        parseInt(others) +
        parseInt(grosspay) +
        parseInt(absent) +
        parseInt(tardiness) +
        parseInt(sss) +
        parseInt(pagibig) +
        parseInt(philhealth) +
        parseInt(cashadvances) +
        parseInt(withholdingtax) +
        parseInt(others) +
        parseInt(monthpay13);

        if (!isNaN(result)) {
            document.getElementById('totalincome').value = result;
        }
        }

Comment: Why are you setting `others` twice and adding it two times in the `result` formula?
Answer: The problem is that you're using the same ID others for field 6 and field 16. Give them different IDs
16.<input type="text" id="others1" Placeholder="More others"  onkeyup="sum();" />

And change the JS:
var others1 = var others = document.getElementById('others1').value;

var result =

parseInt(basicpay) +
parseInt(overtime) +
parseInt(regularholiday) +
parseInt(specialholiday) +
parseInt(allowanceday) +
parseInt(others) +
parseInt(grosspay) +
parseInt(absent) +
parseInt(tardiness) +
parseInt(sss) +
parseInt(pagibig) +
parseInt(philhealth) +
parseInt(cashadvances) +
parseInt(withholdingtax) +
parseInt(others1) +
parseInt(monthpay13);

Answer: I think that problem is because your 6 and 16 number textbox has same ID.
Change your ID of textbox number 16 and It should work.
Comment: HAHAHAHAHA! NICE ONE SIR! CASE CLOSE! Thanks Alot guys!
Answer: The issue happens on the very last field. This is caused by the fact that you have two boxes with the same ID. To fix that change the last box ID from others to others2. And also change your variable called others to others2 because there are two variables called others


Need help connecting C wire please model GSX16S481AA

Question: I had this unit put in about 3 years ago and have had so many issues with thermostats. Can someone help me identify where to place the c wire? It is available behind thermostat but not plugged in. Thank you so much
UPDATE: The pictures I posted originally showed C hooked up, but I came to find out that was actually Y, and I moved it to the correct terminal. I now need to know what transformer to connect the back of C to, and do I need to add the wire or should it be somewhere in front of me for me to simply plug in? Thank you for all your help
Comment: find the 24 volt transformer, the C wire is on it
Comment: Would you consider helping me for compensation? I want to get this done and I know it is simpler than what it looks like but my brain just won't understand any of the diagrams I'm looking at ♂
Answer: Your thermostat cable has a yellow wire connected to the C terminal of the system.   It also has a blue wire (normally used for C) not connected to the system.
I emphasize cable because we don't know what the yellow (and blue, and all the other) wires are connected to at the other end at the thermostat.
It does look like the C terminal on your system is connected by a blue wire to the common side of the transformer ... I can't be sure from the jumble of wires but I think so.   So the normal way to do it would be the blue wire connects that to the C terminal on your thermostat.
There are lots of articles telling you what's normal.  You should probably just follow one of them methodicaly.  Your system, unlike many, seems to have all the necessary terminals and your thermostat cable has all the necessary wires.
Comment: No.  Connect each colored wire to the appropriate terminal*at both ends* according to the manuals or a good online tutorial.
Comment: So just connect the blue wire with the yellow wire already in c?
Comment: Got it. Was hoping the answer was simpler than you telling me to research, as I have no clue what is what but r&r is simple.. thank you for your response
Comment: I am willing to pay for assistance in figuring out these wires. Via Zelle or PayPal to a verified member of this online community, thank you
Comment: Okay so never mind on the C and Y mixup, I had to undo it. So I guess my system just doesn't have the Y connected. I'm so lost
Answer: For time been ignore the electric schematics.
On you pic 1 and 2 is the 24 Volt transformer in top right corner. It shall have 4 wires. Two on one side and two on the other side. 2 wires are input (thus 120 Volt), and two wires are output, thus 24 volt. Turn off power to the AC and do not touch anything.
There is a bar with letters and screws. From left is R which is the 24 Volt from Transformer to the thermostat, then there is C which is the common wire, Then there is G which is for the fan and so on.
Your C tab has a yellow wire that goes to the thermostat. Find it at the thermostat and connect it to the C-tab on thermostat.
Remove the thermostat and inspect how many wires are in that cable.
Comment: Okay, so the C wire was actually the Y. I made the switch. So the big mistery for me now is the C wire - what transformer to connect it to and do I need to add the wire or is it already there? Uploading pics so you see what I mean. Thank you for all your help
Comment: Also, thermostat does have 5 wires. The Blue is tucked away waiting for me to use (C wire)