Add skip attribute for CayleyClient send test.

--- tests/test_cayley_client.py
+++ tests/test_cayley_client.py
@@ -1,8 +1,10 @@
 from unittest import TestCase
+import unittest
 from pyley import CayleyClient, GraphObject

 class CayleyClientTests(TestCase):
+    @unittest.skip('Disabled for now!')
     def test_send(self):
         client = CayleyClient()
         g = GraphObject()

<|original_code|>
from unittest import TestCase
from pyley import CayleyClient, GraphObject

class CayleyClientTests(TestCase):
    def test_send(self):
        client = CayleyClient()
        g = GraphObject()
        query = g.V().Has("name", "Casablanca") \
            .Out("/film/film/starring") \
            .Out("/film/performance/actor") \
            .Out("name") \
            .All()
        response = client.Send(query)

        print response.result

        self.assertTrue(response.r.status_code == 200)
        self.assertTrue(response.r is not None)
        self.assertTrue(len(response.result) > 0)

<|edits_diff|>
--- tests/test_cayley_client.py
+++ tests/test_cayley_client.py
@@ -1,4 +1,5 @@
 from unittest import TestCase
+import unittest
 from pyley import CayleyClient, GraphObject

<|current_version|>
from unittest import TestCase
import unittest
from pyley import CayleyClient, GraphObject

class CayleyClientTests(TestCase):
    def test_send(self):
        client = CayleyClient()
        g = GraphObject()
        query = g.V().Has("name", "Casablanca") \
            .Out("/film/film/starring") \
            .Out("/film/performance/actor") \
            .Out("name") \
            .All()
        response = client.Send(query)

        print response.result

        self.assertTrue(response.r.status_code == 200)
        self.assertTrue(response.r is not None)
        self.assertTrue(len(response.result) > 0)

<|next_version|>
from unittest import TestCase
import unittest
from pyley import CayleyClient, GraphObject

class CayleyClientTests(TestCase):
    @unittest.skip('Disabled for now!')
    def test_send(self):
        client = CayleyClient()
        g = GraphObject()
        query = g.V().Has("name", "Casablanca") \
            .Out("/film/film/starring") \
            .Out("/film/performance/actor") \
            .Out("name") \
            .All()
        response = client.Send(query)

        print response.result

        self.assertTrue(response.r.status_code == 200)
        self.assertTrue(response.r is not None)
        self.assertTrue(len(response.result) > 0)


Raise an error if the user doesn't have a _config.py

This raises a less cryptic error.

--- source/cytoplasm/configuration.py
+++ source/cytoplasm/configuration.py
@@ -1,6 +1,7 @@
 # This module contains the user's configurations, to be accessed like:
 # `print cytoplasm.configuration.build_dir`
 import os, imp
+from .errors import CytoplasmError

 # If the user has a file called _config.py, import that.
 # The user's _config.py should "from cytoplasm.defaults import *" if they want to use
@@ -8,3 +9,5 @@
 if os.path.exists("_config.py"):
     imp.load_source("_config", "_config.py")
     from _config import *
+else:
+    raise CytoplasmError("You don't seem to have a configuration file at '_config.py'.")

<|original_code|>
# This module contains the user's configurations, to be accessed like:
# `print cytoplasm.configuration.build_dir`
import os, imp

# If the user has a file called _config.py, import that.
# The user's _config.py should "from cytoplasm.defaults import *" if they want to use
# some of the defaults.
if os.path.exists("_config.py"):
    imp.load_source("_config", "_config.py")
    from _config import *

<|edits_diff|>
--- source/cytoplasm/configuration.py
+++ source/cytoplasm/configuration.py
@@ -1,6 +1,7 @@
 # This module contains the user's configurations, to be accessed like:
 # `print cytoplasm.configuration.build_dir`
 import os, imp
+from .errors import CytoplasmError

 # If the user has a file called _config.py, import that.
 # The user's _config.py should "from cytoplasm.defaults import *" if they want to use
<|current_version|>
# This module contains the user's configurations, to be accessed like:
# `print cytoplasm.configuration.build_dir`
import os, imp
from .errors import CytoplasmError

# If the user has a file called _config.py, import that.
# The user's _config.py should "from cytoplasm.defaults import *" if they want to use
# some of the defaults.
if os.path.exists("_config.py"):
    imp.load_source("_config", "_config.py")
    from _config import *

<|next_version|>
# This module contains the user's configurations, to be accessed like:
# `print cytoplasm.configuration.build_dir`
import os, imp
from .errors import CytoplasmError

# If the user has a file called _config.py, import that.
# The user's _config.py should "from cytoplasm.defaults import *" if they want to use
# some of the defaults.
if os.path.exists("_config.py"):
    imp.load_source("_config", "_config.py")
    from _config import *
else:
    raise CytoplasmError("You don't seem to have a configuration file at '_config.py'.")


Update test suite generator to import tests in source_test.

--- tests/test_suite.py
+++ tests/test_suite.py
@@ -15,6 +15,7 @@
 import unittest

 from . import downloader_test
+from . import source_test

 def suite():
     """ Return a test suite.
@@ -22,6 +23,7 @@
     loader = unittest.TestLoader()
     res = unittest.TestSuite()
     res.addTest(loader.loadTestsFromModule(downloader_test))
+    res.addTest(loader.loadTestsFromModule(source_test))
     return res

<|original_code|>
#! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest

from . import downloader_test

def suite():
    """ Return a test suite.
    """
    loader = unittest.TestLoader()
    res = unittest.TestSuite()
    res.addTest(loader.loadTestsFromModule(downloader_test))
    return res

def main():
    """ The main function.

    Returns:
      exit code.
    """
    try:
        res = unittest.TextTestRunner(verbosity=2).run(suite())
    except KeyboardInterrupt:
        return -1
    else:
        return 0 if res.wasSuccessful() else 1

if __name__ == "__main__":
    sys.exit(main())

<|edits_diff|>
--- tests/test_suite.py
+++ tests/test_suite.py
@@ -15,6 +15,7 @@
 import unittest

 from . import downloader_test
+from . import source_test

 def suite():
     """ Return a test suite.
<|current_version|>
#! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest

from . import downloader_test
from . import source_test

def suite():
    """ Return a test suite.
    """
    loader = unittest.TestLoader()
    res = unittest.TestSuite()
    res.addTest(loader.loadTestsFromModule(downloader_test))
    return res

def main():
    """ The main function.

    Returns:
      exit code.
    """
    try:
        res = unittest.TextTestRunner(verbosity=2).run(suite())
    except KeyboardInterrupt:
        return -1
    else:
        return 0 if res.wasSuccessful() else 1

if __name__ == "__main__":
    sys.exit(main())

<|next_version|>
#! /usr/bin/env python
#
# test_suite.py
#
# Copyright (c) 2015-2016 Junpei Kawamoto
#
# This software is released under the MIT License.
#
# http://opensource.org/licenses/mit-license.php
#
""" Test suite.
"""
from __future__ import absolute_import
import sys
import unittest

from . import downloader_test
from . import source_test

def suite():
    """ Return a test suite.
    """
    loader = unittest.TestLoader()
    res = unittest.TestSuite()
    res.addTest(loader.loadTestsFromModule(downloader_test))
    res.addTest(loader.loadTestsFromModule(source_test))
    return res

def main():
    """ The main function.

    Returns:
      exit code.
    """
    try:
        res = unittest.TextTestRunner(verbosity=2).run(suite())
    except KeyboardInterrupt:
        return -1
    else:
        return 0 if res.wasSuccessful() else 1

if __name__ == "__main__":
    sys.exit(main())


Trim down merge verbosity to avoid overly large log files.

--- lobster/cmssw/data/merge_cfg.py
+++ lobster/cmssw/data/merge_cfg.py
@@ -6,9 +6,14 @@

 options = VarParsing('analysis')
 options.register('output', mytype=VarParsing.varType.string)
+options.register('loginterval', 1000, mytype=VarParsing.varType.int)
 options.parseArguments()

 process = cms.Process("PickEvent")
+
+process.load('FWCore.MessageService.MessageLogger_cfi')
+process.MessageLogger.cerr.FwkReport.reportEvery = options.loginterval
+
 process.source = cms.Source ("PoolSource",
         fileNames = cms.untracked.vstring(''),
         duplicateCheckMode = cms.untracked.string('noDuplicateCheck')

<|original_code|>
import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys

options = VarParsing('analysis')
options.register('output', mytype=VarParsing.varType.string)
options.parseArguments()

process = cms.Process("PickEvent")
process.source = cms.Source ("PoolSource",
        fileNames = cms.untracked.vstring(''),
        duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
)

process.out = cms.OutputModule("PoolOutputModule",
        fileName = cms.untracked.string(options.output)
)

process.end = cms.EndPath(process.out)

<|edits_diff|>
--- lobster/cmssw/data/merge_cfg.py
+++ lobster/cmssw/data/merge_cfg.py
@@ -6,6 +6,7 @@

 options = VarParsing('analysis')
 options.register('output', mytype=VarParsing.varType.string)
+options.register('loginterval', 1000, mytype=VarParsing.varType.int)
 options.parseArguments()

 process = cms.Process("PickEvent")
<|current_version|>
import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys

options = VarParsing('analysis')
options.register('output', mytype=VarParsing.varType.string)
options.register('loginterval', 1000, mytype=VarParsing.varType.int)
options.parseArguments()

process = cms.Process("PickEvent")
process.source = cms.Source ("PoolSource",
        fileNames = cms.untracked.vstring(''),
        duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
)

process.out = cms.OutputModule("PoolOutputModule",
        fileName = cms.untracked.string(options.output)
)

process.end = cms.EndPath(process.out)

<|next_version|>
import FWCore.ParameterSet.Config as cms
from FWCore.ParameterSet.VarParsing import VarParsing
import subprocess
import os
import sys

options = VarParsing('analysis')
options.register('output', mytype=VarParsing.varType.string)
options.register('loginterval', 1000, mytype=VarParsing.varType.int)
options.parseArguments()

process = cms.Process("PickEvent")

process.load('FWCore.MessageService.MessageLogger_cfi')
process.MessageLogger.cerr.FwkReport.reportEvery = options.loginterval

process.source = cms.Source ("PoolSource",
        fileNames = cms.untracked.vstring(''),
        duplicateCheckMode = cms.untracked.string('noDuplicateCheck')
)

process.out = cms.OutputModule("PoolOutputModule",
        fileName = cms.untracked.string(options.output)
)

process.end = cms.EndPath(process.out)


Add fee_account to BuildingData of legacy test base

--- tests/fixtures/dummy/facilities.py
+++ tests/fixtures/dummy/facilities.py
@@ -4,6 +4,7 @@
 from fixture import DataSet

 from .address import AddressData
+from .finance import AccountData

 class SiteData(DataSet):
@@ -17,12 +18,14 @@
         street = "dummy"
         number = "01"
         short_name = "abc"
+        fee_account = AccountData.dummy_revenue

     class dummy_house2:
         site = SiteData.dummy
         street = "dummy"
         number = "02"
         short_name = "def"
+        fee_account = AccountData.dummy_revenue

 class RoomData(DataSet):

<|original_code|>
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet

from .address import AddressData

class SiteData(DataSet):
    class dummy:
        name = "dummy"

class BuildingData(DataSet):
    class dummy_house1:
        site = SiteData.dummy
        street = "dummy"
        number = "01"
        short_name = "abc"

    class dummy_house2:
        site = SiteData.dummy
        street = "dummy"
        number = "02"
        short_name = "def"

class RoomData(DataSet):
    class dummy_room1:
        number = "1"
        level = 1
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address1

    class dummy_room2:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house2
        address = AddressData.dummy_address2

    class dummy_room3:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address3

    class dummy_room4(dummy_room1):
        number = "2"
        address = AddressData.dummy_address4

    class dummy_room5(dummy_room1):
        number = "2"
        address = AddressData.dummy_address5

<|edits_diff|>
--- tests/fixtures/dummy/facilities.py
+++ tests/fixtures/dummy/facilities.py
@@ -4,6 +4,7 @@
 from fixture import DataSet

 from .address import AddressData
+from .finance import AccountData

 class SiteData(DataSet):
@@ -17,6 +18,7 @@
         street = "dummy"
         number = "01"
         short_name = "abc"
+        fee_account = AccountData.dummy_revenue

     class dummy_house2:
         site = SiteData.dummy
<|current_version|>
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet

from .address import AddressData
from .finance import AccountData

class SiteData(DataSet):
    class dummy:
        name = "dummy"

class BuildingData(DataSet):
    class dummy_house1:
        site = SiteData.dummy
        street = "dummy"
        number = "01"
        short_name = "abc"
        fee_account = AccountData.dummy_revenue

    class dummy_house2:
        site = SiteData.dummy
        street = "dummy"
        number = "02"
        short_name = "def"

class RoomData(DataSet):
    class dummy_room1:
        number = "1"
        level = 1
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address1

    class dummy_room2:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house2
        address = AddressData.dummy_address2

    class dummy_room3:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address3

    class dummy_room4(dummy_room1):
        number = "2"
        address = AddressData.dummy_address4

    class dummy_room5(dummy_room1):
        number = "2"
        address = AddressData.dummy_address5

<|next_version|>
# Copyright (c) 2015 The Pycroft Authors. See the AUTHORS file.
# This file is part of the Pycroft project and licensed under the terms of
# the Apache License, Version 2.0. See the LICENSE file for details.
from fixture import DataSet

from .address import AddressData
from .finance import AccountData

class SiteData(DataSet):
    class dummy:
        name = "dummy"

class BuildingData(DataSet):
    class dummy_house1:
        site = SiteData.dummy
        street = "dummy"
        number = "01"
        short_name = "abc"
        fee_account = AccountData.dummy_revenue

    class dummy_house2:
        site = SiteData.dummy
        street = "dummy"
        number = "02"
        short_name = "def"
        fee_account = AccountData.dummy_revenue

class RoomData(DataSet):
    class dummy_room1:
        number = "1"
        level = 1
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address1

    class dummy_room2:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house2
        address = AddressData.dummy_address2

    class dummy_room3:
        number = "2"
        level = 2
        inhabitable = True
        building = BuildingData.dummy_house1
        address = AddressData.dummy_address3

    class dummy_room4(dummy_room1):
        number = "2"
        address = AddressData.dummy_address4

    class dummy_room5(dummy_room1):
        number = "2"
        address = AddressData.dummy_address5


Disable non-critical logging in tests

Disable non-critical logging in tests

--- app/tests/settings.py
+++ app/tests/settings.py
@@ -1,3 +1,4 @@
+import logging
 import os

 # Set environment variables before importing settings
@@ -21,3 +22,6 @@
 TEMPLATE_DEBUG = False
 DEBUG_LOGGING = False
 THUMBNAIL_DEBUG = False
+
+# Disable non-critical logging in tests
+logging.disable(logging.CRITICAL)

<|original_code|>
import os

# Set environment variables before importing settings
os.environ["PROTECTED_S3_CUSTOM_DOMAIN"] = "testserver/media"

# noinspection PyUnresolvedReferences
from config.settings import *

""" Settings overrides for tests """

ALLOWED_HOSTS = [".testserver"]

WHITENOISE_AUTOREFRESH = True

PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]

EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

# Disable debugging in tests
DEBUG = False
TEMPLATE_DEBUG = False
DEBUG_LOGGING = False
THUMBNAIL_DEBUG = False

<|edits_diff|>
--- app/tests/settings.py
+++ app/tests/settings.py
@@ -1,3 +1,4 @@
+import logging
 import os

 # Set environment variables before importing settings
<|current_version|>
import logging
import os

# Set environment variables before importing settings
os.environ["PROTECTED_S3_CUSTOM_DOMAIN"] = "testserver/media"

# noinspection PyUnresolvedReferences
from config.settings import *

""" Settings overrides for tests """

ALLOWED_HOSTS = [".testserver"]

WHITENOISE_AUTOREFRESH = True

PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]

EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

# Disable debugging in tests
DEBUG = False
TEMPLATE_DEBUG = False
DEBUG_LOGGING = False
THUMBNAIL_DEBUG = False

<|next_version|>
import logging
import os

# Set environment variables before importing settings
os.environ["PROTECTED_S3_CUSTOM_DOMAIN"] = "testserver/media"

# noinspection PyUnresolvedReferences
from config.settings import *

""" Settings overrides for tests """

ALLOWED_HOSTS = [".testserver"]

WHITENOISE_AUTOREFRESH = True

PASSWORD_HASHERS = ["django.contrib.auth.hashers.MD5PasswordHasher"]

EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

# Disable debugging in tests
DEBUG = False
TEMPLATE_DEBUG = False
DEBUG_LOGGING = False
THUMBNAIL_DEBUG = False

# Disable non-critical logging in tests
logging.disable(logging.CRITICAL)


Add log to self play

Add log to self play

--- main.py
+++ main.py
@@ -1,7 +1,12 @@
 from game import Game
 from self_play import SelfPlay
+
+import game_stats_tree

 g = Game()

 runtime = SelfPlay(g)
 runtime.play()
+
+game_stats_tree = game_stats_tree.Node()
+update_game_stats(game_stats_tree, runtime.log)

<|original_code|>
from game import Game
from self_play import SelfPlay

g = Game()

runtime = SelfPlay(g)
runtime.play()

<|edits_diff|>
--- main.py
+++ main.py
@@ -1,5 +1,7 @@
 from game import Game
 from self_play import SelfPlay
+
+import game_stats_tree

 g = Game()

<|current_version|>
from game import Game
from self_play import SelfPlay

import game_stats_tree

g = Game()

runtime = SelfPlay(g)
runtime.play()

<|next_version|>
from game import Game
from self_play import SelfPlay

import game_stats_tree

g = Game()

runtime = SelfPlay(g)
runtime.play()

game_stats_tree = game_stats_tree.Node()
update_game_stats(game_stats_tree, runtime.log)


Check if song is_playing before play

Check if song is_playing before play

--- main.py
+++ main.py
@@ -13,7 +13,13 @@
     return itunes.quit()

+def is_playing(itunes):
+    return itunes.player_state.get() == k.playing
+
+
 def now_playing(itunes):
+    if not is_playing(itunes):
+        return play(itunes)
     track = itunes.current_track.get()
     return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
                                       track.artist(),
@@ -21,6 +27,8 @@

 def play(itunes):
+    if is_playing(itunes):
+        return play_next(itunes)
     itunes.play()
     return now_playing(itunes)

<|original_code|>
#!/usr/bin/env python3

import sys
from appscript import *
from termcolor import colored, cprint

def open(itunes):
    return itunes.activate()

def close(itunes):
    return itunes.quit()

def now_playing(itunes):
    track = itunes.current_track.get()
    return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
                                      track.artist(),
                                      track.album()))

def play(itunes):
    itunes.play()
    return now_playing(itunes)

def stop(itunes):
    return itunes.stop()

def main():
    cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
        app('System Events').processes[its.name == 'iTunes'].count(), \
        app('iTunes')

    if not is_open == 1:
        open(itunes)

    cmds = {
        'np': now_playing,
        'play': play,
        'show': open,
        'stop': stop,
        'close': close
    }
    cmd = cmds[cmd] if cmd in cmds else now_playing
    return cmd(itunes)

if __name__ == '__main__':
    main()

<|edits_diff|>
--- main.py
+++ main.py
@@ -13,7 +13,13 @@
     return itunes.quit()

+def is_playing(itunes):
+    return itunes.player_state.get() == k.playing
+
+
 def now_playing(itunes):
+    if not is_playing(itunes):
+        return play(itunes)
     track = itunes.current_track.get()
     return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
                                       track.artist(),
<|current_version|>
#!/usr/bin/env python3

import sys
from appscript import *
from termcolor import colored, cprint

def open(itunes):
    return itunes.activate()

def close(itunes):
    return itunes.quit()

def is_playing(itunes):
    return itunes.player_state.get() == k.playing

def now_playing(itunes):
    if not is_playing(itunes):
        return play(itunes)
    track = itunes.current_track.get()
    return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
                                      track.artist(),
                                      track.album()))

def play(itunes):
    itunes.play()
    return now_playing(itunes)

def stop(itunes):
    return itunes.stop()

def main():
    cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
        app('System Events').processes[its.name == 'iTunes'].count(), \
        app('iTunes')

    if not is_open == 1:
        open(itunes)

    cmds = {
        'np': now_playing,
        'play': play,
        'show': open,
        'stop': stop,
        'close': close
    }
    cmd = cmds[cmd] if cmd in cmds else now_playing
    return cmd(itunes)

if __name__ == '__main__':
    main()

<|next_version|>
#!/usr/bin/env python3

import sys
from appscript import *
from termcolor import colored, cprint

def open(itunes):
    return itunes.activate()

def close(itunes):
    return itunes.quit()

def is_playing(itunes):
    return itunes.player_state.get() == k.playing

def now_playing(itunes):
    if not is_playing(itunes):
        return play(itunes)
    track = itunes.current_track.get()
    return print('{} - {}\n{}'.format(colored(track.name(), attrs=['bold']),
                                      track.artist(),
                                      track.album()))

def play(itunes):
    if is_playing(itunes):
        return play_next(itunes)
    itunes.play()
    return now_playing(itunes)

def stop(itunes):
    return itunes.stop()

def main():
    cmd, is_open, itunes = None if len(sys.argv) == 1 else sys.argv[1], \
        app('System Events').processes[its.name == 'iTunes'].count(), \
        app('iTunes')

    if not is_open == 1:
        open(itunes)

    cmds = {
        'np': now_playing,
        'play': play,
        'show': open,
        'stop': stop,
        'close': close
    }
    cmd = cmds[cmd] if cmd in cmds else now_playing
    return cmd(itunes)

if __name__ == '__main__':
    main()


Clean up the description for PyPI

Clean up the description for PyPI

--- setup.py
+++ setup.py
@@ -1,4 +1,5 @@
 import sys
+import re

 if sys.version < '3.4':
     print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
@@ -8,6 +9,9 @@

 with open('README.md') as f:
     description = f.read()
+    description = re.sub(r'\[!\[.+\].+\]\(.+\)', '', description)
+    description = '\n'.join(description.splitlines()[2:])
+    description = re.sub('\n{2,}', '\n\n', description).strip()

 from circle_asset.version import VERSION, SHORT_DESCRIPTION

<|original_code|>
import sys

if sys.version < '3.4':
    print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
    exit(1)

from setuptools import setup, find_packages

with open('README.md') as f:
    description = f.read()

from circle_asset.version import VERSION, SHORT_DESCRIPTION

setup(name='circle-asset',
      version=VERSION,
      description=SHORT_DESCRIPTION,
      author='Alistair Lynn',
      author_email='arplynn@gmail.com',
      license="MIT",
      long_description=description,
      url='https://github.com/prophile/circle-asset',
      zip_safe=True,
      setup_requires=['nose >=1, <2'],
      install_requires=[
          'requests >=2.5, <3'
      ],
      entry_points={'console_scripts': [
          'circle-asset=circle_asset.cli:main'
      ]},
      packages=find_packages(),
      test_suite='nose.collector')

<|edits_diff|>
--- setup.py
+++ setup.py
@@ -1,4 +1,5 @@
 import sys
+import re

 if sys.version < '3.4':
     print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
<|current_version|>
import sys
import re

if sys.version < '3.4':
    print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
    exit(1)

from setuptools import setup, find_packages

with open('README.md') as f:
    description = f.read()

from circle_asset.version import VERSION, SHORT_DESCRIPTION

setup(name='circle-asset',
      version=VERSION,
      description=SHORT_DESCRIPTION,
      author='Alistair Lynn',
      author_email='arplynn@gmail.com',
      license="MIT",
      long_description=description,
      url='https://github.com/prophile/circle-asset',
      zip_safe=True,
      setup_requires=['nose >=1, <2'],
      install_requires=[
          'requests >=2.5, <3'
      ],
      entry_points={'console_scripts': [
          'circle-asset=circle_asset.cli:main'
      ]},
      packages=find_packages(),
      test_suite='nose.collector')

<|next_version|>
import sys
import re

if sys.version < '3.4':
    print('Sorry, this is not a compatible version of Python. Use 3.4 or later.')
    exit(1)

from setuptools import setup, find_packages

with open('README.md') as f:
    description = f.read()
    description = re.sub(r'\[!\[.+\].+\]\(.+\)', '', description)
    description = '\n'.join(description.splitlines()[2:])
    description = re.sub('\n{2,}', '\n\n', description).strip()

from circle_asset.version import VERSION, SHORT_DESCRIPTION

setup(name='circle-asset',
      version=VERSION,
      description=SHORT_DESCRIPTION,
      author='Alistair Lynn',
      author_email='arplynn@gmail.com',
      license="MIT",
      long_description=description,
      url='https://github.com/prophile/circle-asset',
      zip_safe=True,
      setup_requires=['nose >=1, <2'],
      install_requires=[
          'requests >=2.5, <3'
      ],
      entry_points={'console_scripts': [
          'circle-asset=circle_asset.cli:main'
      ]},
      packages=find_packages(),
      test_suite='nose.collector')


[trunk] Add option to Python line ending conversion to specify a single filename on the command line

--- python/convert_line_endings.py
+++ python/convert_line_endings.py
@@ -1,6 +1,7 @@
 #!/usr/bin/python

 import os
+import sys

 def convert_line_endings(file):
   if '\r\n' in open(file, 'rb').read():
@@ -12,6 +13,9 @@
       outfile.write(text)

 def main():
+  if len(sys.argv) > 1:
+    convert_line_endings(sys.argv[1])
+    return
   for dirpath, dirnames, filenames in os.walk('.'):
     for file in filenames:
       if os.path.splitext(file)[1] == '.cs':

<|original_code|>
#!/usr/bin/python

import os

def convert_line_endings(file):
  if '\r\n' in open(file, 'rb').read():
    print '%s contains DOS line endings. Converting' % file
    with open(file, 'rb') as infile:
      text = infile.read()
      text = text.replace('\r\n', '\n')
    with open(file, 'wb') as outfile:
      outfile.write(text)

def main():
  for dirpath, dirnames, filenames in os.walk('.'):
    for file in filenames:
      if os.path.splitext(file)[1] == '.cs':
        csPath = os.path.join(dirpath, file)
        convert_line_endings(csPath)

if __name__ == "__main__":
  main()

<|edits_diff|>
--- python/convert_line_endings.py
+++ python/convert_line_endings.py
@@ -1,6 +1,7 @@
 #!/usr/bin/python

 import os
+import sys

 def convert_line_endings(file):
   if '\r\n' in open(file, 'rb').read():
<|current_version|>
#!/usr/bin/python

import os
import sys

def convert_line_endings(file):
  if '\r\n' in open(file, 'rb').read():
    print '%s contains DOS line endings. Converting' % file
    with open(file, 'rb') as infile:
      text = infile.read()
      text = text.replace('\r\n', '\n')
    with open(file, 'wb') as outfile:
      outfile.write(text)

def main():
  for dirpath, dirnames, filenames in os.walk('.'):
    for file in filenames:
      if os.path.splitext(file)[1] == '.cs':
        csPath = os.path.join(dirpath, file)
        convert_line_endings(csPath)

if __name__ == "__main__":
  main()

<|next_version|>
#!/usr/bin/python

import os
import sys

def convert_line_endings(file):
  if '\r\n' in open(file, 'rb').read():
    print '%s contains DOS line endings. Converting' % file
    with open(file, 'rb') as infile:
      text = infile.read()
      text = text.replace('\r\n', '\n')
    with open(file, 'wb') as outfile:
      outfile.write(text)

def main():
  if len(sys.argv) > 1:
    convert_line_endings(sys.argv[1])
    return
  for dirpath, dirnames, filenames in os.walk('.'):
    for file in filenames:
      if os.path.splitext(file)[1] == '.cs':
        csPath = os.path.join(dirpath, file)
        convert_line_endings(csPath)

if __name__ == "__main__":
  main()


Add a waffle flag for GraphQL.

Add a waffle flag for GraphQL.

--- mozillians/graphql/views.py
+++ mozillians/graphql/views.py
@@ -1,5 +1,7 @@
+from django.http import Http404
 from django.views.decorators.csrf import csrf_exempt

+import waffle
 from graphene_django.views import GraphQLView

@@ -9,4 +11,6 @@
     @csrf_exempt
     def dispatch(self, *args, **kwargs):
         """Override dispatch method to allow the use of multiple decorators."""
+        if not waffle.flag_is_active(self.request, 'enable_graphql'):
+            raise Http404()
         return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)

<|original_code|>
from django.views.decorators.csrf import csrf_exempt

from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""
        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)

<|edits_diff|>
--- mozillians/graphql/views.py
+++ mozillians/graphql/views.py
@@ -1,5 +1,7 @@
+from django.http import Http404
 from django.views.decorators.csrf import csrf_exempt

+import waffle
 from graphene_django.views import GraphQLView

<|current_version|>
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt

import waffle
from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""
        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)

<|next_version|>
from django.http import Http404
from django.views.decorators.csrf import csrf_exempt

import waffle
from graphene_django.views import GraphQLView

class MozilliansGraphQLView(GraphQLView):
    """Class Based View to handle GraphQL requests."""

    @csrf_exempt
    def dispatch(self, *args, **kwargs):
        """Override dispatch method to allow the use of multiple decorators."""
        if not waffle.flag_is_active(self.request, 'enable_graphql'):
            raise Http404()
        return super(MozilliansGraphQLView, self).dispatch(*args, **kwargs)


Add logging message when plugin fails to render custom panels

--- InvenTree/plugin/views.py
+++ InvenTree/plugin/views.py
@@ -1,3 +1,4 @@
+import logging
 import sys
 import traceback

@@ -7,6 +8,9 @@
 from error_report.models import Error

 from plugin.registry import registry
+
+
+logger = logging.getLogger('inventree')

 class InvenTreePluginViewMixin:
@@ -42,6 +46,8 @@
                     html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
                 )

+                logger.error(f"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'")
+
         return panels

     def get_context_data(self, **kwargs):

<|original_code|>
import sys
import traceback

from django.conf import settings
from django.views.debug import ExceptionReporter

from error_report.models import Error

from plugin.registry import registry

class InvenTreePluginViewMixin:
    """
    Custom view mixin which adds context data to the view,
    based on loaded plugins.

    This allows rendered pages to be augmented by loaded plugins.

    """

    def get_plugin_panels(self, ctx):
        """
        Return a list of extra 'plugin panels' associated with this view
        """

        panels = []

        for plug in registry.with_mixin('panel'):

            try:
                panels += plug.render_panels(self, self.request, ctx)
            except Exception:
                # Prevent any plugin error from crashing the page render
                kind, info, data = sys.exc_info()

                # Log the error to the database
                Error.objects.create(
                    kind=kind.__name__,
                    info=info,
                    data='\n'.join(traceback.format_exception(kind, info, data)),
                    path=self.request.path,
                    html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
                )

        return panels

    def get_context_data(self, **kwargs):
        """
        Add plugin context data to the view
        """

        ctx = super().get_context_data(**kwargs)

        if settings.PLUGINS_ENABLED:
            ctx['plugin_panels'] = self.get_plugin_panels(ctx)

        return ctx

<|edits_diff|>
--- InvenTree/plugin/views.py
+++ InvenTree/plugin/views.py
@@ -1,3 +1,4 @@
+import logging
 import sys
 import traceback

@@ -7,6 +8,9 @@
 from error_report.models import Error

 from plugin.registry import registry
+
+
+logger = logging.getLogger('inventree')

 class InvenTreePluginViewMixin:
<|current_version|>
import logging
import sys
import traceback

from django.conf import settings
from django.views.debug import ExceptionReporter

from error_report.models import Error

from plugin.registry import registry

logger = logging.getLogger('inventree')

class InvenTreePluginViewMixin:
    """
    Custom view mixin which adds context data to the view,
    based on loaded plugins.

    This allows rendered pages to be augmented by loaded plugins.

    """

    def get_plugin_panels(self, ctx):
        """
        Return a list of extra 'plugin panels' associated with this view
        """

        panels = []

        for plug in registry.with_mixin('panel'):

            try:
                panels += plug.render_panels(self, self.request, ctx)
            except Exception:
                # Prevent any plugin error from crashing the page render
                kind, info, data = sys.exc_info()

                # Log the error to the database
                Error.objects.create(
                    kind=kind.__name__,
                    info=info,
                    data='\n'.join(traceback.format_exception(kind, info, data)),
                    path=self.request.path,
                    html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
                )

        return panels

    def get_context_data(self, **kwargs):
        """
        Add plugin context data to the view
        """

        ctx = super().get_context_data(**kwargs)

        if settings.PLUGINS_ENABLED:
            ctx['plugin_panels'] = self.get_plugin_panels(ctx)

        return ctx

<|next_version|>
import logging
import sys
import traceback

from django.conf import settings
from django.views.debug import ExceptionReporter

from error_report.models import Error

from plugin.registry import registry

logger = logging.getLogger('inventree')

class InvenTreePluginViewMixin:
    """
    Custom view mixin which adds context data to the view,
    based on loaded plugins.

    This allows rendered pages to be augmented by loaded plugins.

    """

    def get_plugin_panels(self, ctx):
        """
        Return a list of extra 'plugin panels' associated with this view
        """

        panels = []

        for plug in registry.with_mixin('panel'):

            try:
                panels += plug.render_panels(self, self.request, ctx)
            except Exception:
                # Prevent any plugin error from crashing the page render
                kind, info, data = sys.exc_info()

                # Log the error to the database
                Error.objects.create(
                    kind=kind.__name__,
                    info=info,
                    data='\n'.join(traceback.format_exception(kind, info, data)),
                    path=self.request.path,
                    html=ExceptionReporter(self.request, kind, info, data).get_traceback_html(),
                )

                logger.error(f"Plugin '{plug.slug}' could not render custom panels at '{self.request.path}'")

        return panels

    def get_context_data(self, **kwargs):
        """
        Add plugin context data to the view
        """

        ctx = super().get_context_data(**kwargs)

        if settings.PLUGINS_ENABLED:
            ctx['plugin_panels'] = self.get_plugin_panels(ctx)

        return ctx


[Telemetry] Set facebook_crendentials_backend_2's url to https

TBR=tonyg@chromium.org

BUG=428098

Review URL: https://codereview.chromium.org/688113003

Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#301945}

--- telemetry/telemetry/core/backends/facebook_credentials_backend.py
+++ telemetry/telemetry/core/backends/facebook_credentials_backend.py
@@ -35,7 +35,12 @@
     return 'pass'

 class FacebookCredentialsBackend2(FacebookCredentialsBackend):
+  """ Facebook credential backend for https client. """

   @property
   def credentials_type(self):
     return 'facebook2'
+
+  @property
+  def url(self):
+    return 'https://www.facebook.com/'

<|original_code|>
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.core.backends import form_based_credentials_backend

class FacebookCredentialsBackend(
    form_based_credentials_backend.FormBasedCredentialsBackend):

  @property
  def logged_in_javascript(self):
    """Evaluates to true iff already logged in."""
    return ('document.getElementById("fbNotificationsList")!== null || '
            'document.getElementById("m_home_notice")!== null')

  @property
  def credentials_type(self):
    return 'facebook'

  @property
  def url(self):
    return 'http://www.facebook.com/'

  @property
  def login_form_id(self):
    return 'login_form'

  @property
  def login_input_id(self):
    return 'email'

  @property
  def password_input_id(self):
    return 'pass'

class FacebookCredentialsBackend2(FacebookCredentialsBackend):

  @property
  def credentials_type(self):
    return 'facebook2'

<|edits_diff|>
--- telemetry/telemetry/core/backends/facebook_credentials_backend.py
+++ telemetry/telemetry/core/backends/facebook_credentials_backend.py
@@ -35,6 +35,7 @@
     return 'pass'

 class FacebookCredentialsBackend2(FacebookCredentialsBackend):
+  """ Facebook credential backend for https client. """

   @property
   def credentials_type(self):
<|current_version|>
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.core.backends import form_based_credentials_backend

class FacebookCredentialsBackend(
    form_based_credentials_backend.FormBasedCredentialsBackend):

  @property
  def logged_in_javascript(self):
    """Evaluates to true iff already logged in."""
    return ('document.getElementById("fbNotificationsList")!== null || '
            'document.getElementById("m_home_notice")!== null')

  @property
  def credentials_type(self):
    return 'facebook'

  @property
  def url(self):
    return 'http://www.facebook.com/'

  @property
  def login_form_id(self):
    return 'login_form'

  @property
  def login_input_id(self):
    return 'email'

  @property
  def password_input_id(self):
    return 'pass'

class FacebookCredentialsBackend2(FacebookCredentialsBackend):
  """ Facebook credential backend for https client. """

  @property
  def credentials_type(self):
    return 'facebook2'

<|next_version|>
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

from telemetry.core.backends import form_based_credentials_backend

class FacebookCredentialsBackend(
    form_based_credentials_backend.FormBasedCredentialsBackend):

  @property
  def logged_in_javascript(self):
    """Evaluates to true iff already logged in."""
    return ('document.getElementById("fbNotificationsList")!== null || '
            'document.getElementById("m_home_notice")!== null')

  @property
  def credentials_type(self):
    return 'facebook'

  @property
  def url(self):
    return 'http://www.facebook.com/'

  @property
  def login_form_id(self):
    return 'login_form'

  @property
  def login_input_id(self):
    return 'email'

  @property
  def password_input_id(self):
    return 'pass'

class FacebookCredentialsBackend2(FacebookCredentialsBackend):
  """ Facebook credential backend for https client. """

  @property
  def credentials_type(self):
    return 'facebook2'

  @property
  def url(self):
    return 'https://www.facebook.com/'


Add unit test to pass Trigger instance.

Add unit test to pass Trigger instance.

--- tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py
+++ tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py
@@ -4,11 +4,14 @@

 from chainer import testing
 from chainer.training import extensions
+from chainer.training import trigger

 @testing.parameterize(
     {'trigger': ('epoch', 2)},
     {'trigger': ('iteration', 10)},
+    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
+    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
 )
 class TestSnapshotObject(unittest.TestCase):

@@ -22,6 +25,8 @@
 @testing.parameterize(
     {'trigger': ('epoch', 2)},
     {'trigger': ('iteration', 10)},
+    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
+    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
 )
 class TestSnapshot(unittest.TestCase):

<|original_code|>
import unittest

import mock

from chainer import testing
from chainer.training import extensions

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)

<|edits_diff|>
--- tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py
+++ tests/chainer_tests/training_tests/extensions_tests/test_snapshot.py
@@ -4,11 +4,14 @@

 from chainer import testing
 from chainer.training import extensions
+from chainer.training import trigger

 @testing.parameterize(
     {'trigger': ('epoch', 2)},
     {'trigger': ('iteration', 10)},
+    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
+    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
 )
 class TestSnapshotObject(unittest.TestCase):

<|current_version|>
import unittest

import mock

from chainer import testing
from chainer.training import extensions
from chainer.training import trigger

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)

<|next_version|>
import unittest

import mock

from chainer import testing
from chainer.training import extensions
from chainer.training import trigger

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshotObject(unittest.TestCase):

    def test_trigger(self):
        target = mock.MagicMock()
        snapshot_object = extensions.snapshot_object(target, 'myfile.dat',
                                                     trigger=self.trigger)
        self.assertEqual(snapshot_object.trigger, self.trigger)

@testing.parameterize(
    {'trigger': ('epoch', 2)},
    {'trigger': ('iteration', 10)},
    {'trigger': trigger.IntervalTrigger(5, 'epoch')},
    {'trigger': trigger.IntervalTrigger(20, 'iteration')},
)
class TestSnapshot(unittest.TestCase):

    def test_trigger(self):
        snapshot = extensions.snapshot(trigger=self.trigger)
        self.assertEqual(snapshot.trigger, self.trigger)

testing.run_module(__name__, __file__)


Update the pipeline to take into account the outlier rejection method to compute the RPP

--- pipeline/compute_rpp/compute_rpp.py
+++ pipeline/compute_rpp/compute_rpp.py
@@ -3,6 +3,7 @@
 import numpy as np

 from skcycling.utils import load_power_from_fit
+from skcycling.restoration import denoise
 from skcycling.power_profile import Rpp

 # The first input argument corresponding to the data path
@@ -26,6 +27,8 @@
     print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
     # Open the file
     power_ride = load_power_from_fit(filename)
+    # Reject the outliers using thresholding method
+    power_ride = denoise.outliers_rejection(power_ride)
     # Fit the ride
     rpp_rider.fit(power_ride)

<|original_code|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)

<|edits_diff|>
--- pipeline/compute_rpp/compute_rpp.py
+++ pipeline/compute_rpp/compute_rpp.py
@@ -3,6 +3,7 @@
 import numpy as np

 from skcycling.utils import load_power_from_fit
+from skcycling.restoration import denoise
 from skcycling.power_profile import Rpp

 # The first input argument corresponding to the data path
<|current_version|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)

<|next_version|>
import sys
import os
import numpy as np

from skcycling.utils import load_power_from_fit
from skcycling.restoration import denoise
from skcycling.power_profile import Rpp

# The first input argument corresponding to the data path
data_path = sys.argv[1]

# The second input argument is the storage directory
storage_path = sys.argv[2]

# We can create a list of all the *.fit files present inside that directory
# Create a list with the files to considered
filenames = []
for root, dirs, files in os.walk(data_path):
    for file in files:
        if file.endswith('.fit'):
            filenames.append(os.path.join(root, file))

max_duration_rpp = 30
rpp_rider = Rpp(max_duration_rpp=max_duration_rpp)
# Open each file and fit
for idx_file, filename in enumerate(filenames):
    print 'Process file #{} over {}'.format(idx_file+1, len(filenames))
    # Open the file
    power_ride = load_power_from_fit(filename)
    # Reject the outliers using thresholding method
    power_ride = denoise.outliers_rejection(power_ride)
    # Fit the ride
    rpp_rider.fit(power_ride)

# Create a directory to store the data if it is not existing
if not os.path.exists(storage_path):
    os.makedirs(storage_path)

# Store the data somewhere
np.save(os.path.join(storage_path, 'profile.npy'), rpp_rider.rpp_)


Use app logging instead of celery

Use app logging instead of celery

--- changes/jobs/sync_repo.py
+++ changes/jobs/sync_repo.py
@@ -1,4 +1,5 @@
 from datetime import datetime
+from flask import current_app

 from changes.config import db, queue
 from changes.models import Repository
@@ -49,6 +50,7 @@

     except Exception as exc:
         # should we actually use retry support here?
+        current_app.logger.exception('Failed to sync repository %s', repo_id)
         raise queue.retry('sync_repo', kwargs={
             'repo_id': repo_id,
         }, exc=exc, countdown=120)

<|original_code|>
from datetime import datetime

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)

<|edits_diff|>
--- changes/jobs/sync_repo.py
+++ changes/jobs/sync_repo.py
@@ -1,4 +1,5 @@
 from datetime import datetime
+from flask import current_app

 from changes.config import db, queue
 from changes.models import Repository
<|current_version|>
from datetime import datetime
from flask import current_app

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)

<|next_version|>
from datetime import datetime
from flask import current_app

from changes.config import db, queue
from changes.models import Repository

def sync_repo(repo_id):
    repo = Repository.query.get(repo_id)
    if not repo:
        return

    vcs = repo.get_vcs()
    if vcs is None:
        return

    repo.last_update_attempt = datetime.utcnow()
    db.session.add(repo)
    db.session.commit()

    try:
        if vcs.exists():
            vcs.update()
        else:
            vcs.clone()

        # TODO(dcramer): this doesnt scrape everything, and really we wouldn't
        # want to do this all in a single job so we should split this into a
        # backfill task
        might_have_more = True
        parent = None
        while might_have_more:
            might_have_more = False
            for commit in vcs.log(parent=parent):
                revision, created = commit.save(repo)
                db.session.commit()
                if not created:
                    break
                might_have_more = True
                parent = commit.id

        repo.last_update = datetime.utcnow()

        db.session.add(repo)
        db.session.commit()

        queue.delay('sync_repo', kwargs={
            'repo_id': repo_id
        }, countdown=15)

    except Exception as exc:
        # should we actually use retry support here?
        current_app.logger.exception('Failed to sync repository %s', repo_id)
        raise queue.retry('sync_repo', kwargs={
            'repo_id': repo_id,
        }, exc=exc, countdown=120)


Add dependencies to installer via requirements.txt

--- setup.py
+++ setup.py
@@ -3,6 +3,9 @@

 from setuptools import setup, find_packages

+# use requirements.txt for dependencies
+with open('requirements.txt') as f:
+    required = map(lambda s: s.strip(), f.readlines())

 with open('README.md') as f:
     readme = f.read()
@@ -15,6 +18,7 @@
     version='0.1.0',
     description='Webmention Manager',
     long_description=readme,
+    install_requires=required,
     author='Mike Taylor',
     author_email='bear@bear.im',
     url='https://github.com/bear/ronkyuu',

<|original_code|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup, find_packages

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='ronkyuu',
    version='0.1.0',
    description='Webmention Manager',
    long_description=readme,
    author='Mike Taylor',
    author_email='bear@bear.im',
    url='https://github.com/bear/ronkyuu',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)
<|edits_diff|>
--- setup.py
+++ setup.py
@@ -3,6 +3,9 @@

 from setuptools import setup, find_packages

+# use requirements.txt for dependencies
+with open('requirements.txt') as f:
+    required = map(lambda s: s.strip(), f.readlines())

 with open('README.md') as f:
     readme = f.read()
<|current_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup, find_packages

# use requirements.txt for dependencies
with open('requirements.txt') as f:
    required = map(lambda s: s.strip(), f.readlines())

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='ronkyuu',
    version='0.1.0',
    description='Webmention Manager',
    long_description=readme,
    author='Mike Taylor',
    author_email='bear@bear.im',
    url='https://github.com/bear/ronkyuu',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)
<|next_version|>
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup, find_packages

# use requirements.txt for dependencies
with open('requirements.txt') as f:
    required = map(lambda s: s.strip(), f.readlines())

with open('README.md') as f:
    readme = f.read()

with open('LICENSE') as f:
    license = f.read()

setup(
    name='ronkyuu',
    version='0.1.0',
    description='Webmention Manager',
    long_description=readme,
    install_requires=required,
    author='Mike Taylor',
    author_email='bear@bear.im',
    url='https://github.com/bear/ronkyuu',
    license=license,
    packages=find_packages(exclude=('tests', 'docs'))
)


Set the current language from the page

Set the current language from the page

--- views/base.py
+++ views/base.py
@@ -1,6 +1,7 @@
 from django.http import HttpResponseRedirect
 from django.shortcuts import render_to_response
 from django.template import RequestContext
+from django.utils import translation

 from feincms.models import Page

@@ -14,6 +15,9 @@
     if page.redirect_to:
         return HttpResponseRedirect(page.redirect_to)

+    translation.activate(page.language)
+    request.LANGUAGE_CODE = translation.get_language()
+
     return render_to_response(page.template.path, {
         'feincms_page': page,
         }, context_instance=RequestContext(request))

<|original_code|>
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext

from feincms.models import Page

def handler(request, path=None):
    if path is None:
        path = request.path

    page = Page.objects.page_for_path_or_404(path)

    if page.redirect_to:
        return HttpResponseRedirect(page.redirect_to)

    return render_to_response(page.template.path, {
        'feincms_page': page,
        }, context_instance=RequestContext(request))

<|edits_diff|>
--- views/base.py
+++ views/base.py
@@ -1,6 +1,7 @@
 from django.http import HttpResponseRedirect
 from django.shortcuts import render_to_response
 from django.template import RequestContext
+from django.utils import translation

 from feincms.models import Page

<|current_version|>
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import translation

from feincms.models import Page

def handler(request, path=None):
    if path is None:
        path = request.path

    page = Page.objects.page_for_path_or_404(path)

    if page.redirect_to:
        return HttpResponseRedirect(page.redirect_to)

    return render_to_response(page.template.path, {
        'feincms_page': page,
        }, context_instance=RequestContext(request))

<|next_version|>
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import translation

from feincms.models import Page

def handler(request, path=None):
    if path is None:
        path = request.path

    page = Page.objects.page_for_path_or_404(path)

    if page.redirect_to:
        return HttpResponseRedirect(page.redirect_to)

    translation.activate(page.language)
    request.LANGUAGE_CODE = translation.get_language()

    return render_to_response(page.template.path, {
        'feincms_page': page,
        }, context_instance=RequestContext(request))


Add extra fields to status info page

Add extra fields to status info page

--- mint/rest/api/models/__init__.py
+++ mint/rest/api/models/__init__.py
@@ -1,11 +1,21 @@
 from mint.rest.modellib import Model
 from mint.rest.modellib import fields

+class RMCUrlField(fields.CalculatedField):
+    def getValue(self, controller, request, class_, parent, value):
+        return request.getHostWithProtocol() + '/catalog'
+
+
 class RbuilderStatus(Model):
+    id            = fields.AbsoluteUrlField(isAttribute=True)
     version       = fields.CharField()
     conaryVersion = fields.CharField()
+    rmcService    = RMCUrlField()
     products      = fields.UrlField('products', None)
     users         = fields.UrlField('users', None)
+
+    def get_absolute_url(self):
+        return '',

 from mint.rest.api.models.members import *
 from mint.rest.api.models.users import *

<|original_code|>
from mint.rest.modellib import Model
from mint.rest.modellib import fields

class RbuilderStatus(Model):
    version       = fields.CharField()
    conaryVersion = fields.CharField()
    products      = fields.UrlField('products', None)
    users         = fields.UrlField('users', None)

from mint.rest.api.models.members import *
from mint.rest.api.models.users import *
from mint.rest.api.models.products import *
from mint.rest.api.models.productversions import *
from mint.rest.api.models.images import *
from mint.rest.api.models.repos import *

<|edits_diff|>
--- mint/rest/api/models/__init__.py
+++ mint/rest/api/models/__init__.py
@@ -1,9 +1,16 @@
 from mint.rest.modellib import Model
 from mint.rest.modellib import fields

+class RMCUrlField(fields.CalculatedField):
+    def getValue(self, controller, request, class_, parent, value):
+        return request.getHostWithProtocol() + '/catalog'
+
+
 class RbuilderStatus(Model):
+    id            = fields.AbsoluteUrlField(isAttribute=True)
     version       = fields.CharField()
     conaryVersion = fields.CharField()
+    rmcService    = RMCUrlField()
     products      = fields.UrlField('products', None)
     users         = fields.UrlField('users', None)

<|current_version|>
from mint.rest.modellib import Model
from mint.rest.modellib import fields

class RMCUrlField(fields.CalculatedField):
    def getValue(self, controller, request, class_, parent, value):
        return request.getHostWithProtocol() + '/catalog'

class RbuilderStatus(Model):
    id            = fields.AbsoluteUrlField(isAttribute=True)
    version       = fields.CharField()
    conaryVersion = fields.CharField()
    rmcService    = RMCUrlField()
    products      = fields.UrlField('products', None)
    users         = fields.UrlField('users', None)

from mint.rest.api.models.members import *
from mint.rest.api.models.users import *
from mint.rest.api.models.products import *
from mint.rest.api.models.productversions import *
from mint.rest.api.models.images import *
from mint.rest.api.models.repos import *

<|next_version|>
from mint.rest.modellib import Model
from mint.rest.modellib import fields

class RMCUrlField(fields.CalculatedField):
    def getValue(self, controller, request, class_, parent, value):
        return request.getHostWithProtocol() + '/catalog'

class RbuilderStatus(Model):
    id            = fields.AbsoluteUrlField(isAttribute=True)
    version       = fields.CharField()
    conaryVersion = fields.CharField()
    rmcService    = RMCUrlField()
    products      = fields.UrlField('products', None)
    users         = fields.UrlField('users', None)

    def get_absolute_url(self):
        return '',

from mint.rest.api.models.members import *
from mint.rest.api.models.users import *
from mint.rest.api.models.products import *
from mint.rest.api.models.productversions import *
from mint.rest.api.models.images import *
from mint.rest.api.models.repos import *


Include defaults in generated global args list.

--- scripts/generate_global_kwargs_doc.py
+++ scripts/generate_global_kwargs_doc.py
@@ -2,10 +2,13 @@

 from os import path

+from pyinfra.api import Config
 from pyinfra.api.operation_kwargs import OPERATION_KWARGS

 def build_global_kwargs_doc():
+    pyinfra_config = Config()
+
     this_dir = path.dirname(path.realpath(__file__))
     docs_dir = path.abspath(path.join(this_dir, '..', 'docs'))

@@ -21,6 +24,11 @@
             description = config
             if isinstance(config, dict):
                 description = config.get('description')
+                default = config.get('default')
+                if callable(default):
+                    default = default(pyinfra_config)
+                if default:
+                    key = '{0}={1}'.format(key, default)

             lines.append('    + ``{0}``: {1}'.format(key, description))

<|original_code|>
#!/usr/bin/env python

from os import path

from pyinfra.api.operation_kwargs import OPERATION_KWARGS

def build_global_kwargs_doc():
    this_dir = path.dirname(path.realpath(__file__))
    docs_dir = path.abspath(path.join(this_dir, '..', 'docs'))

    lines = []

    for category, kwarg_configs in OPERATION_KWARGS.items():
        if category is None:
            continue

        lines.append('{0}:'.format(category))

        for key, config in kwarg_configs.items():
            description = config
            if isinstance(config, dict):
                description = config.get('description')

            lines.append('    + ``{0}``: {1}'.format(key, description))

    module_filename = path.join(docs_dir, '_deploy_globals.rst')
    print('--> Writing {0}'.format(module_filename))

    out = '\n'.join(lines)

    with open(module_filename, 'w') as outfile:
        outfile.write(out)

if __name__ == '__main__':
    print('### Building global kwargs doc')
    build_global_kwargs_doc()

<|edits_diff|>
--- scripts/generate_global_kwargs_doc.py
+++ scripts/generate_global_kwargs_doc.py
@@ -2,10 +2,13 @@

 from os import path

+from pyinfra.api import Config
 from pyinfra.api.operation_kwargs import OPERATION_KWARGS

 def build_global_kwargs_doc():
+    pyinfra_config = Config()
+
     this_dir = path.dirname(path.realpath(__file__))
     docs_dir = path.abspath(path.join(this_dir, '..', 'docs'))

<|current_version|>
#!/usr/bin/env python

from os import path

from pyinfra.api import Config
from pyinfra.api.operation_kwargs import OPERATION_KWARGS

def build_global_kwargs_doc():
    pyinfra_config = Config()

    this_dir = path.dirname(path.realpath(__file__))
    docs_dir = path.abspath(path.join(this_dir, '..', 'docs'))

    lines = []

    for category, kwarg_configs in OPERATION_KWARGS.items():
        if category is None:
            continue

        lines.append('{0}:'.format(category))

        for key, config in kwarg_configs.items():
            description = config
            if isinstance(config, dict):
                description = config.get('description')

            lines.append('    + ``{0}``: {1}'.format(key, description))

    module_filename = path.join(docs_dir, '_deploy_globals.rst')
    print('--> Writing {0}'.format(module_filename))

    out = '\n'.join(lines)

    with open(module_filename, 'w') as outfile:
        outfile.write(out)

if __name__ == '__main__':
    print('### Building global kwargs doc')
    build_global_kwargs_doc()

<|next_version|>
#!/usr/bin/env python

from os import path

from pyinfra.api import Config
from pyinfra.api.operation_kwargs import OPERATION_KWARGS

def build_global_kwargs_doc():
    pyinfra_config = Config()

    this_dir = path.dirname(path.realpath(__file__))
    docs_dir = path.abspath(path.join(this_dir, '..', 'docs'))

    lines = []

    for category, kwarg_configs in OPERATION_KWARGS.items():
        if category is None:
            continue

        lines.append('{0}:'.format(category))

        for key, config in kwarg_configs.items():
            description = config
            if isinstance(config, dict):
                description = config.get('description')
                default = config.get('default')
                if callable(default):
                    default = default(pyinfra_config)
                if default:
                    key = '{0}={1}'.format(key, default)

            lines.append('    + ``{0}``: {1}'.format(key, description))

    module_filename = path.join(docs_dir, '_deploy_globals.rst')
    print('--> Writing {0}'.format(module_filename))

    out = '\n'.join(lines)

    with open(module_filename, 'w') as outfile:
        outfile.write(out)

if __name__ == '__main__':
    print('### Building global kwargs doc')
    build_global_kwargs_doc()


Add more expected star str

Add more expected star str

--- metafunctions/tests/test_star.py
+++ metafunctions/tests/test_star.py
@@ -28,11 +28,17 @@

         cmp = (a | b) | star(f)
         star_a = star(a)
+        merge_star = star(a+b)
+        chain_star = star(a|b)

         self.assertEqual(str(cmp), '(a | b | star(f))')
         self.assertEqual(str(star_a), 'star(a)')
         self.assertEqual(str(g), 'star(g)')
         self.assertEqual(str(h), 'h')
+        self.assertEqual(str(merge_star), 'star(a + b)')
+        self.assertEqual(str(h), 'star(a | b)')
+
+

 @node
 def a(x):

<|original_code|>
from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase

class TestUnit(BaseTestCase):
    def test_simple_star(self):
        @node
        def f(*args):
            return args

        cmp = (a | b) | star(f)
        self.assertEqual(cmp('_'), ('_', 'a', 'b'))

    def test_str_repr(self):
        @node
        def f(*args):
            return args

        @star
        @node
        def g(*x):
            return x

        @node
        @star
        def h(*x):
            return x

        cmp = (a | b) | star(f)
        star_a = star(a)

        self.assertEqual(str(cmp), '(a | b | star(f))')
        self.assertEqual(str(star_a), 'star(a)')
        self.assertEqual(str(g), 'star(g)')
        self.assertEqual(str(h), 'h')

@node
def a(x):
    return x + 'a'
@node
def b(x):
    return x + 'b'

<|edits_diff|>
--- metafunctions/tests/test_star.py
+++ metafunctions/tests/test_star.py
@@ -28,6 +28,8 @@

         cmp = (a | b) | star(f)
         star_a = star(a)
+        merge_star = star(a+b)
+        chain_star = star(a|b)

         self.assertEqual(str(cmp), '(a | b | star(f))')
         self.assertEqual(str(star_a), 'star(a)')
<|current_version|>
from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase

class TestUnit(BaseTestCase):
    def test_simple_star(self):
        @node
        def f(*args):
            return args

        cmp = (a | b) | star(f)
        self.assertEqual(cmp('_'), ('_', 'a', 'b'))

    def test_str_repr(self):
        @node
        def f(*args):
            return args

        @star
        @node
        def g(*x):
            return x

        @node
        @star
        def h(*x):
            return x

        cmp = (a | b) | star(f)
        star_a = star(a)
        merge_star = star(a+b)
        chain_star = star(a|b)

        self.assertEqual(str(cmp), '(a | b | star(f))')
        self.assertEqual(str(star_a), 'star(a)')
        self.assertEqual(str(g), 'star(g)')
        self.assertEqual(str(h), 'h')

@node
def a(x):
    return x + 'a'
@node
def b(x):
    return x + 'b'

<|next_version|>
from metafunctions.util import node, star
from metafunctions.tests.util import BaseTestCase

class TestUnit(BaseTestCase):
    def test_simple_star(self):
        @node
        def f(*args):
            return args

        cmp = (a | b) | star(f)
        self.assertEqual(cmp('_'), ('_', 'a', 'b'))

    def test_str_repr(self):
        @node
        def f(*args):
            return args

        @star
        @node
        def g(*x):
            return x

        @node
        @star
        def h(*x):
            return x

        cmp = (a | b) | star(f)
        star_a = star(a)
        merge_star = star(a+b)
        chain_star = star(a|b)

        self.assertEqual(str(cmp), '(a | b | star(f))')
        self.assertEqual(str(star_a), 'star(a)')
        self.assertEqual(str(g), 'star(g)')
        self.assertEqual(str(h), 'h')
        self.assertEqual(str(merge_star), 'star(a + b)')
        self.assertEqual(str(h), 'star(a | b)')

@node
def a(x):
    return x + 'a'
@node
def b(x):
    return x + 'b'


flask: Load asset bundles into webassets environment

--- skylines/__init__.py
+++ skylines/__init__.py
@@ -1,12 +1,17 @@
 from flask import Flask
 from flask.ext.babel import Babel
 from flask.ext.assets import Environment
+from webassets.loaders import PythonLoader

 def create_app():
     app = Flask(__name__, static_folder='public')
     babel = Babel(app)
+
+    bundles = PythonLoader('skylines.assets.bundles').load_bundles()
     assets = Environment(app)
+    assets.register(bundles)
+
     return app

 app = create_app()

<|original_code|>
from flask import Flask
from flask.ext.babel import Babel
from flask.ext.assets import Environment

def create_app():
    app = Flask(__name__, static_folder='public')
    babel = Babel(app)
    assets = Environment(app)
    return app

app = create_app()

import skylines.views

<|edits_diff|>
--- skylines/__init__.py
+++ skylines/__init__.py
@@ -1,11 +1,14 @@
 from flask import Flask
 from flask.ext.babel import Babel
 from flask.ext.assets import Environment
+from webassets.loaders import PythonLoader

 def create_app():
     app = Flask(__name__, static_folder='public')
     babel = Babel(app)
+
+    bundles = PythonLoader('skylines.assets.bundles').load_bundles()
     assets = Environment(app)
     return app

<|current_version|>
from flask import Flask
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader

def create_app():
    app = Flask(__name__, static_folder='public')
    babel = Babel(app)

    bundles = PythonLoader('skylines.assets.bundles').load_bundles()
    assets = Environment(app)
    return app

app = create_app()

import skylines.views

<|next_version|>
from flask import Flask
from flask.ext.babel import Babel
from flask.ext.assets import Environment
from webassets.loaders import PythonLoader

def create_app():
    app = Flask(__name__, static_folder='public')
    babel = Babel(app)

    bundles = PythonLoader('skylines.assets.bundles').load_bundles()
    assets = Environment(app)
    assets.register(bundles)

    return app

app = create_app()

import skylines.views


Make output data cleaner on the eyes :)

Make output data cleaner on the eyes :)

--- salt/runners/state.py
+++ salt/runners/state.py
@@ -12,10 +12,12 @@
     Execute an overstate sequence to orchestrate the executing of states
     over a group of systems
     '''
+    stage_num = 0
     overstate = salt.overstate.OverState(__opts__, env, os_fn)
     for stage in overstate.stages_iter():
         if isinstance(stage, dict):
             # This is highstate data
+            print('Stage execution results:')
             for key, val in stage.items():
                 salt.output.display_output(
                         {key: val},
@@ -23,7 +25,12 @@
                         opts=__opts__)
         elif isinstance(stage, list):
             # This is a stage
+            if stage_num == 0:
+                print('Executing the following Over State:')
+            else:
+                print('Executed Stage:')
             salt.output.display_output(stage, 'overstatestage', opts=__opts__)
+            stage_num += 1
     return overstate.over_run

 def show_stages(env='base', os_fn=None):

<|original_code|>
'''
Execute overstate functions
'''

# Import salt libs
import salt.overstate
import salt.output

def over(env='base', os_fn=None):
    '''
    Execute an overstate sequence to orchestrate the executing of states
    over a group of systems
    '''
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    for stage in overstate.stages_iter():
        if isinstance(stage, dict):
            # This is highstate data
            for key, val in stage.items():
                salt.output.display_output(
                        {key: val},
                        'highstate',
                        opts=__opts__)
        elif isinstance(stage, list):
            # This is a stage
            salt.output.display_output(stage, 'overstatestage', opts=__opts__)
    return overstate.over_run

def show_stages(env='base', os_fn=None):
    '''
    Display the stage data to be executed
    '''
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    salt.output.display_output(
            overstate.over,
            'overstatestage',
            opts=__opts__)
    return overstate.over

<|edits_diff|>
--- salt/runners/state.py
+++ salt/runners/state.py
@@ -12,10 +12,12 @@
     Execute an overstate sequence to orchestrate the executing of states
     over a group of systems
     '''
+    stage_num = 0
     overstate = salt.overstate.OverState(__opts__, env, os_fn)
     for stage in overstate.stages_iter():
         if isinstance(stage, dict):
             # This is highstate data
+            print('Stage execution results:')
             for key, val in stage.items():
                 salt.output.display_output(
                         {key: val},
@@ -23,6 +25,10 @@
                         opts=__opts__)
         elif isinstance(stage, list):
             # This is a stage
+            if stage_num == 0:
+                print('Executing the following Over State:')
+            else:
+                print('Executed Stage:')
             salt.output.display_output(stage, 'overstatestage', opts=__opts__)
     return overstate.over_run

<|current_version|>
'''
Execute overstate functions
'''

# Import salt libs
import salt.overstate
import salt.output

def over(env='base', os_fn=None):
    '''
    Execute an overstate sequence to orchestrate the executing of states
    over a group of systems
    '''
    stage_num = 0
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    for stage in overstate.stages_iter():
        if isinstance(stage, dict):
            # This is highstate data
            print('Stage execution results:')
            for key, val in stage.items():
                salt.output.display_output(
                        {key: val},
                        'highstate',
                        opts=__opts__)
        elif isinstance(stage, list):
            # This is a stage
            if stage_num == 0:
                print('Executing the following Over State:')
            else:
                print('Executed Stage:')
            salt.output.display_output(stage, 'overstatestage', opts=__opts__)
    return overstate.over_run

def show_stages(env='base', os_fn=None):
    '''
    Display the stage data to be executed
    '''
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    salt.output.display_output(
            overstate.over,
            'overstatestage',
            opts=__opts__)
    return overstate.over

<|next_version|>
'''
Execute overstate functions
'''

# Import salt libs
import salt.overstate
import salt.output

def over(env='base', os_fn=None):
    '''
    Execute an overstate sequence to orchestrate the executing of states
    over a group of systems
    '''
    stage_num = 0
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    for stage in overstate.stages_iter():
        if isinstance(stage, dict):
            # This is highstate data
            print('Stage execution results:')
            for key, val in stage.items():
                salt.output.display_output(
                        {key: val},
                        'highstate',
                        opts=__opts__)
        elif isinstance(stage, list):
            # This is a stage
            if stage_num == 0:
                print('Executing the following Over State:')
            else:
                print('Executed Stage:')
            salt.output.display_output(stage, 'overstatestage', opts=__opts__)
            stage_num += 1
    return overstate.over_run

def show_stages(env='base', os_fn=None):
    '''
    Display the stage data to be executed
    '''
    overstate = salt.overstate.OverState(__opts__, env, os_fn)
    salt.output.display_output(
            overstate.over,
            'overstatestage',
            opts=__opts__)
    return overstate.over


Add docstrings so that hubot can say what went wrong

--- cla_backend/apps/status/tests/smoketests.py
+++ cla_backend/apps/status/tests/smoketests.py
@@ -11,12 +11,14 @@
         pass

     def test_can_access_db(self):
+        "access the database"
         cursor = connection.cursor()
         cursor.execute('SELECT 1')
         row = cursor.fetchone()
         self.assertEqual(1, row[0])

     def test_can_access_celery(self):
+        "connect to SQS"
         if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
             conn = Celery('cla_backend').connection()
             conn.connect()

<|original_code|>
import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

<|edits_diff|>
--- cla_backend/apps/status/tests/smoketests.py
+++ cla_backend/apps/status/tests/smoketests.py
@@ -11,6 +11,7 @@
         pass

     def test_can_access_db(self):
+        "access the database"
         cursor = connection.cursor()
         cursor.execute('SELECT 1')
         row = cursor.fetchone()
<|current_version|>
import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()

<|next_version|>
import unittest

from celery import Celery
from django.conf import settings
from django.db import connection

class SmokeTests(unittest.TestCase):

    def setUp(self):
        pass

    def test_can_access_db(self):
        "access the database"
        cursor = connection.cursor()
        cursor.execute('SELECT 1')
        row = cursor.fetchone()
        self.assertEqual(1, row[0])

    def test_can_access_celery(self):
        "connect to SQS"
        if not getattr(settings, 'CELERY_ALWAYS_EAGER', False):
            conn = Celery('cla_backend').connection()
            conn.connect()
            conn.release()


Remove django.contrib.sites from admin interface

--- picaxe/urls.py
+++ picaxe/urls.py
@@ -1,5 +1,6 @@
 from django.conf.urls import patterns, include, url
 from django.contrib import admin
+from django.contrib.sites.models import Site

 urlpatterns = patterns('',
     # Examples:
@@ -9,3 +10,5 @@
     url(r'^admin/', include(admin.site.urls)),
     url(r'photologue/', include('photologue.urls', namespace='photologue')),
 )
+
+admin.site.unregister(Site)

<|original_code|>
from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'picaxe.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'photologue/', include('photologue.urls', namespace='photologue')),
)

<|edits_diff|>
--- picaxe/urls.py
+++ picaxe/urls.py
@@ -1,5 +1,6 @@
 from django.conf.urls import patterns, include, url
 from django.contrib import admin
+from django.contrib.sites.models import Site

 urlpatterns = patterns('',
     # Examples:
<|current_version|>
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.sites.models import Site

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'picaxe.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'photologue/', include('photologue.urls', namespace='photologue')),
)

<|next_version|>
from django.conf.urls import patterns, include, url
from django.contrib import admin
from django.contrib.sites.models import Site

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'picaxe.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'photologue/', include('photologue.urls', namespace='photologue')),
)

admin.site.unregister(Site)


Add blank lines according to hound

Add blank lines according to hound

--- panoptes_client/avatar.py
+++ panoptes_client/avatar.py
@@ -5,6 +5,7 @@
     LinkResolver,
 )
 from panoptes_client.project import Project
+

 class Avatar(PanoptesObject):
     _api_slug = 'avatar'
@@ -26,5 +27,6 @@
         print(avatar_response.raw)
         return avatar_response

+
 LinkResolver.register(Avatar)
 LinkResolver.register(Avatar, 'avatar')

<|original_code|>
from panoptes_client.panoptes import (
    Panoptes,
    PanoptesAPIException,
    PanoptesObject,
    LinkResolver,
)
from panoptes_client.project import Project

class Avatar(PanoptesObject):
    _api_slug = 'avatar'
    _link_slug = 'avatars'
    _edit_attributes = ()

    @classmethod
    def http_get(cls, path, params={}, headers={}):
        project = params.pop('project')
        # print()
        # print(Project.url(project.id))
        # print()

        avatar_response = Panoptes.client().get(
            Project.url(project.id) + cls.url(path),
            params,
            headers,
        )
        print(avatar_response.raw)
        return avatar_response

LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')

<|edits_diff|>
--- panoptes_client/avatar.py
+++ panoptes_client/avatar.py
@@ -5,6 +5,7 @@
     LinkResolver,
 )
 from panoptes_client.project import Project
+

 class Avatar(PanoptesObject):
     _api_slug = 'avatar'
<|current_version|>
from panoptes_client.panoptes import (
    Panoptes,
    PanoptesAPIException,
    PanoptesObject,
    LinkResolver,
)
from panoptes_client.project import Project

class Avatar(PanoptesObject):
    _api_slug = 'avatar'
    _link_slug = 'avatars'
    _edit_attributes = ()

    @classmethod
    def http_get(cls, path, params={}, headers={}):
        project = params.pop('project')
        # print()
        # print(Project.url(project.id))
        # print()

        avatar_response = Panoptes.client().get(
            Project.url(project.id) + cls.url(path),
            params,
            headers,
        )
        print(avatar_response.raw)
        return avatar_response

LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')

<|next_version|>
from panoptes_client.panoptes import (
    Panoptes,
    PanoptesAPIException,
    PanoptesObject,
    LinkResolver,
)
from panoptes_client.project import Project

class Avatar(PanoptesObject):
    _api_slug = 'avatar'
    _link_slug = 'avatars'
    _edit_attributes = ()

    @classmethod
    def http_get(cls, path, params={}, headers={}):
        project = params.pop('project')
        # print()
        # print(Project.url(project.id))
        # print()

        avatar_response = Panoptes.client().get(
            Project.url(project.id) + cls.url(path),
            params,
            headers,
        )
        print(avatar_response.raw)
        return avatar_response

LinkResolver.register(Avatar)
LinkResolver.register(Avatar, 'avatar')


Add docstring to instance methods

Add docstring to instance methods

--- mooc_aggregator_restful_api/udacity.py
+++ mooc_aggregator_restful_api/udacity.py
@@ -24,12 +24,27 @@
         self.tracks = self.response.json()['tracks']

     def status_code(self):
+        '''
+        Return status code of response object
+
+        '''
+
         return self.response.status_code

     def get_courses(self):
+        '''
+        Return list of course objects for all courses offered by Udacity
+
+        '''
+
         return self.courses

     def get_tracks(self):
+        '''
+        Return list of tracks offered by Udacity
+
+        '''
+
         return self.tracks

 if __name__ == '__main__':

<|original_code|>
'''
This module retrieves the course catalog and overviews of the Udacity API

Link to Documentation:
https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf

'''

import json
import requests

class UdacityAPI(object):
    '''
    This class defines attributes and methods for Udaciy API

    '''
    UDACITY_API_ENDPOINT = 'https://udacity.com/public-api/v0/courses'

    def __init__(self):
        self.response = requests.get(UDACITY_API_ENDPOINT)
        self.courses = self.response.json()['courses']
        self.tracks = self.response.json()['tracks']

    def status_code(self):
        return self.response.status_code

    def get_courses(self):
        return self.courses

    def get_tracks(self):
        return self.tracks

if __name__ == '__main__':
    udacity_object = UdacityAPI()
    print len(udacity_object.get_courses())
    print udacity_object.get_courses()[0].keys()

<|edits_diff|>
--- mooc_aggregator_restful_api/udacity.py
+++ mooc_aggregator_restful_api/udacity.py
@@ -24,9 +24,19 @@
         self.tracks = self.response.json()['tracks']

     def status_code(self):
+        '''
+        Return status code of response object
+
+        '''
+
         return self.response.status_code

     def get_courses(self):
+        '''
+        Return list of course objects for all courses offered by Udacity
+
+        '''
+
         return self.courses

     def get_tracks(self):
<|current_version|>
'''
This module retrieves the course catalog and overviews of the Udacity API

Link to Documentation:
https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf

'''

import json
import requests

class UdacityAPI(object):
    '''
    This class defines attributes and methods for Udaciy API

    '''
    UDACITY_API_ENDPOINT = 'https://udacity.com/public-api/v0/courses'

    def __init__(self):
        self.response = requests.get(UDACITY_API_ENDPOINT)
        self.courses = self.response.json()['courses']
        self.tracks = self.response.json()['tracks']

    def status_code(self):
        '''
        Return status code of response object

        '''

        return self.response.status_code

    def get_courses(self):
        '''
        Return list of course objects for all courses offered by Udacity

        '''

        return self.courses

    def get_tracks(self):
        return self.tracks

if __name__ == '__main__':
    udacity_object = UdacityAPI()
    print len(udacity_object.get_courses())
    print udacity_object.get_courses()[0].keys()

<|next_version|>
'''
This module retrieves the course catalog and overviews of the Udacity API

Link to Documentation:
https://s3.amazonaws.com/content.udacity-data.com/techdocs/UdacityCourseCatalogAPIDocumentation-v0.pdf

'''

import json
import requests

class UdacityAPI(object):
    '''
    This class defines attributes and methods for Udaciy API

    '''
    UDACITY_API_ENDPOINT = 'https://udacity.com/public-api/v0/courses'

    def __init__(self):
        self.response = requests.get(UDACITY_API_ENDPOINT)
        self.courses = self.response.json()['courses']
        self.tracks = self.response.json()['tracks']

    def status_code(self):
        '''
        Return status code of response object

        '''

        return self.response.status_code

    def get_courses(self):
        '''
        Return list of course objects for all courses offered by Udacity

        '''

        return self.courses

    def get_tracks(self):
        '''
        Return list of tracks offered by Udacity

        '''

        return self.tracks

if __name__ == '__main__':
    udacity_object = UdacityAPI()
    print len(udacity_object.get_courses())
    print udacity_object.get_courses()[0].keys()