commit
stringlengths 40
40
| old_file
stringlengths 4
118
| new_file
stringlengths 4
118
| old_contents
stringlengths 10
2.94k
| new_contents
stringlengths 21
3.18k
| subject
stringlengths 16
444
| message
stringlengths 17
2.63k
| lang
stringclasses 1
value | license
stringclasses 13
values | repos
stringlengths 5
43k
| ndiff
stringlengths 52
3.32k
| instruction
stringlengths 16
444
| content
stringlengths 133
4.32k
| fuzzy_diff
stringlengths 16
3.18k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d3bd1fe50806180c8fb6889b1bed28f602608d6 | couchdb/tests/__main__.py | couchdb/tests/__main__.py |
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
multipart, mapping, view, package, tools
def suite():
suite = unittest.TestSuite()
suite.addTest(client.suite())
suite.addTest(design.suite())
suite.addTest(couchhttp.suite())
suite.addTest(multipart.suite())
suite.addTest(mapping.suite())
suite.addTest(view.suite())
suite.addTest(couch_tests.suite())
suite.addTest(package.suite())
suite.addTest(tools.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
|
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
multipart, mapping, view, package, tools, \
loader
def suite():
suite = unittest.TestSuite()
suite.addTest(client.suite())
suite.addTest(design.suite())
suite.addTest(couchhttp.suite())
suite.addTest(multipart.suite())
suite.addTest(mapping.suite())
suite.addTest(view.suite())
suite.addTest(couch_tests.suite())
suite.addTest(package.suite())
suite.addTest(tools.suite())
suite.addTest(loader.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Include loader tests in test suite | Include loader tests in test suite
| Python | bsd-3-clause | djc/couchdb-python,djc/couchdb-python |
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
- multipart, mapping, view, package, tools
+ multipart, mapping, view, package, tools, \
+ loader
def suite():
suite = unittest.TestSuite()
suite.addTest(client.suite())
suite.addTest(design.suite())
suite.addTest(couchhttp.suite())
suite.addTest(multipart.suite())
suite.addTest(mapping.suite())
suite.addTest(view.suite())
suite.addTest(couch_tests.suite())
suite.addTest(package.suite())
suite.addTest(tools.suite())
+ suite.addTest(loader.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| Include loader tests in test suite | ## Code Before:
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
multipart, mapping, view, package, tools
def suite():
suite = unittest.TestSuite()
suite.addTest(client.suite())
suite.addTest(design.suite())
suite.addTest(couchhttp.suite())
suite.addTest(multipart.suite())
suite.addTest(mapping.suite())
suite.addTest(view.suite())
suite.addTest(couch_tests.suite())
suite.addTest(package.suite())
suite.addTest(tools.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
## Instruction:
Include loader tests in test suite
## Code After:
import unittest
from couchdb.tests import client, couch_tests, design, couchhttp, \
multipart, mapping, view, package, tools, \
loader
def suite():
suite = unittest.TestSuite()
suite.addTest(client.suite())
suite.addTest(design.suite())
suite.addTest(couchhttp.suite())
suite.addTest(multipart.suite())
suite.addTest(mapping.suite())
suite.addTest(view.suite())
suite.addTest(couch_tests.suite())
suite.addTest(package.suite())
suite.addTest(tools.suite())
suite.addTest(loader.suite())
return suite
if __name__ == '__main__':
unittest.main(defaultTest='suite')
| ...
from couchdb.tests import client, couch_tests, design, couchhttp, \
multipart, mapping, view, package, tools, \
loader
...
suite.addTest(tools.suite())
suite.addTest(loader.suite())
return suite
... |
a6dd8aee6a3b6272372532a19fba3d830d40612a | neo/test/io/test_axonio.py | neo/test/io/test_axonio.py |
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
'File_axon_4.abf',]
files_to_download = files_to_test
ioclass = AxonIO
if __name__ == "__main__":
unittest.main()
|
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
'File_axon_4.abf',
'File_axon_5.abf',
'File_axon_6.abf',
]
files_to_download = files_to_test
ioclass = AxonIO
if __name__ == "__main__":
unittest.main()
| Test with file from Jackub | Test with file from Jackub
git-svn-id: 0eea5547755d67006ec5687992a7464f0ad96b59@379 acbc63fc-6c75-0410-9d68-8fa99cba188a
| Python | bsd-3-clause | SummitKwan/python-neo,mschmidt87/python-neo,rgerkin/python-neo,jakobj/python-neo,CINPLA/python-neo,apdavison/python-neo,theunissenlab/python-neo,samuelgarcia/python-neo,guangxingli/python-neo,mgr0dzicki/python-neo,JuliaSprenger/python-neo,NeuralEnsemble/python-neo,npyoung/python-neo,INM-6/python-neo,tclose/python-neo,tkf/neo,amchagas/python-neo,Blackfynn/python-neo |
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
- 'File_axon_4.abf',]
+ 'File_axon_4.abf',
+ 'File_axon_5.abf',
+ 'File_axon_6.abf',
+
+
+ ]
files_to_download = files_to_test
ioclass = AxonIO
if __name__ == "__main__":
unittest.main()
| Test with file from Jackub | ## Code Before:
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
'File_axon_4.abf',]
files_to_download = files_to_test
ioclass = AxonIO
if __name__ == "__main__":
unittest.main()
## Instruction:
Test with file from Jackub
## Code After:
try:
import unittest2 as unittest
except ImportError:
import unittest
from neo.io import AxonIO
from neo.test.io.common_io_test import BaseTestIO
class TestAxonIO(BaseTestIO, unittest.TestCase):
files_to_test = ['File_axon_1.abf',
'File_axon_2.abf',
'File_axon_3.abf',
'File_axon_4.abf',
'File_axon_5.abf',
'File_axon_6.abf',
]
files_to_download = files_to_test
ioclass = AxonIO
if __name__ == "__main__":
unittest.main()
| # ... existing code ...
'File_axon_3.abf',
'File_axon_4.abf',
'File_axon_5.abf',
'File_axon_6.abf',
]
files_to_download = files_to_test
# ... rest of the code ... |
5b3d38821517f10f9b9da31f28af19e7302de954 | dimod/reference/composites/structure.py | dimod/reference/composites/structure.py | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
todo
"""
def __init__(self, sampler, nodelist, edgelist):
Sampler.__init__(self)
Composite.__init__(self, sampler)
Structured.__init__(self, nodelist, edgelist)
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
"""
# we will override these in the __init__, but because they are abstract properties we need to
# signal that we are overriding them
edgelist = None
nodelist = None
children = None
def __init__(self, sampler, nodelist, edgelist):
self.children = [sampler]
self.nodelist = nodelist
self.edgelist = edgelist
@property
def parameters(self):
return self.child.parameters
@property
def properties(self):
return self.child.properties
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| Update Structure composite to use the new abc | Update Structure composite to use the new abc
| Python | apache-2.0 | oneklc/dimod,oneklc/dimod | from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
+ """
+ # we will override these in the __init__, but because they are abstract properties we need to
+ # signal that we are overriding them
+ edgelist = None
+ nodelist = None
+ children = None
- todo
- """
def __init__(self, sampler, nodelist, edgelist):
- Sampler.__init__(self)
- Composite.__init__(self, sampler)
- Structured.__init__(self, nodelist, edgelist)
+ self.children = [sampler]
+ self.nodelist = nodelist
+ self.edgelist = edgelist
+
+ @property
+ def parameters(self):
+ return self.child.parameters
+
+ @property
+ def properties(self):
+ return self.child.properties
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| Update Structure composite to use the new abc | ## Code Before:
from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
todo
"""
def __init__(self, sampler, nodelist, edgelist):
Sampler.__init__(self)
Composite.__init__(self, sampler)
Structured.__init__(self, nodelist, edgelist)
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
## Instruction:
Update Structure composite to use the new abc
## Code After:
from dimod.core.sampler import Sampler
from dimod.core.composite import Composite
from dimod.core.structured import Structured
from dimod.decorators import bqm_structured
class StructureComposite(Sampler, Composite, Structured):
"""Creates a structured composed sampler from an unstructured sampler.
"""
# we will override these in the __init__, but because they are abstract properties we need to
# signal that we are overriding them
edgelist = None
nodelist = None
children = None
def __init__(self, sampler, nodelist, edgelist):
self.children = [sampler]
self.nodelist = nodelist
self.edgelist = edgelist
@property
def parameters(self):
return self.child.parameters
@property
def properties(self):
return self.child.properties
@bqm_structured
def sample(self, bqm, **sample_kwargs):
return self.child.sample(bqm, **sample_kwargs)
| // ... existing code ...
"""Creates a structured composed sampler from an unstructured sampler.
"""
# we will override these in the __init__, but because they are abstract properties we need to
# signal that we are overriding them
edgelist = None
nodelist = None
children = None
def __init__(self, sampler, nodelist, edgelist):
self.children = [sampler]
self.nodelist = nodelist
self.edgelist = edgelist
@property
def parameters(self):
return self.child.parameters
@property
def properties(self):
return self.child.properties
// ... rest of the code ... |
3cf942c5cf7f791cbbd04bf1d092c2c8061b69ac | prjxray/site_type.py | prjxray/site_type.py | """ Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
| """ Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
| Add INOUT to direction enum. | prjxray: Add INOUT to direction enum.
INOUT is found on the PS7 interface on the Zynq.
Signed-off-by: Tim 'mithro' Ansell <[email protected]>
| Python | isc | SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray,SymbiFlow/prjxray | """ Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
+ INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
| Add INOUT to direction enum. | ## Code Before:
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
## Instruction:
Add INOUT to direction enum.
## Code After:
""" Description of a site type """
from collections import namedtuple
import enum
class SitePinDirection(enum.Enum):
IN = "IN"
OUT = "OUT"
INOUT = "INOUT"
SiteTypePin = namedtuple('SiteTypePin', 'name direction')
class SiteType(object):
def __init__(self, site_type):
self.type = site_type['type']
self.site_pins = {}
for site_pin, site_pin_info in site_type['site_pins'].items():
self.site_pins[site_pin] = SiteTypePin(
name=site_pin,
direction=SitePinDirection(site_pin_info['direction']),
)
def get_site_pins(self):
return self.site_pins.keys()
def get_site_pin(self, site_pin):
return self.site_pins[site_pin]
| // ... existing code ...
OUT = "OUT"
INOUT = "INOUT"
// ... rest of the code ... |
4f1c4f75a3576c4bfb3517e6e9168fc8433a5c4b | engine/gobject.py | engine/gobject.py | from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
| from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def set(self, **kwargs):
for key, value in kwargs.items():
if key not in self.__attributes__:
raise TypeError('Unexpected attribute {}'.format(key))
setattr(self, key, value)
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
| Add method set to GObject to set attributes | Add method set to GObject to set attributes
| Python | bsd-3-clause | entwanne/NAGM | from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
+ def set(self, **kwargs):
+ for key, value in kwargs.items():
+ if key not in self.__attributes__:
+ raise TypeError('Unexpected attribute {}'.format(key))
+ setattr(self, key, value)
+
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
| Add method set to GObject to set attributes | ## Code Before:
from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
## Instruction:
Add method set to GObject to set attributes
## Code After:
from .meta import GObjectMeta
from . import signals
from . import meta
@meta.apply
class GObject(metaclass=GObjectMeta):
# Attributes of the object
__attributes__ = ()
def __init__(self, **kwargs):
for key in self.__attributes__:
setattr(self, key, kwargs.pop(key))
if kwargs:
raise TypeError('Unexpected attributes {}'.format(', '.join(kwargs.keys())))
def set(self, **kwargs):
for key, value in kwargs.items():
if key not in self.__attributes__:
raise TypeError('Unexpected attribute {}'.format(key))
setattr(self, key, value)
def send(self, handler, *args, **kwargs):
signals.send_signal(handler, self, *args, **kwargs)
def __getstate__(self):
return {k: getattr(self, k) for k in self.__attributes__}
def __setstate__(self, state):
self.__init__(**state)
| # ... existing code ...
def set(self, **kwargs):
for key, value in kwargs.items():
if key not in self.__attributes__:
raise TypeError('Unexpected attribute {}'.format(key))
setattr(self, key, value)
def send(self, handler, *args, **kwargs):
# ... rest of the code ... |
8126a93ec002c3cbff8f9cd7bfe996de740f4bef | setup.py | setup.py | from distutils.core import setup
setup(
name='buqeyemodel',
# packages=['buqeyemodel'],
py_modules=['buqeyemodel'],
version='0.1',
description='A statistical model of EFT convergence.',
author='Jordan Melendez',
author_email='[email protected]',
license='MIT',
url='https://github.com/jordan-melendez/buqeyemodel',
download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz',
keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics'
]
)
| from distutils.core import setup
setup(
name='buqeyemodel',
packages=['buqeyemodel'],
# py_modules=['buqeyemodel', 'pymc3_additions'],
version='0.1',
description='A statistical model of EFT convergence.',
author='Jordan Melendez',
author_email='[email protected]',
license='MIT',
url='https://github.com/jordan-melendez/buqeyemodel',
download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz',
keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics'
]
)
| Put buqeyemodel back in folder for multi-file use | Put buqeyemodel back in folder for multi-file use
| Python | mit | jordan-melendez/buqeyemodel,jordan-melendez/buqeyemodel | from distutils.core import setup
setup(
name='buqeyemodel',
- # packages=['buqeyemodel'],
+ packages=['buqeyemodel'],
- py_modules=['buqeyemodel'],
+ # py_modules=['buqeyemodel', 'pymc3_additions'],
version='0.1',
description='A statistical model of EFT convergence.',
author='Jordan Melendez',
author_email='[email protected]',
license='MIT',
url='https://github.com/jordan-melendez/buqeyemodel',
download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz',
keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics'
]
)
| Put buqeyemodel back in folder for multi-file use | ## Code Before:
from distutils.core import setup
setup(
name='buqeyemodel',
# packages=['buqeyemodel'],
py_modules=['buqeyemodel'],
version='0.1',
description='A statistical model of EFT convergence.',
author='Jordan Melendez',
author_email='[email protected]',
license='MIT',
url='https://github.com/jordan-melendez/buqeyemodel',
download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz',
keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics'
]
)
## Instruction:
Put buqeyemodel back in folder for multi-file use
## Code After:
from distutils.core import setup
setup(
name='buqeyemodel',
packages=['buqeyemodel'],
# py_modules=['buqeyemodel', 'pymc3_additions'],
version='0.1',
description='A statistical model of EFT convergence.',
author='Jordan Melendez',
author_email='[email protected]',
license='MIT',
url='https://github.com/jordan-melendez/buqeyemodel',
download_url='https://github.com/jordan-melendez/buqeyemodel/archive/v0.1.tar.gz',
keywords='EFT nuclear model gaussian process uncertainty quantification buqeyemodel buqeye',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering',
'Topic :: Scientific/Engineering :: Mathematics',
'Topic :: Scientific/Engineering :: Physics'
]
)
| ...
name='buqeyemodel',
packages=['buqeyemodel'],
# py_modules=['buqeyemodel', 'pymc3_additions'],
version='0.1',
... |
73457f6c4a0dde5b5eb2c35992cd0f4d221cea06 | machete/issues/models.py | machete/issues/models.py |
import thunderdome
from machete.base import BaseVertex, BaseEdge
class Issue(BaseVertex):
description = thunderdome.String()
class Severity(BaseVertex):
name = thunderdome.String()
class AssignedTo(BaseEdge):
pass
| import thunderdome
from machete.base import BaseVertex, BaseEdge
class Issue(BaseVertex):
"""Represents an issue in machete and associated information."""
description = thunderdome.String()
@property
def severity(self):
"""
Returns the severity associated with this issue
:rtype: machete.issues.models.Severity
"""
result = self.outV(Caliber)
# Ensure this invariant holds as each issue should have one severity
assert len(result) <= 1
return result[0]
class Severity(BaseVertex):
"""Indicates the severity of an issue"""
name = thunderdome.String()
@property
def issues(self):
"""
Return a list of issues associated with this severity.
:rtype: list
"""
return self.inV(Caliber)
class Caliber(BaseEdge):
"""Edge connecting an issue to its severity"""
@property
def issue(self):
"""
Return the issue associated with this caliber.
:rtype: machete.issues.models.Issue
"""
return self.outV()
@property
def severity(self):
"""
Return the severity associated with this caliber.
:rtype: machete.issues.models.Severity
"""
return self.inV()
class AssignedTo(BaseEdge):
"""Edge associating an issue with a particular user or users"""
pass
| Add Properties and Caliber Relationship Between Issue and Severity | Add Properties and Caliber Relationship Between Issue and Severity
| Python | bsd-3-clause | rustyrazorblade/machete,rustyrazorblade/machete,rustyrazorblade/machete | -
import thunderdome
from machete.base import BaseVertex, BaseEdge
+
class Issue(BaseVertex):
+ """Represents an issue in machete and associated information."""
description = thunderdome.String()
+ @property
+ def severity(self):
+ """
+ Returns the severity associated with this issue
+
+ :rtype: machete.issues.models.Severity
+
+ """
+ result = self.outV(Caliber)
+ # Ensure this invariant holds as each issue should have one severity
+ assert len(result) <= 1
+ return result[0]
+
+
class Severity(BaseVertex):
+ """Indicates the severity of an issue"""
name = thunderdome.String()
+ @property
+ def issues(self):
+ """
+ Return a list of issues associated with this severity.
+
+ :rtype: list
+
+ """
+ return self.inV(Caliber)
+
+
+ class Caliber(BaseEdge):
+ """Edge connecting an issue to its severity"""
+
+ @property
+ def issue(self):
+ """
+ Return the issue associated with this caliber.
+
+ :rtype: machete.issues.models.Issue
+
+ """
+ return self.outV()
+
+ @property
+ def severity(self):
+ """
+ Return the severity associated with this caliber.
+
+ :rtype: machete.issues.models.Severity
+
+ """
+ return self.inV()
+
+
class AssignedTo(BaseEdge):
+ """Edge associating an issue with a particular user or users"""
pass
- | Add Properties and Caliber Relationship Between Issue and Severity | ## Code Before:
import thunderdome
from machete.base import BaseVertex, BaseEdge
class Issue(BaseVertex):
description = thunderdome.String()
class Severity(BaseVertex):
name = thunderdome.String()
class AssignedTo(BaseEdge):
pass
## Instruction:
Add Properties and Caliber Relationship Between Issue and Severity
## Code After:
import thunderdome
from machete.base import BaseVertex, BaseEdge
class Issue(BaseVertex):
"""Represents an issue in machete and associated information."""
description = thunderdome.String()
@property
def severity(self):
"""
Returns the severity associated with this issue
:rtype: machete.issues.models.Severity
"""
result = self.outV(Caliber)
# Ensure this invariant holds as each issue should have one severity
assert len(result) <= 1
return result[0]
class Severity(BaseVertex):
"""Indicates the severity of an issue"""
name = thunderdome.String()
@property
def issues(self):
"""
Return a list of issues associated with this severity.
:rtype: list
"""
return self.inV(Caliber)
class Caliber(BaseEdge):
"""Edge connecting an issue to its severity"""
@property
def issue(self):
"""
Return the issue associated with this caliber.
:rtype: machete.issues.models.Issue
"""
return self.outV()
@property
def severity(self):
"""
Return the severity associated with this caliber.
:rtype: machete.issues.models.Severity
"""
return self.inV()
class AssignedTo(BaseEdge):
"""Edge associating an issue with a particular user or users"""
pass
| # ... existing code ...
import thunderdome
# ... modified code ...
class Issue(BaseVertex):
"""Represents an issue in machete and associated information."""
description = thunderdome.String()
...
@property
def severity(self):
"""
Returns the severity associated with this issue
:rtype: machete.issues.models.Severity
"""
result = self.outV(Caliber)
# Ensure this invariant holds as each issue should have one severity
assert len(result) <= 1
return result[0]
class Severity(BaseVertex):
"""Indicates the severity of an issue"""
name = thunderdome.String()
...
@property
def issues(self):
"""
Return a list of issues associated with this severity.
:rtype: list
"""
return self.inV(Caliber)
class Caliber(BaseEdge):
"""Edge connecting an issue to its severity"""
@property
def issue(self):
"""
Return the issue associated with this caliber.
:rtype: machete.issues.models.Issue
"""
return self.outV()
@property
def severity(self):
"""
Return the severity associated with this caliber.
:rtype: machete.issues.models.Severity
"""
return self.inV()
class AssignedTo(BaseEdge):
"""Edge associating an issue with a particular user or users"""
pass
# ... rest of the code ... |
4320eecc294fa1233a2ad7b4cdec1e2dc1e83b37 | testing/test_simbad.py | testing/test_simbad.py | import pytest
import vcr
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue.models import EPIC, create_session
from k2catalogue.simbad import Simbad
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def epic(session):
return session.query(EPIC).filter(EPIC.epic_id == 201763507).first()
@pytest.fixture
def simbad(epic):
return Simbad(epic)
@pytest.fixture
def form_data(simbad):
return simbad.form_data(radius=5.)
@vcr.use_cassette('.cassettes/response.yml')
@pytest.fixture
def response(simbad):
return simbad.send_request()
def test_form_data(form_data):
assert form_data['Coord'] == '169.18 4.72'
def test_response(response):
assert response.status_code == 200
def test_open(simbad):
with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open:
simbad.open(radius=10)
url, = mock_open.call_args[0]
assert 'file://' in url and 'html' in url
| import pytest
import vcr
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue.models import EPIC, create_session
from k2catalogue.simbad import Simbad
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def epic(session):
return mock.Mock(ra=123.456, dec=-56.789)
@pytest.fixture
def simbad(epic):
return Simbad(epic)
@pytest.fixture
def form_data(simbad):
return simbad.form_data(radius=5.)
@vcr.use_cassette('.cassettes/response.yml')
@pytest.fixture
def response(simbad):
return simbad.send_request()
def test_form_data(form_data):
assert form_data['Coord'] == '123.46 -56.79'
def test_response(response):
assert response.status_code == 200
def test_open(simbad):
with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open:
simbad.open(radius=10)
url, = mock_open.call_args[0]
assert 'file://' in url and 'html' in url
| Remove real database during testing | Remove real database during testing
| Python | mit | mindriot101/k2catalogue | import pytest
import vcr
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue.models import EPIC, create_session
from k2catalogue.simbad import Simbad
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def epic(session):
- return session.query(EPIC).filter(EPIC.epic_id == 201763507).first()
+ return mock.Mock(ra=123.456, dec=-56.789)
@pytest.fixture
def simbad(epic):
return Simbad(epic)
@pytest.fixture
def form_data(simbad):
return simbad.form_data(radius=5.)
@vcr.use_cassette('.cassettes/response.yml')
@pytest.fixture
def response(simbad):
return simbad.send_request()
def test_form_data(form_data):
- assert form_data['Coord'] == '169.18 4.72'
+ assert form_data['Coord'] == '123.46 -56.79'
def test_response(response):
assert response.status_code == 200
def test_open(simbad):
with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open:
simbad.open(radius=10)
url, = mock_open.call_args[0]
assert 'file://' in url and 'html' in url
| Remove real database during testing | ## Code Before:
import pytest
import vcr
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue.models import EPIC, create_session
from k2catalogue.simbad import Simbad
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def epic(session):
return session.query(EPIC).filter(EPIC.epic_id == 201763507).first()
@pytest.fixture
def simbad(epic):
return Simbad(epic)
@pytest.fixture
def form_data(simbad):
return simbad.form_data(radius=5.)
@vcr.use_cassette('.cassettes/response.yml')
@pytest.fixture
def response(simbad):
return simbad.send_request()
def test_form_data(form_data):
assert form_data['Coord'] == '169.18 4.72'
def test_response(response):
assert response.status_code == 200
def test_open(simbad):
with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open:
simbad.open(radius=10)
url, = mock_open.call_args[0]
assert 'file://' in url and 'html' in url
## Instruction:
Remove real database during testing
## Code After:
import pytest
import vcr
try:
from unittest import mock
except ImportError:
import mock
from k2catalogue.models import EPIC, create_session
from k2catalogue.simbad import Simbad
@pytest.fixture
def session():
return create_session()
@pytest.fixture
def epic(session):
return mock.Mock(ra=123.456, dec=-56.789)
@pytest.fixture
def simbad(epic):
return Simbad(epic)
@pytest.fixture
def form_data(simbad):
return simbad.form_data(radius=5.)
@vcr.use_cassette('.cassettes/response.yml')
@pytest.fixture
def response(simbad):
return simbad.send_request()
def test_form_data(form_data):
assert form_data['Coord'] == '123.46 -56.79'
def test_response(response):
assert response.status_code == 200
def test_open(simbad):
with mock.patch('k2catalogue.simbad.webbrowser.open') as mock_open:
simbad.open(radius=10)
url, = mock_open.call_args[0]
assert 'file://' in url and 'html' in url
| ...
def epic(session):
return mock.Mock(ra=123.456, dec=-56.789)
...
def test_form_data(form_data):
assert form_data['Coord'] == '123.46 -56.79'
... |
462656f9653ae43ea69080414735927b18e0debf | stats/random_walk.py | stats/random_walk.py | import neo4j
import random
from logbook import Logger
log = Logger('trinity.topics')
DEFAULT_DEPTH = 5
NUM_WALKS = 100
# Passed sorted list (desc order), return top nodes
TO_RETURN = lambda x: x[:10]
random.seed()
def random_walk(graph, node, depth=DEFAULT_DEPTH):
# Pick random neighbor
neighbors = {}
i = 0
for r in node.relationships().outgoing:
#TODO replace with i + r['count']
neighbors[(i, i + 1)] = r.getOtherNode(node)
i += 1
choice = random.range(i)
for x,y in neighbors:
if x <= i and i < y:
return [node].extend(random_walk(graph, neighbors[(x,y)], depth-1))
def run(graph, index, node):
nodes = {}
for i in range(NUM_WALKS):
with graph.transaction:
walked_nodes = random_walk(graph, node)
# Loop through nodes (that aren't the start node), count
for n in filter(lambda m: m.id != node.id, walked_nodes):
if nodes.has_key(n):
nodes[n]++
else
nodes[n] = 1
return TO_RETURN(sorted(nodes, key=nodes.__getitem__))
| import neo4j
import random
DEFAULT_DEPTH = 5
NUM_WALKS = 100
# Passed sorted list (desc order), return top nodes
TO_RETURN = lambda x: x[:10]
random.seed()
def random_walk(graph, node, depth=DEFAULT_DEPTH):
if depth == 0:
return [node]
# Pick random neighbor
neighbors = {}
i = 0
for r in node.relationships().outgoing:
neighbors[(i, i + int(r['count']))] = r.getOtherNode(node)
i += int(r['count'])
if i == 0:
# No neighbors
return [node]
r = random.randrange(i)
for x,y in neighbors:
if x <= r and r < y:
return [node] + random_walk(graph, neighbors[(x,y)], depth-1)
def run(graph, index, node):
nodes = {}
for i in range(NUM_WALKS):
with graph.transaction:
walked_nodes = random_walk(graph, node)
# Loop through nodes (that aren't the start node), count
for n in filter(lambda m: m.id != node.id, walked_nodes):
if nodes.has_key(n):
nodes[n] += 1
else:
nodes[n] = 1
return TO_RETURN([{'name': n['name'], 'count': nodes[n]}
for n in sorted(nodes, key=nodes.__getitem__)])
| Modify random walk so that it works. | Modify random walk so that it works.
| Python | mit | peplin/trinity | import neo4j
import random
-
- from logbook import Logger
- log = Logger('trinity.topics')
DEFAULT_DEPTH = 5
NUM_WALKS = 100
# Passed sorted list (desc order), return top nodes
TO_RETURN = lambda x: x[:10]
random.seed()
def random_walk(graph, node, depth=DEFAULT_DEPTH):
+ if depth == 0:
+ return [node]
+
# Pick random neighbor
neighbors = {}
i = 0
for r in node.relationships().outgoing:
- #TODO replace with i + r['count']
- neighbors[(i, i + 1)] = r.getOtherNode(node)
+ neighbors[(i, i + int(r['count']))] = r.getOtherNode(node)
- i += 1
+ i += int(r['count'])
+ if i == 0:
+ # No neighbors
+ return [node]
- choice = random.range(i)
+ r = random.randrange(i)
for x,y in neighbors:
- if x <= i and i < y:
+ if x <= r and r < y:
- return [node].extend(random_walk(graph, neighbors[(x,y)], depth-1))
+ return [node] + random_walk(graph, neighbors[(x,y)], depth-1)
def run(graph, index, node):
nodes = {}
for i in range(NUM_WALKS):
with graph.transaction:
walked_nodes = random_walk(graph, node)
# Loop through nodes (that aren't the start node), count
for n in filter(lambda m: m.id != node.id, walked_nodes):
if nodes.has_key(n):
- nodes[n]++
+ nodes[n] += 1
- else
+ else:
nodes[n] = 1
- return TO_RETURN(sorted(nodes, key=nodes.__getitem__))
+ return TO_RETURN([{'name': n['name'], 'count': nodes[n]}
+ for n in sorted(nodes, key=nodes.__getitem__)])
| Modify random walk so that it works. | ## Code Before:
import neo4j
import random
from logbook import Logger
log = Logger('trinity.topics')
DEFAULT_DEPTH = 5
NUM_WALKS = 100
# Passed sorted list (desc order), return top nodes
TO_RETURN = lambda x: x[:10]
random.seed()
def random_walk(graph, node, depth=DEFAULT_DEPTH):
# Pick random neighbor
neighbors = {}
i = 0
for r in node.relationships().outgoing:
#TODO replace with i + r['count']
neighbors[(i, i + 1)] = r.getOtherNode(node)
i += 1
choice = random.range(i)
for x,y in neighbors:
if x <= i and i < y:
return [node].extend(random_walk(graph, neighbors[(x,y)], depth-1))
def run(graph, index, node):
nodes = {}
for i in range(NUM_WALKS):
with graph.transaction:
walked_nodes = random_walk(graph, node)
# Loop through nodes (that aren't the start node), count
for n in filter(lambda m: m.id != node.id, walked_nodes):
if nodes.has_key(n):
nodes[n]++
else
nodes[n] = 1
return TO_RETURN(sorted(nodes, key=nodes.__getitem__))
## Instruction:
Modify random walk so that it works.
## Code After:
import neo4j
import random
DEFAULT_DEPTH = 5
NUM_WALKS = 100
# Passed sorted list (desc order), return top nodes
TO_RETURN = lambda x: x[:10]
random.seed()
def random_walk(graph, node, depth=DEFAULT_DEPTH):
if depth == 0:
return [node]
# Pick random neighbor
neighbors = {}
i = 0
for r in node.relationships().outgoing:
neighbors[(i, i + int(r['count']))] = r.getOtherNode(node)
i += int(r['count'])
if i == 0:
# No neighbors
return [node]
r = random.randrange(i)
for x,y in neighbors:
if x <= r and r < y:
return [node] + random_walk(graph, neighbors[(x,y)], depth-1)
def run(graph, index, node):
nodes = {}
for i in range(NUM_WALKS):
with graph.transaction:
walked_nodes = random_walk(graph, node)
# Loop through nodes (that aren't the start node), count
for n in filter(lambda m: m.id != node.id, walked_nodes):
if nodes.has_key(n):
nodes[n] += 1
else:
nodes[n] = 1
return TO_RETURN([{'name': n['name'], 'count': nodes[n]}
for n in sorted(nodes, key=nodes.__getitem__)])
| ...
import random
...
def random_walk(graph, node, depth=DEFAULT_DEPTH):
if depth == 0:
return [node]
# Pick random neighbor
...
for r in node.relationships().outgoing:
neighbors[(i, i + int(r['count']))] = r.getOtherNode(node)
i += int(r['count'])
if i == 0:
# No neighbors
return [node]
r = random.randrange(i)
for x,y in neighbors:
if x <= r and r < y:
return [node] + random_walk(graph, neighbors[(x,y)], depth-1)
...
if nodes.has_key(n):
nodes[n] += 1
else:
nodes[n] = 1
return TO_RETURN([{'name': n['name'], 'count': nodes[n]}
for n in sorted(nodes, key=nodes.__getitem__)])
... |
8386d7372f9ff8bfad651efe43504746aff19b73 | app/models/rooms/rooms.py | app/models/rooms/rooms.py | from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
| import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
| Implement the Room base class | Implement the Room base class
| Python | mit | Alweezy/alvin-mutisya-dojo-project | - from models.people.people import Staff, Fellow
- from models.rooms.rooms import Office, LivingSpace
- import random
+ import os
+ import sys
+ from os import path
+ sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
- class Dojo(object):
+ class Room(object):
+ """Models the kind of rooms available at Andela,
+ It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
+ def __init__(self, room_name, room_type, room_capacity):
+ """Initializes the base class Room
+ :param room_name: A string representing the name of the room
+ :param room_type: A string representing the type of room, whether office or residential
+ :param room_capacity: An integer representing the amount of space per room.
- def __init__(self):
- self.offices = []
- self.livingrooms = []
- self.staff = []
- self.fellows = []
- self.all_rooms = []
- self.all_people = []
-
- def get_room(self, rooms):
- """A function to generate a list of random rooms with space.
- :param rooms:
- :return: room_name
"""
+ self.room_name = room_name
+ self.room_type = room_type
+ self.room_capacity = room_capacity
+ self.occupants = []
- # a room is only available if it's capacity is not exceeded
- available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
- # return False if all rooms are full
- if len(available_rooms) < 1:
- return False
- # choose a room fro the list of available rooms.
- chosen_room = random.choice(available_rooms)
- return chosen_room.room_name
-
- def create_room(self, room_name, room_type):
- if room_type is 'office':
- if room_name not in [room.room_name for room in self.offices]:
- room = Office(room_name=room_name, room_type=room_type)
- self.offices.append(room)
- self.all_rooms.append(room)
- return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
- return 'An office with that name already exists'
- if room_type is 'livingspace':
- if room_name not in [room.room_name for room in self.livingrooms]:
- room = LivingSpace(room_name=room_name, room_type=room_type)
- # add object to list( has both room_name and room_type)
- self.livingrooms.append(room)
- self.all_rooms.append(room)
- return 'A room called ' + room_name + ' has been successfully created!'
- return 'A living room with that name already exists'
| Implement the Room base class | ## Code Before:
from models.people.people import Staff, Fellow
from models.rooms.rooms import Office, LivingSpace
import random
class Dojo(object):
def __init__(self):
self.offices = []
self.livingrooms = []
self.staff = []
self.fellows = []
self.all_rooms = []
self.all_people = []
def get_room(self, rooms):
"""A function to generate a list of random rooms with space.
:param rooms:
:return: room_name
"""
# a room is only available if it's capacity is not exceeded
available_rooms = [room for room in rooms if len(room.occupants) < room.room_capacity]
# return False if all rooms are full
if len(available_rooms) < 1:
return False
# choose a room fro the list of available rooms.
chosen_room = random.choice(available_rooms)
return chosen_room.room_name
def create_room(self, room_name, room_type):
if room_type is 'office':
if room_name not in [room.room_name for room in self.offices]:
room = Office(room_name=room_name, room_type=room_type)
self.offices.append(room)
self.all_rooms.append(room)
return 'An office called' + ' ' + room_name + ' ' + 'has been successfully created'
return 'An office with that name already exists'
if room_type is 'livingspace':
if room_name not in [room.room_name for room in self.livingrooms]:
room = LivingSpace(room_name=room_name, room_type=room_type)
# add object to list( has both room_name and room_type)
self.livingrooms.append(room)
self.all_rooms.append(room)
return 'A room called ' + room_name + ' has been successfully created!'
return 'A living room with that name already exists'
## Instruction:
Implement the Room base class
## Code After:
import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
| ...
import os
import sys
from os import path
sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
...
class Room(object):
"""Models the kind of rooms available at Andela,
It forms the base class Room from which OfficeSpace and LivingRoom inherit"""
def __init__(self, room_name, room_type, room_capacity):
"""Initializes the base class Room
:param room_name: A string representing the name of the room
:param room_type: A string representing the type of room, whether office or residential
:param room_capacity: An integer representing the amount of space per room.
"""
self.room_name = room_name
self.room_type = room_type
self.room_capacity = room_capacity
self.occupants = []
... |
cbb59747af48ae60473f27b6de976a08a741ab54 | tests/test_test_utils.py | tests/test_test_utils.py | from itertools import product
from unittest import TestCase
from zipline.utils.test_utils import parameter_space
class TestParameterSpace(TestCase):
x_args = [1, 2]
y_args = [3, 4]
@classmethod
def setUpClass(cls):
cls.xy_invocations = []
@classmethod
def tearDownClass(cls):
# This is the only actual test here.
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
@parameter_space(x=x_args, y=y_args)
def test_xy(self, x, y):
self.xy_invocations.append((x, y))
def test_nothing(self):
# Ensure that there's at least one "real" test in the class, or else
# our {setUp,tearDown}Class won't be called if, for example,
# `parameter_space` returns None.
pass
| from itertools import product
from unittest import TestCase
from zipline.utils.test_utils import parameter_space
class TestParameterSpace(TestCase):
x_args = [1, 2]
y_args = [3, 4]
@classmethod
def setUpClass(cls):
cls.xy_invocations = []
cls.yx_invocations = []
@classmethod
def tearDownClass(cls):
# This is the only actual test here.
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
assert cls.yx_invocations == list(product(cls.y_args, cls.x_args))
@parameter_space(x=x_args, y=y_args)
def test_xy(self, x, y):
self.xy_invocations.append((x, y))
@parameter_space(x=x_args, y=y_args)
def test_yx(self, y, x):
# Ensure that product is called with args in the order that they appear
# in the function's parameter list.
self.yx_invocations.append((y, x))
def test_nothing(self):
# Ensure that there's at least one "real" test in the class, or else
# our {setUp,tearDown}Class won't be called if, for example,
# `parameter_space` returns None.
pass
| Add test for parameter_space ordering. | TEST: Add test for parameter_space ordering.
| Python | apache-2.0 | magne-max/zipline-ja,florentchandelier/zipline,Scapogo/zipline,florentchandelier/zipline,bartosh/zipline,wilsonkichoi/zipline,bartosh/zipline,alphaBenj/zipline,wilsonkichoi/zipline,humdings/zipline,humdings/zipline,umuzungu/zipline,alphaBenj/zipline,enigmampc/catalyst,enigmampc/catalyst,magne-max/zipline-ja,quantopian/zipline,Scapogo/zipline,umuzungu/zipline,quantopian/zipline | from itertools import product
from unittest import TestCase
from zipline.utils.test_utils import parameter_space
class TestParameterSpace(TestCase):
x_args = [1, 2]
y_args = [3, 4]
@classmethod
def setUpClass(cls):
cls.xy_invocations = []
+ cls.yx_invocations = []
@classmethod
def tearDownClass(cls):
# This is the only actual test here.
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
+ assert cls.yx_invocations == list(product(cls.y_args, cls.x_args))
@parameter_space(x=x_args, y=y_args)
def test_xy(self, x, y):
self.xy_invocations.append((x, y))
+
+ @parameter_space(x=x_args, y=y_args)
+ def test_yx(self, y, x):
+ # Ensure that product is called with args in the order that they appear
+ # in the function's parameter list.
+ self.yx_invocations.append((y, x))
def test_nothing(self):
# Ensure that there's at least one "real" test in the class, or else
# our {setUp,tearDown}Class won't be called if, for example,
# `parameter_space` returns None.
pass
| Add test for parameter_space ordering. | ## Code Before:
from itertools import product
from unittest import TestCase
from zipline.utils.test_utils import parameter_space
class TestParameterSpace(TestCase):
x_args = [1, 2]
y_args = [3, 4]
@classmethod
def setUpClass(cls):
cls.xy_invocations = []
@classmethod
def tearDownClass(cls):
# This is the only actual test here.
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
@parameter_space(x=x_args, y=y_args)
def test_xy(self, x, y):
self.xy_invocations.append((x, y))
def test_nothing(self):
# Ensure that there's at least one "real" test in the class, or else
# our {setUp,tearDown}Class won't be called if, for example,
# `parameter_space` returns None.
pass
## Instruction:
Add test for parameter_space ordering.
## Code After:
from itertools import product
from unittest import TestCase
from zipline.utils.test_utils import parameter_space
class TestParameterSpace(TestCase):
x_args = [1, 2]
y_args = [3, 4]
@classmethod
def setUpClass(cls):
cls.xy_invocations = []
cls.yx_invocations = []
@classmethod
def tearDownClass(cls):
# This is the only actual test here.
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
assert cls.yx_invocations == list(product(cls.y_args, cls.x_args))
@parameter_space(x=x_args, y=y_args)
def test_xy(self, x, y):
self.xy_invocations.append((x, y))
@parameter_space(x=x_args, y=y_args)
def test_yx(self, y, x):
# Ensure that product is called with args in the order that they appear
# in the function's parameter list.
self.yx_invocations.append((y, x))
def test_nothing(self):
# Ensure that there's at least one "real" test in the class, or else
# our {setUp,tearDown}Class won't be called if, for example,
# `parameter_space` returns None.
pass
| // ... existing code ...
cls.xy_invocations = []
cls.yx_invocations = []
// ... modified code ...
assert cls.xy_invocations == list(product(cls.x_args, cls.y_args))
assert cls.yx_invocations == list(product(cls.y_args, cls.x_args))
...
self.xy_invocations.append((x, y))
@parameter_space(x=x_args, y=y_args)
def test_yx(self, y, x):
# Ensure that product is called with args in the order that they appear
# in the function's parameter list.
self.yx_invocations.append((y, x))
// ... rest of the code ... |
41fccd9d5060f2b8dcedde2cb9ab3391b48df420 | scripts/generate_input_syntax.py | scripts/generate_input_syntax.py | import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
| import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
| Update scripts to reflect new MOOSE_DIR definition | Update scripts to reflect new MOOSE_DIR definition
r25009
| Python | apache-2.0 | idaholab/raven,idaholab/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven,idaholab/raven,joshua-cogliati-inl/raven,joshua-cogliati-inl/raven | import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
- # this script is actually in the scripts subdirectory, so go up a level
- app_path += '/..'
# Set the name of the application here and moose directory relative to the application
- app_name = 'RAVEN'
- MOOSE_DIR = app_path + '/../moose'
+ app_name = 'raven'
+
+ MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
+ FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
- # See if MOOSE_DIR is already in the environment instead
+ #### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
+ FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
+ if os.environ.has_key("FRAMEWORK_DIR"):
+ FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
- sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
+ sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
- genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
+ genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
| Update scripts to reflect new MOOSE_DIR definition | ## Code Before:
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# this script is actually in the scripts subdirectory, so go up a level
app_path += '/..'
# Set the name of the application here and moose directory relative to the application
app_name = 'RAVEN'
MOOSE_DIR = app_path + '/../moose'
# See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
sys.path.append(MOOSE_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, MOOSE_DIR)
## Instruction:
Update scripts to reflect new MOOSE_DIR definition
## Code After:
import sys, os
# get the location of this script
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
# this will automatically copy the documentation to the base directory
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
| ...
app_path = os.path.abspath(os.path.dirname(sys.argv[0]))
...
# Set the name of the application here and moose directory relative to the application
app_name = 'raven'
MOOSE_DIR = os.path.abspath(os.path.join(app_path, '..', '..' 'moose'))
FRAMEWORK_DIR = os.path.abspath(os.path.join(app_path, '..', '..', 'moose', 'framework'))
#### See if MOOSE_DIR is already in the environment instead
if os.environ.has_key("MOOSE_DIR"):
...
MOOSE_DIR = os.environ['MOOSE_DIR']
FRAMEWORK_DIR = os.path.join(MOOSE_DIR, 'framework')
if os.environ.has_key("FRAMEWORK_DIR"):
FRAMEWORK_DIR = os.environ['FRAMEWORK_DIR']
sys.path.append(FRAMEWORK_DIR + '/scripts/syntaxHTML')
import genInputFileSyntaxHTML
...
# in a folder named syntax
genInputFileSyntaxHTML.generateHTML(app_name, app_path, sys.argv, FRAMEWORK_DIR)
... |
96076567bac3329cba55b61c59781c7670c7a02b | anybox/recipe/odoo/runtime/patch_odoo.py | anybox/recipe/odoo/runtime/patch_odoo.py |
import subprocess
def do_patch(gevent_script_path):
"""
Patch odoo prefork so that --workers execute the correct gevent script.
This monkey patch could be safer, if the script path determination could be
isolated from the actual process management logic in the original.
"""
from odoo.service.server import PreforkServer, stripped_sys_argv
def long_polling_spawn(server):
nargs = stripped_sys_argv()
nargs[0] = gevent_script_path
popen = subprocess.Popen(nargs)
server.long_polling_pid = popen.pid
PreforkServer.long_polling_spawn = long_polling_spawn
|
import subprocess
def do_patch(gevent_script_path):
"""
Patch odoo prefork so that --workers execute the correct gevent script.
This monkey patch could be safer, if the script path determination could be
isolated from the actual process management logic in the original.
"""
try:
from odoo.service.server import PreforkServer, stripped_sys_argv
except ImportError:
from openerp.service.server import PreforkServer, stripped_sys_argv
def long_polling_spawn(server):
nargs = stripped_sys_argv()
nargs[0] = gevent_script_path
popen = subprocess.Popen(nargs)
server.long_polling_pid = popen.pid
PreforkServer.long_polling_spawn = long_polling_spawn
| Maintain compatilbility with <10 version | Maintain compatilbility with <10 version | Python | agpl-3.0 | anybox/anybox.recipe.odoo |
import subprocess
def do_patch(gevent_script_path):
"""
Patch odoo prefork so that --workers execute the correct gevent script.
This monkey patch could be safer, if the script path determination could be
isolated from the actual process management logic in the original.
"""
+ try:
- from odoo.service.server import PreforkServer, stripped_sys_argv
+ from odoo.service.server import PreforkServer, stripped_sys_argv
+ except ImportError:
+ from openerp.service.server import PreforkServer, stripped_sys_argv
def long_polling_spawn(server):
nargs = stripped_sys_argv()
nargs[0] = gevent_script_path
popen = subprocess.Popen(nargs)
server.long_polling_pid = popen.pid
PreforkServer.long_polling_spawn = long_polling_spawn
| Maintain compatilbility with <10 version | ## Code Before:
import subprocess
def do_patch(gevent_script_path):
"""
Patch odoo prefork so that --workers execute the correct gevent script.
This monkey patch could be safer, if the script path determination could be
isolated from the actual process management logic in the original.
"""
from odoo.service.server import PreforkServer, stripped_sys_argv
def long_polling_spawn(server):
nargs = stripped_sys_argv()
nargs[0] = gevent_script_path
popen = subprocess.Popen(nargs)
server.long_polling_pid = popen.pid
PreforkServer.long_polling_spawn = long_polling_spawn
## Instruction:
Maintain compatilbility with <10 version
## Code After:
import subprocess
def do_patch(gevent_script_path):
"""
Patch odoo prefork so that --workers execute the correct gevent script.
This monkey patch could be safer, if the script path determination could be
isolated from the actual process management logic in the original.
"""
try:
from odoo.service.server import PreforkServer, stripped_sys_argv
except ImportError:
from openerp.service.server import PreforkServer, stripped_sys_argv
def long_polling_spawn(server):
nargs = stripped_sys_argv()
nargs[0] = gevent_script_path
popen = subprocess.Popen(nargs)
server.long_polling_pid = popen.pid
PreforkServer.long_polling_spawn = long_polling_spawn
| // ... existing code ...
try:
from odoo.service.server import PreforkServer, stripped_sys_argv
except ImportError:
from openerp.service.server import PreforkServer, stripped_sys_argv
// ... rest of the code ... |
e6c41d8bd83b6710114a9d37915a0b3bbeb78d2a | sms_sponsorship/tests/load_tests.py | sms_sponsorship/tests/load_tests.py | from locust import HttpLocust, TaskSet, task
from random import randint
class SmsSponsorWorkflow(TaskSet):
@task(1)
def send_sms(self):
url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format(
randint(100, 999))
self.client.get(url)
class SmsSponsor(HttpLocust):
task_set = SmsSponsorWorkflow
| from locust import HttpLocust, TaskSet, task
from random import randint
class SmsSponsorWorkflow(TaskSet):
@task(1)
def send_sms(self):
url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format(
randint(1000000, 9999999))
self.client.get(url)
class SmsSponsor(HttpLocust):
task_set = SmsSponsorWorkflow
| Replace phone number and avoid sending SMS for load testing | Replace phone number and avoid sending SMS for load testing
| Python | agpl-3.0 | eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules,eicher31/compassion-modules,ecino/compassion-modules,ecino/compassion-modules,CompassionCH/compassion-modules,eicher31/compassion-modules | from locust import HttpLocust, TaskSet, task
from random import randint
class SmsSponsorWorkflow(TaskSet):
@task(1)
def send_sms(self):
- url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format(
+ url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format(
- randint(100, 999))
+ randint(1000000, 9999999))
self.client.get(url)
class SmsSponsor(HttpLocust):
task_set = SmsSponsorWorkflow
| Replace phone number and avoid sending SMS for load testing | ## Code Before:
from locust import HttpLocust, TaskSet, task
from random import randint
class SmsSponsorWorkflow(TaskSet):
@task(1)
def send_sms(self):
url = "/sms/mnc?sender=%2B41789364{}&service=compassion".format(
randint(100, 999))
self.client.get(url)
class SmsSponsor(HttpLocust):
task_set = SmsSponsorWorkflow
## Instruction:
Replace phone number and avoid sending SMS for load testing
## Code After:
from locust import HttpLocust, TaskSet, task
from random import randint
class SmsSponsorWorkflow(TaskSet):
@task(1)
def send_sms(self):
url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format(
randint(1000000, 9999999))
self.client.get(url)
class SmsSponsor(HttpLocust):
task_set = SmsSponsorWorkflow
| # ... existing code ...
def send_sms(self):
url = "/sms/mnc?sender=%2B4199{}&service=compassion&text=test".format(
randint(1000000, 9999999))
self.client.get(url)
# ... rest of the code ... |
c40cb3410944053c18abf8fb2b23a59f4b336015 | conversion_calls.py | conversion_calls.py | from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msxsl_call(input_file, transform_file, output_file):
return ('msxsl.exe', input_file, transform_file, '-o', output_file)
def get_saxon_call(input_file, transform_file, output_file):
return (
'java',
'-jar',
'saxon9.jar',
'-s:' + input_file,
'-xsl:' + transform_file,
'-o:' + output_file
)
| from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
Parameters
----------
index : int
Index of conversion to be used.
Incorrect index will use default (all conversions).
Returns
-------
list of tuples
List of conversion detail tuples.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msxsl_call(input_file, transform_file, output_file):
return ('msxsl.exe', input_file, transform_file, '-o', output_file)
def get_saxon_call(input_file, transform_file, output_file):
return (
'java',
'-jar',
'saxon9.jar',
'-s:' + input_file,
'-xsl:' + transform_file,
'-o:' + output_file
)
| Expand docstring for get conversions. | Expand docstring for get conversions.
Add parameter and return value descriptions.
| Python | mit | AustralianAntarcticDataCentre/metadata_xml_convert,AustralianAntarcticDataCentre/metadata_xml_convert | from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
+
+
+ Parameters
+ ----------
+
+ index : int
+ Index of conversion to be used.
+ Incorrect index will use default (all conversions).
+
+
+ Returns
+ -------
+
+ list of tuples
+ List of conversion detail tuples.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msxsl_call(input_file, transform_file, output_file):
return ('msxsl.exe', input_file, transform_file, '-o', output_file)
def get_saxon_call(input_file, transform_file, output_file):
return (
'java',
'-jar',
'saxon9.jar',
'-s:' + input_file,
'-xsl:' + transform_file,
'-o:' + output_file
)
| Expand docstring for get conversions. | ## Code Before:
from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msxsl_call(input_file, transform_file, output_file):
return ('msxsl.exe', input_file, transform_file, '-o', output_file)
def get_saxon_call(input_file, transform_file, output_file):
return (
'java',
'-jar',
'saxon9.jar',
'-s:' + input_file,
'-xsl:' + transform_file,
'-o:' + output_file
)
## Instruction:
Expand docstring for get conversions.
## Code After:
from settings import CONVERSIONS
def get_conversions(index):
"""
Get the list of conversions to be performed.
Defaults to doing all XSL conversions for all the files.
Parameters
----------
index : int
Index of conversion to be used.
Incorrect index will use default (all conversions).
Returns
-------
list of tuples
List of conversion detail tuples.
"""
if 0 <= index and index < len(CONVERSIONS):
return [CONVERSIONS[index],]
# Default to all conversions.
return CONVERSIONS
def get_msxsl_call(input_file, transform_file, output_file):
return ('msxsl.exe', input_file, transform_file, '-o', output_file)
def get_saxon_call(input_file, transform_file, output_file):
return (
'java',
'-jar',
'saxon9.jar',
'-s:' + input_file,
'-xsl:' + transform_file,
'-o:' + output_file
)
| ...
Defaults to doing all XSL conversions for all the files.
Parameters
----------
index : int
Index of conversion to be used.
Incorrect index will use default (all conversions).
Returns
-------
list of tuples
List of conversion detail tuples.
"""
... |
6f6e16cfabb7c3ff3f634718b16f87bd7705d284 | tests/v7/test_item_list.py | tests/v7/test_item_list.py | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
| from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
item_list_2 = ItemList(values)
assert item_list == item_list_2
item_list_3 = ItemList([1, 5, 8, 3])
assert item_list != item_list_3 | Add a couple more test cases for item list | Add a couple more test cases for item list
| Python | mit | maxalbert/tohu | from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
+ item_list_2 = ItemList(values)
+ assert item_list == item_list_2
+
+ item_list_3 = ItemList([1, 5, 8, 3])
+ assert item_list != item_list_3 | Add a couple more test cases for item list | ## Code Before:
from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
## Instruction:
Add a couple more test cases for item list
## Code After:
from .context import tohu
from tohu.v7.item_list import ItemList
def test_item_list():
values = [11, 55, 22, 66, 33]
item_list = ItemList(values)
assert item_list.items == values
assert item_list == values
assert len(item_list) == 5
assert item_list[3] == 66
assert [x for x in item_list] == values
item_list_2 = ItemList(values)
assert item_list == item_list_2
item_list_3 = ItemList([1, 5, 8, 3])
assert item_list != item_list_3 | // ... existing code ...
assert [x for x in item_list] == values
item_list_2 = ItemList(values)
assert item_list == item_list_2
item_list_3 = ItemList([1, 5, 8, 3])
assert item_list != item_list_3
// ... rest of the code ... |
e8708c28e79a9063469e684b5583114c69ec425f | datadog_checks_dev/datadog_checks/dev/spec.py | datadog_checks_dev/datadog_checks/dev/spec.py | import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
assets = manifest.get('assets', {})
if 'integration' in assets:
relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
else:
relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| Fix CI for logs E2E with v2 manifests | Fix CI for logs E2E with v2 manifests | Python | bsd-3-clause | DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core | import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
+ assets = manifest.get('assets', {})
+ if 'integration' in assets:
+ relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
+ else:
- relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
+ relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| Fix CI for logs E2E with v2 manifests | ## Code Before:
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
relative_spec_path = manifest.get('assets', {}).get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
## Instruction:
Fix CI for logs E2E with v2 manifests
## Code After:
import json
import yaml
from .utils import file_exists, path_join, read_file
def load_spec(check_root):
spec_path = get_spec_path(check_root)
return yaml.safe_load(read_file(spec_path))
def get_spec_path(check_root):
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
assets = manifest.get('assets', {})
if 'integration' in assets:
relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
else:
relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
raise ValueError('No config spec defined')
spec_path = path_join(check_root, *relative_spec_path.split('/'))
if not file_exists(spec_path):
raise ValueError('No config spec found')
return spec_path
| ...
manifest = json.loads(read_file(path_join(check_root, 'manifest.json')))
assets = manifest.get('assets', {})
if 'integration' in assets:
relative_spec_path = assets['integration'].get('configuration', {}).get('spec', '')
else:
relative_spec_path = assets.get('configuration', {}).get('spec', '')
if not relative_spec_path:
... |
52bfbea4e2cb17268349b61c7f00b9253755e74d | example/books/models.py | example/books/models.py | from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse(self.detail_url_name, args=[self.id])
| from __future__ import unicode_literals
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse(self.detail_url_name, args=[self.id])
def __str__(self):
return '{0} {1} {2}'.format(self.title, self.author, self.category)
| Add support for django 2 to example project | Add support for django 2 to example project
| Python | mit | spapas/django-generic-scaffold,spapas/django-generic-scaffold | from __future__ import unicode_literals
+ try:
- from django.core.urlresolvers import reverse
+ from django.core.urlresolvers import reverse
+ except ModuleNotFoundError:
+ from django.urls import reverse
+
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse(self.detail_url_name, args=[self.id])
+ def __str__(self):
+ return '{0} {1} {2}'.format(self.title, self.author, self.category)
+ | Add support for django 2 to example project | ## Code Before:
from __future__ import unicode_literals
from django.core.urlresolvers import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse(self.detail_url_name, args=[self.id])
## Instruction:
Add support for django 2 to example project
## Code After:
from __future__ import unicode_literals
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import models
import generic_scaffold
class Book(models.Model):
title = models.CharField(max_length=128)
author = models.CharField(max_length=128)
category = models.CharField(max_length=32)
def get_absolute_url(self):
return reverse(self.detail_url_name, args=[self.id])
def __str__(self):
return '{0} {1} {2}'.format(self.title, self.author, self.category)
| # ... existing code ...
try:
from django.core.urlresolvers import reverse
except ModuleNotFoundError:
from django.urls import reverse
from django.db import models
# ... modified code ...
return reverse(self.detail_url_name, args=[self.id])
def __str__(self):
return '{0} {1} {2}'.format(self.title, self.author, self.category)
# ... rest of the code ... |
09340916e7db6ba8ccb5697b9444fbccc0512103 | example/example/views.py | example/example/views.py | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = formset_media_js + (
# Other form javascript...
)
MyFormSet = formset_factory(MyForm)
def formset_view(request):
formset = MyFormSet(request.POST or None)
if formset.is_valid():
pass
return render(request, 'formset.html', {'formset': formset})
| from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = formset_media_js + (
# Other form javascript...
)
MyFormSet = formset_factory(MyForm, can_delete=True)
def formset_view(request):
formset = MyFormSet(request.POST or None)
if formset.is_valid():
pass
return render(request, 'formset.html', {'formset': formset})
| Add `can_delete=True` to the example formset | Add `can_delete=True` to the example formset
| Python | bsd-2-clause | pretix/django-formset-js,pretix/django-formset-js,pretix/django-formset-js | from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = formset_media_js + (
# Other form javascript...
)
- MyFormSet = formset_factory(MyForm)
+ MyFormSet = formset_factory(MyForm, can_delete=True)
def formset_view(request):
formset = MyFormSet(request.POST or None)
if formset.is_valid():
pass
return render(request, 'formset.html', {'formset': formset})
| Add `can_delete=True` to the example formset | ## Code Before:
from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = formset_media_js + (
# Other form javascript...
)
MyFormSet = formset_factory(MyForm)
def formset_view(request):
formset = MyFormSet(request.POST or None)
if formset.is_valid():
pass
return render(request, 'formset.html', {'formset': formset})
## Instruction:
Add `can_delete=True` to the example formset
## Code After:
from django import forms
from django.forms.formsets import formset_factory
from django.shortcuts import render
from djangoformsetjs.utils import formset_media_js
class MyForm(forms.Form):
foo = forms.CharField()
class Media(object):
# The form must have `formset_media_js` in its Media
js = formset_media_js + (
# Other form javascript...
)
MyFormSet = formset_factory(MyForm, can_delete=True)
def formset_view(request):
formset = MyFormSet(request.POST or None)
if formset.is_valid():
pass
return render(request, 'formset.html', {'formset': formset})
| # ... existing code ...
MyFormSet = formset_factory(MyForm, can_delete=True)
# ... rest of the code ... |
f41adb3b11a572251949778ed3fa49cd0c3901c7 | AFQ/tests/test_csd.py | AFQ/tests/test_csd.py | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data()
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 8]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
| import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 6]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
| Replace the test data set with this one. | Replace the test data set with this one.
| Python | bsd-2-clause | arokem/pyAFQ,arokem/pyAFQ,yeatmanlab/pyAFQ,yeatmanlab/pyAFQ | import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
- fdata, fbval, fbvec = dpd.get_data()
+ fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
- for sh_order in [4, 8]:
+ for sh_order in [4, 6]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
| Replace the test data set with this one. | ## Code Before:
import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data()
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 8]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
## Instruction:
Replace the test data set with this one.
## Code After:
import os.path as op
import numpy as np
import numpy.testing as npt
import nibabel as nib
import nibabel.tmpdirs as nbtmp
import dipy.data as dpd
from dipy.reconst.shm import calculate_max_order
from AFQ import csd
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# Convert from npy to txt:
bvals = np.load(fbval)
bvecs = np.load(fbvec)
np.savetxt(op.join(tmpdir, 'bvals.txt'), bvals)
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 6]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
op.join(tmpdir, 'bvecs.txt'),
out_dir=tmpdir, sh_order=sh_order)
npt.assert_(op.exists(fname))
sh_coeffs_img = nib.load(fname)
npt.assert_equal(sh_order,
calculate_max_order(sh_coeffs_img.shape[-1]))
| # ... existing code ...
def test_fit_csd():
fdata, fbval, fbvec = dpd.get_data('small_64D')
with nbtmp.InTemporaryDirectory() as tmpdir:
# ... modified code ...
np.savetxt(op.join(tmpdir, 'bvecs.txt'), bvecs)
for sh_order in [4, 6]:
fname = csd.fit_csd(fdata, op.join(tmpdir, 'bvals.txt'),
# ... rest of the code ... |
80d557749f18ede24af7fc528a9d415af44d94f5 | tests/distributions/test_normal.py | tests/distributions/test_normal.py | import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma)
def test_pdf():
mu, sigma, distribution = make_normal()
mu.assign(0.0)
sigma.assign(1.0)
assert(distribution.log_pdf())
| import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma)
def test_pdf():
pass
| Fix broken test in the most correct way possible ;) | Fix broken test in the most correct way possible ;)
| Python | mit | ibab/tensorfit,tensorprob/tensorprob,ibab/tensorprob | import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma)
def test_pdf():
+ pass
- mu, sigma, distribution = make_normal()
- mu.assign(0.0)
- sigma.assign(1.0)
- assert(distribution.log_pdf())
| Fix broken test in the most correct way possible ;) | ## Code Before:
import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma)
def test_pdf():
mu, sigma, distribution = make_normal()
mu.assign(0.0)
sigma.assign(1.0)
assert(distribution.log_pdf())
## Instruction:
Fix broken test in the most correct way possible ;)
## Code After:
import tensorprob as tp
def make_normal():
mu = tp.Scalar('mu')
sigma = tp.Scalar('sigma', lower=0)
distribution = tp.Normal(mu, sigma)
return mu, sigma, distribution
def test_init():
mu, sigma, distribution = make_normal()
assert(distribution.mu is mu)
assert(distribution.sigma is sigma)
def test_pdf():
pass
| ...
def test_pdf():
pass
... |
e2fbf646b193284fc5d01684193b9c5aeb415efe | generate_html.py | generate_html.py | from jinja2 import Environment, FileSystemLoader
import datetime
import json
env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
names_template = env.get_template('names.html')
area_template = env.get_template('areas.html')
with open("output/templates.js") as templatesjs:
templates = templatesjs.read()
with open("processed/area_matches.json") as area_matches_file:
area_matches = json.load(area_matches_file)
with open('output/areas.html', 'w+') as name_output:
name_output.write(area_template.render(
templates=templates,
area_matches=area_matches,
date=datetime.date.today().isoformat(),
))
with open("processed/interesting_names.json") as interesting_names_file:
interesting_names = json.load(interesting_names_file)
with open('output/names.html', 'w+') as name_output:
name_output.write(names_template.render(
templates=templates,
interesting_names=interesting_names,
interesting_names_json=json.dumps(interesting_names),
date=datetime.date.today().isoformat(),
))
| from jinja2 import Environment, FileSystemLoader
import datetime
import json
env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
names_template = env.get_template('names.html')
area_template = env.get_template('areas.html')
with open("output/templates.js") as templatesjs:
templates = templatesjs.read()
with open("processed/area_matches.json") as area_matches_file:
area_matches = json.load(area_matches_file)
with open('output/areas.html', 'w+') as name_output:
name_output.write(area_template.render(
templates=templates,
area_matches=area_matches,
date=datetime.date.today().isoformat(),
))
with open("processed/interesting_names.json") as interesting_names_file:
interesting_names = json.load(interesting_names_file)
with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file:
key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file]))
name_output.write(names_template.render(
templates=templates,
interesting_names=interesting_names,
interesting_names_json=json.dumps(interesting_names),
date=datetime.date.today().isoformat(),
key_fields_json=json.dumps(key_fields),
))
| Fix due to merge conflicts | Fix due to merge conflicts
| Python | agpl-3.0 | TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine,TalkAboutLocal/local-news-engine | from jinja2 import Environment, FileSystemLoader
import datetime
import json
env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
names_template = env.get_template('names.html')
area_template = env.get_template('areas.html')
with open("output/templates.js") as templatesjs:
templates = templatesjs.read()
with open("processed/area_matches.json") as area_matches_file:
area_matches = json.load(area_matches_file)
with open('output/areas.html', 'w+') as name_output:
name_output.write(area_template.render(
templates=templates,
area_matches=area_matches,
date=datetime.date.today().isoformat(),
))
with open("processed/interesting_names.json") as interesting_names_file:
interesting_names = json.load(interesting_names_file)
- with open('output/names.html', 'w+') as name_output:
+ with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file:
+ key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file]))
name_output.write(names_template.render(
templates=templates,
interesting_names=interesting_names,
interesting_names_json=json.dumps(interesting_names),
date=datetime.date.today().isoformat(),
+ key_fields_json=json.dumps(key_fields),
))
+ | Fix due to merge conflicts | ## Code Before:
from jinja2 import Environment, FileSystemLoader
import datetime
import json
env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
names_template = env.get_template('names.html')
area_template = env.get_template('areas.html')
with open("output/templates.js") as templatesjs:
templates = templatesjs.read()
with open("processed/area_matches.json") as area_matches_file:
area_matches = json.load(area_matches_file)
with open('output/areas.html', 'w+') as name_output:
name_output.write(area_template.render(
templates=templates,
area_matches=area_matches,
date=datetime.date.today().isoformat(),
))
with open("processed/interesting_names.json") as interesting_names_file:
interesting_names = json.load(interesting_names_file)
with open('output/names.html', 'w+') as name_output:
name_output.write(names_template.render(
templates=templates,
interesting_names=interesting_names,
interesting_names_json=json.dumps(interesting_names),
date=datetime.date.today().isoformat(),
))
## Instruction:
Fix due to merge conflicts
## Code After:
from jinja2 import Environment, FileSystemLoader
import datetime
import json
env = Environment(loader=FileSystemLoader('templates'), autoescape=True)
names_template = env.get_template('names.html')
area_template = env.get_template('areas.html')
with open("output/templates.js") as templatesjs:
templates = templatesjs.read()
with open("processed/area_matches.json") as area_matches_file:
area_matches = json.load(area_matches_file)
with open('output/areas.html', 'w+') as name_output:
name_output.write(area_template.render(
templates=templates,
area_matches=area_matches,
date=datetime.date.today().isoformat(),
))
with open("processed/interesting_names.json") as interesting_names_file:
interesting_names = json.load(interesting_names_file)
with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file:
key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file]))
name_output.write(names_template.render(
templates=templates,
interesting_names=interesting_names,
interesting_names_json=json.dumps(interesting_names),
date=datetime.date.today().isoformat(),
key_fields_json=json.dumps(key_fields),
))
| # ... existing code ...
with open('output/names.html', 'w+') as name_output, open("key_field_names.txt") as key_field_names_file:
key_fields = list(set([key_field_name.strip() for key_field_name in key_field_names_file]))
name_output.write(names_template.render(
# ... modified code ...
date=datetime.date.today().isoformat(),
key_fields_json=json.dumps(key_fields),
))
# ... rest of the code ... |
a02f2a1ba8f2cbf0cda0a6b8b794c4970bb4b4f2 | hackfmi/urls.py | hackfmi/urls.py | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,}),
)
| Add url for media files | Add url for media files
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | from django.conf.urls import patterns, include, url
+ from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
+ url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
+ 'document_root': settings.MEDIA_ROOT,}),
)
| Add url for media files | ## Code Before:
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
## Instruction:
Add url for media files
## Code After:
from django.conf.urls import patterns, include, url
from django.conf import settings
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'hackfmi.views.home', name='home'),
# url(r'^hackfmi/', include('hackfmi.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,}),
)
| // ... existing code ...
from django.conf.urls import patterns, include, url
from django.conf import settings
// ... modified code ...
url(r'^admin/', include(admin.site.urls)),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,}),
)
// ... rest of the code ... |
5504dde1cc940fc8f55ff1bcba7ae225ad9759c1 | account_invoice_subcontractor/models/hr.py | account_invoice_subcontractor/models/hr.py |
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
("trainee", "Trainee"),
("internal", "Internal"),
("external", "External"),
]
subcontractor_company_id = fields.Many2one(
"res.company", string="Subcontractor Company"
)
subcontractor_type = fields.Selection(
string="Subcontractor Type", selection="_get_subcontractor_type", required=True
)
commission_rate = fields.Float(
help="Rate in % for the commission on subcontractor work", default=10.00
)
|
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
("trainee", "Trainee"),
("internal", "Internal"),
("external", "External"),
]
subcontractor_company_id = fields.Many2one(
"res.company", string="Subcontractor Company"
)
subcontractor_type = fields.Selection(
string="Subcontractor Type",
selection="_get_subcontractor_type",
required=True,
default="internal",
)
commission_rate = fields.Float(
help="Rate in % for the commission on subcontractor work", default=10.00
)
| FIX set default subcontractor type on employee | FIX set default subcontractor type on employee
| Python | agpl-3.0 | akretion/subcontractor |
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
("trainee", "Trainee"),
("internal", "Internal"),
("external", "External"),
]
subcontractor_company_id = fields.Many2one(
"res.company", string="Subcontractor Company"
)
subcontractor_type = fields.Selection(
- string="Subcontractor Type", selection="_get_subcontractor_type", required=True
+ string="Subcontractor Type",
+ selection="_get_subcontractor_type",
+ required=True,
+ default="internal",
)
commission_rate = fields.Float(
help="Rate in % for the commission on subcontractor work", default=10.00
)
| FIX set default subcontractor type on employee | ## Code Before:
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
("trainee", "Trainee"),
("internal", "Internal"),
("external", "External"),
]
subcontractor_company_id = fields.Many2one(
"res.company", string="Subcontractor Company"
)
subcontractor_type = fields.Selection(
string="Subcontractor Type", selection="_get_subcontractor_type", required=True
)
commission_rate = fields.Float(
help="Rate in % for the commission on subcontractor work", default=10.00
)
## Instruction:
FIX set default subcontractor type on employee
## Code After:
from odoo import api, fields, models
class HrEmployee(models.Model):
_inherit = "hr.employee"
@api.model
def _get_subcontractor_type(self):
return [
("trainee", "Trainee"),
("internal", "Internal"),
("external", "External"),
]
subcontractor_company_id = fields.Many2one(
"res.company", string="Subcontractor Company"
)
subcontractor_type = fields.Selection(
string="Subcontractor Type",
selection="_get_subcontractor_type",
required=True,
default="internal",
)
commission_rate = fields.Float(
help="Rate in % for the commission on subcontractor work", default=10.00
)
| ...
subcontractor_type = fields.Selection(
string="Subcontractor Type",
selection="_get_subcontractor_type",
required=True,
default="internal",
)
... |
4c96f2dc52810c10ef6d73732be0ecd8745c4567 | moviePlayer.py | moviePlayer.py | import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "")
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() | import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "", font = ("Courier"))
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() | Change font of ASCII to Courier | Change font of ASCII to Courier
| Python | apache-2.0 | awhittle3/ASCII-Movie | import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
- label = tk.Label(window, text = "")
+ label = tk.Label(window, text = "", font = ("Courier"))
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() | Change font of ASCII to Courier | ## Code Before:
import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "")
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main()
## Instruction:
Change font of ASCII to Courier
## Code After:
import tkinter as tk
from time import sleep
from movie01 import reel
window = tk.Tk()
def main():
window.title("Tkinter Movie Player")
button = tk.Button(window, text = "Play", command = processPlay)
button.pack()
window.mainloop()
def processPlay():
TIME_STEP = 0.3
label = tk.Label(window, text = "", font = ("Courier"))
label.pack()
count = 0
while count < len(reel):
s = ""
frame = reel[count]
for line in frame:
s += line + "\n"
count += 1
label["text"] = s
label.pack()
window.update()
sleep(TIME_STEP)
main() | # ... existing code ...
label = tk.Label(window, text = "", font = ("Courier"))
label.pack()
# ... rest of the code ... |
31d0af7d5f3a984d4f6c7be62d599553a3bc7c08 | opps/articles/utils.py | opps/articles/utils.py | from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| Add channel root on set context data, sent to template | Add channel root on set context data, sent to template
| Python | mit | YACOWS/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,williamroot/opps,opps/opps,YACOWS/opps,YACOWS/opps,jeanmask/opps,opps/opps | from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
+ context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| Add channel root on set context data, sent to template | ## Code Before:
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
## Instruction:
Add channel root on set context data, sent to template
## Code After:
from django.utils import timezone
from opps.articles.models import ArticleBox, Article
def set_context_data(self, SUPER, **kwargs):
context = super(SUPER, self).get_context_data(**kwargs)
article = Article.objects.filter(
site=self.site,
channel_long_slug__in=self.channel_long_slug,
date_available__lte=timezone.now(),
published=True)
context['posts'] = article.filter(child_class='Post')[:self.limit]
context['albums'] = article.filter(child_class='Album')[:self.limit]
context['channel'] = {}
context['channel']['long_slug'] = self.long_slug
if self.channel:
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
context['articleboxes'] = ArticleBox.objects.filter(
channel__long_slug=self.long_slug)
if self.slug:
context['articleboxes'] = context['articleboxes'].filter(
article__slug=self.slug)
return context
| ...
context['channel']['level'] = self.channel.get_level()
context['channel']['root'] = self.channel.get_root()
... |
1e8c094c0f806b624a41447446676c1f2ac3590d | tools/debug_adapter.py | tools/debug_adapter.py | import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| import sys
import subprocess
import string
out = subprocess.check_output(['lldb', '-P'])
sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Fix adapter debugging on Linux. | Fix adapter debugging on Linux.
| Python | mit | vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb,vadimcn/vscode-lldb | import sys
- if 'darwin' in sys.platform:
- sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
+ import subprocess
+ import string
+
+ out = subprocess.check_output(['lldb', '-P'])
+ sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| Fix adapter debugging on Linux. | ## Code Before:
import sys
if 'darwin' in sys.platform:
sys.path.append('/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Resources/Python')
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
## Instruction:
Fix adapter debugging on Linux.
## Code After:
import sys
import subprocess
import string
out = subprocess.check_output(['lldb', '-P'])
sys.path.append(string.strip(out))
sys.path.append('.')
import adapter
adapter.main.run_tcp_server()
| # ... existing code ...
import sys
import subprocess
import string
out = subprocess.check_output(['lldb', '-P'])
sys.path.append(string.strip(out))
sys.path.append('.')
# ... rest of the code ... |
b7514ff97118f3bd0a22d620659d307226e0d1fd | apps/domain/src/main/core/node.py | apps/domain/src/main/core/node.py | from syft.core.node.domain.domain import Domain
node = Domain(name="om-domain")
| from syft.grid.grid_client import connect
from syft.core.node.domain.domain import Domain
from syft.core.node.device.client import DeviceClient
from syft.grid.connections.http_connection import HTTPConnection
from syft.grid.services.worker_management_service import CreateWorkerService
node = Domain(name="om-domain")
node.immediate_services_with_reply.append(CreateWorkerService)
node._register_services() # re-register all services including SignalingService
try:
node.private_device = connect(
url="http://localhost:5000", # Domain Address
conn_type=HTTPConnection, # HTTP Connection Protocol
client_type=DeviceClient,
) # Device Client type
node.in_memory_client_registry[node.private_device.device_id] = node.private_device
except:
pass
| ADD a new worker connection | ADD a new worker connection
| Python | apache-2.0 | OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft | + from syft.grid.grid_client import connect
from syft.core.node.domain.domain import Domain
+ from syft.core.node.device.client import DeviceClient
+ from syft.grid.connections.http_connection import HTTPConnection
+ from syft.grid.services.worker_management_service import CreateWorkerService
node = Domain(name="om-domain")
+ node.immediate_services_with_reply.append(CreateWorkerService)
+ node._register_services() # re-register all services including SignalingService
+ try:
+ node.private_device = connect(
+ url="http://localhost:5000", # Domain Address
+ conn_type=HTTPConnection, # HTTP Connection Protocol
+ client_type=DeviceClient,
+ ) # Device Client type
+ node.in_memory_client_registry[node.private_device.device_id] = node.private_device
+ except:
+ pass
+ | ADD a new worker connection | ## Code Before:
from syft.core.node.domain.domain import Domain
node = Domain(name="om-domain")
## Instruction:
ADD a new worker connection
## Code After:
from syft.grid.grid_client import connect
from syft.core.node.domain.domain import Domain
from syft.core.node.device.client import DeviceClient
from syft.grid.connections.http_connection import HTTPConnection
from syft.grid.services.worker_management_service import CreateWorkerService
node = Domain(name="om-domain")
node.immediate_services_with_reply.append(CreateWorkerService)
node._register_services() # re-register all services including SignalingService
try:
node.private_device = connect(
url="http://localhost:5000", # Domain Address
conn_type=HTTPConnection, # HTTP Connection Protocol
client_type=DeviceClient,
) # Device Client type
node.in_memory_client_registry[node.private_device.device_id] = node.private_device
except:
pass
| ...
from syft.grid.grid_client import connect
from syft.core.node.domain.domain import Domain
from syft.core.node.device.client import DeviceClient
from syft.grid.connections.http_connection import HTTPConnection
from syft.grid.services.worker_management_service import CreateWorkerService
...
node = Domain(name="om-domain")
node.immediate_services_with_reply.append(CreateWorkerService)
node._register_services() # re-register all services including SignalingService
try:
node.private_device = connect(
url="http://localhost:5000", # Domain Address
conn_type=HTTPConnection, # HTTP Connection Protocol
client_type=DeviceClient,
) # Device Client type
node.in_memory_client_registry[node.private_device.device_id] = node.private_device
except:
pass
... |
c705fcf1771466ac2445a8058334c27cd1040e81 | docs/examples/compute/azure_arm/instantiate.py | docs/examples/compute/azure_arm/instantiate.py | from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
| from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
| Fix lint in example script | Fix lint in example script
| Python | apache-2.0 | Scalr/libcloud,illfelder/libcloud,pquentin/libcloud,apache/libcloud,pquentin/libcloud,andrewsomething/libcloud,samuelchong/libcloud,vongazman/libcloud,illfelder/libcloud,erjohnso/libcloud,SecurityCompass/libcloud,watermelo/libcloud,ByteInternet/libcloud,illfelder/libcloud,apache/libcloud,vongazman/libcloud,erjohnso/libcloud,mgogoulos/libcloud,techhat/libcloud,StackPointCloud/libcloud,ByteInternet/libcloud,samuelchong/libcloud,curoverse/libcloud,t-tran/libcloud,Scalr/libcloud,mistio/libcloud,StackPointCloud/libcloud,StackPointCloud/libcloud,t-tran/libcloud,pquentin/libcloud,Kami/libcloud,techhat/libcloud,andrewsomething/libcloud,SecurityCompass/libcloud,curoverse/libcloud,apache/libcloud,ZuluPro/libcloud,vongazman/libcloud,techhat/libcloud,t-tran/libcloud,mistio/libcloud,ByteInternet/libcloud,watermelo/libcloud,Scalr/libcloud,Kami/libcloud,ZuluPro/libcloud,watermelo/libcloud,samuelchong/libcloud,curoverse/libcloud,erjohnso/libcloud,mgogoulos/libcloud,mistio/libcloud,Kami/libcloud,andrewsomething/libcloud,SecurityCompass/libcloud,mgogoulos/libcloud,ZuluPro/libcloud | from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
- driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
+ driver = cls(tenant_id='tenant_id',
+ subscription_id='subscription_id',
+ key='application_id', secret='password')
| Fix lint in example script | ## Code Before:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id', subscription_id='subscription_id', key='application_id', secret='password')
## Instruction:
Fix lint in example script
## Code After:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
| ...
cls = get_driver(Provider.AZURE_ARM)
driver = cls(tenant_id='tenant_id',
subscription_id='subscription_id',
key='application_id', secret='password')
... |
2bad8f41c8e64249ae3d1e0d129a41917ec73482 | app/test_base.py | app/test_base.py | from flask.ext.testing import TestCase
import unittest
from app import create_app, db
class BaseTestCase(TestCase):
def create_app(self):
return create_app('config.TestingConfiguration')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def login(self, username, password):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()
| from flask.ext.testing import TestCase
import unittest
from app import create_app, db
class BaseTestCase(TestCase):
def create_app(self):
return create_app('config.TestingConfiguration')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def login(self, username='admin', password='changeme'):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()
| Add default values for login credentials in test base | Add default values for login credentials in test base
| Python | mit | rtfoley/scorepy,rtfoley/scorepy,rtfoley/scorepy | from flask.ext.testing import TestCase
import unittest
from app import create_app, db
+
class BaseTestCase(TestCase):
def create_app(self):
return create_app('config.TestingConfiguration')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
- def login(self, username, password):
+ def login(self, username='admin', password='changeme'):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()
| Add default values for login credentials in test base | ## Code Before:
from flask.ext.testing import TestCase
import unittest
from app import create_app, db
class BaseTestCase(TestCase):
def create_app(self):
return create_app('config.TestingConfiguration')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def login(self, username, password):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()
## Instruction:
Add default values for login credentials in test base
## Code After:
from flask.ext.testing import TestCase
import unittest
from app import create_app, db
class BaseTestCase(TestCase):
def create_app(self):
return create_app('config.TestingConfiguration')
def setUp(self):
db.create_all()
def tearDown(self):
db.session.remove()
db.drop_all()
def login(self, username='admin', password='changeme'):
return self.client.post('/login', data=dict(
username=username,
password=password
), follow_redirects=True)
def logout(self):
return self.client.get('/logout', follow_redirects=True)
if __name__ == '__main__':
unittest.main()
| // ... existing code ...
from app import create_app, db
// ... modified code ...
def login(self, username='admin', password='changeme'):
return self.client.post('/login', data=dict(
// ... rest of the code ... |
bebb1d9bc44300e7c65fba90d6c2eb76243ea372 | scripts/cm2lut.py | scripts/cm2lut.py | # Authors: Frederic Petit <[email protected]>,
# Gael Varoquaux <[email protected]>
# Copyright (c) 2007, Enthought, Inc.
# License: BSD Style.
from matplotlib.cm import datad, get_cmap
import numpy as np
from enthought.mayavi.core import lut as destination_module
import os
target_dir = os.path.dirname(destination_module.__file__)
values = np.linspace(0., 1., 256)
lut_dic = {}
for name in datad.keys():
if name.endswith('_r'):
continue
lut_dic[name] = get_cmap(name)(values.copy())
out_name = os.path.join(target_dir, 'pylab_luts.npz')
np.savez(out_name, **lut_dic)
| # Authors: Frederic Petit <[email protected]>,
# Gael Varoquaux <[email protected]>
# Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
import os
import numpy as np
from matplotlib.cm import datad, get_cmap
from enthought.mayavi.core import lut as destination_module
from enthought.persistence import state_pickler
target_dir = os.path.dirname(destination_module.__file__)
values = np.linspace(0., 1., 256)
lut_dic = {}
for name in datad.keys():
if name.endswith('_r'):
continue
lut_dic[name] = get_cmap(name)(values.copy())
out_name = os.path.join(target_dir, 'pylab_luts.pkl')
state_pickler.dump(lut_dic, out_name)
| Add a modified lut-data-generating script to use pickle, rather than npz | ENH: Add a modified lut-data-generating script to use pickle, rather than npz
| Python | bsd-3-clause | dmsurti/mayavi,liulion/mayavi,alexandreleroux/mayavi,alexandreleroux/mayavi,dmsurti/mayavi,liulion/mayavi | # Authors: Frederic Petit <[email protected]>,
# Gael Varoquaux <[email protected]>
- # Copyright (c) 2007, Enthought, Inc.
+ # Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
+ import os
+ import numpy as np
+
from matplotlib.cm import datad, get_cmap
- import numpy as np
from enthought.mayavi.core import lut as destination_module
- import os
+ from enthought.persistence import state_pickler
target_dir = os.path.dirname(destination_module.__file__)
values = np.linspace(0., 1., 256)
lut_dic = {}
for name in datad.keys():
if name.endswith('_r'):
continue
lut_dic[name] = get_cmap(name)(values.copy())
- out_name = os.path.join(target_dir, 'pylab_luts.npz')
+ out_name = os.path.join(target_dir, 'pylab_luts.pkl')
- np.savez(out_name, **lut_dic)
+ state_pickler.dump(lut_dic, out_name)
| Add a modified lut-data-generating script to use pickle, rather than npz | ## Code Before:
# Authors: Frederic Petit <[email protected]>,
# Gael Varoquaux <[email protected]>
# Copyright (c) 2007, Enthought, Inc.
# License: BSD Style.
from matplotlib.cm import datad, get_cmap
import numpy as np
from enthought.mayavi.core import lut as destination_module
import os
target_dir = os.path.dirname(destination_module.__file__)
values = np.linspace(0., 1., 256)
lut_dic = {}
for name in datad.keys():
if name.endswith('_r'):
continue
lut_dic[name] = get_cmap(name)(values.copy())
out_name = os.path.join(target_dir, 'pylab_luts.npz')
np.savez(out_name, **lut_dic)
## Instruction:
Add a modified lut-data-generating script to use pickle, rather than npz
## Code After:
# Authors: Frederic Petit <[email protected]>,
# Gael Varoquaux <[email protected]>
# Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
import os
import numpy as np
from matplotlib.cm import datad, get_cmap
from enthought.mayavi.core import lut as destination_module
from enthought.persistence import state_pickler
target_dir = os.path.dirname(destination_module.__file__)
values = np.linspace(0., 1., 256)
lut_dic = {}
for name in datad.keys():
if name.endswith('_r'):
continue
lut_dic[name] = get_cmap(name)(values.copy())
out_name = os.path.join(target_dir, 'pylab_luts.pkl')
state_pickler.dump(lut_dic, out_name)
| # ... existing code ...
# Gael Varoquaux <[email protected]>
# Copyright (c) 2007-2009, Enthought, Inc.
# License: BSD Style.
# ... modified code ...
import os
import numpy as np
from matplotlib.cm import datad, get_cmap
from enthought.mayavi.core import lut as destination_module
from enthought.persistence import state_pickler
target_dir = os.path.dirname(destination_module.__file__)
...
out_name = os.path.join(target_dir, 'pylab_luts.pkl')
state_pickler.dump(lut_dic, out_name)
# ... rest of the code ... |
1d0cd4bcc35042bf5146339a817a953e20229f30 | freezer_api/tests/freezer_api_tempest_plugin/clients.py | freezer_api/tests/freezer_api_tempest_plugin/clients.py |
from tempest import clients
from freezer_api.tests.freezer_api_tempest_plugin.services import\
freezer_api_client
class Manager(clients.Manager):
def __init__(self, credentials=None, service=None):
super(Manager, self).__init__(credentials, service)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
self.auth_provider)
|
from tempest import clients
from freezer_api.tests.freezer_api_tempest_plugin.services import\
freezer_api_client
class Manager(clients.Manager):
def __init__(self, credentials=None):
super(Manager, self).__init__(credentials)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
self.auth_provider)
| Fix failed tempest tests with KeystoneV2 | Fix failed tempest tests with KeystoneV2
Change-Id: I78e6a2363d006c6feec84db4d755974e6a6a81b4
Signed-off-by: Ruslan Aliev <[email protected]>
| Python | apache-2.0 | openstack/freezer-api,szaher/freezer-api,szaher/freezer-api,openstack/freezer-api,openstack/freezer-api,szaher/freezer-api,openstack/freezer-api,szaher/freezer-api |
from tempest import clients
from freezer_api.tests.freezer_api_tempest_plugin.services import\
freezer_api_client
class Manager(clients.Manager):
- def __init__(self, credentials=None, service=None):
+ def __init__(self, credentials=None):
- super(Manager, self).__init__(credentials, service)
+ super(Manager, self).__init__(credentials)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
self.auth_provider)
| Fix failed tempest tests with KeystoneV2 | ## Code Before:
from tempest import clients
from freezer_api.tests.freezer_api_tempest_plugin.services import\
freezer_api_client
class Manager(clients.Manager):
def __init__(self, credentials=None, service=None):
super(Manager, self).__init__(credentials, service)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
self.auth_provider)
## Instruction:
Fix failed tempest tests with KeystoneV2
## Code After:
from tempest import clients
from freezer_api.tests.freezer_api_tempest_plugin.services import\
freezer_api_client
class Manager(clients.Manager):
def __init__(self, credentials=None):
super(Manager, self).__init__(credentials)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
self.auth_provider)
| ...
class Manager(clients.Manager):
def __init__(self, credentials=None):
super(Manager, self).__init__(credentials)
self.freezer_api_client = freezer_api_client.FreezerApiClient(
... |
bc0895f318a9297144e31da3647d6fc5716aafc4 | setup.py | setup.py | '''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))
def __enter__(self):
os.chdir(self._temp_dir)
def __exit__(self, type, value, traceback):
os.chdir(self._return_dir)
def setup_pyquic():
with temp_cd('pyquic/py_quic'):
os.system('make')
shutil.rmtree('quic/py_quic')
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
def clean_pyquic():
shutil.rmtree('py_quic')
os.system('git submodule update --checkout --remote -f')
if __name__ == "__main__":
setup_pyquic()
| '''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))
def __enter__(self):
os.chdir(self._temp_dir)
def __exit__(self, type, value, traceback):
os.chdir(self._return_dir)
def setup_pyquic():
with temp_cd('pyquic/py_quic'):
os.system('make')
if os.path.exists('quic/py_quic'):
shutil.rmtree('quic/py_quic')
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
def clean_pyquic():
shutil.rmtree('py_quic')
os.system('git submodule update --checkout --remote -f')
if __name__ == "__main__":
setup_pyquic()
| Make sure this works the first time you run it | Make sure this works the first time you run it
| Python | mit | skggm/skggm,skggm/skggm | '''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))
def __enter__(self):
os.chdir(self._temp_dir)
def __exit__(self, type, value, traceback):
os.chdir(self._return_dir)
def setup_pyquic():
with temp_cd('pyquic/py_quic'):
os.system('make')
+ if os.path.exists('quic/py_quic'):
- shutil.rmtree('quic/py_quic')
+ shutil.rmtree('quic/py_quic')
+
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
def clean_pyquic():
shutil.rmtree('py_quic')
os.system('git submodule update --checkout --remote -f')
if __name__ == "__main__":
setup_pyquic()
| Make sure this works the first time you run it | ## Code Before:
'''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))
def __enter__(self):
os.chdir(self._temp_dir)
def __exit__(self, type, value, traceback):
os.chdir(self._return_dir)
def setup_pyquic():
with temp_cd('pyquic/py_quic'):
os.system('make')
shutil.rmtree('quic/py_quic')
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
def clean_pyquic():
shutil.rmtree('py_quic')
os.system('git submodule update --checkout --remote -f')
if __name__ == "__main__":
setup_pyquic()
## Instruction:
Make sure this works the first time you run it
## Code After:
'''
Setup script that:
/pyquic:
- compiles pyquic
- copies py_quic into base directory so that we can use the module directly
'''
import os
import shutil
class temp_cd():
def __init__(self, temp_dir):
self._temp_dir = temp_dir
self._return_dir = os.path.dirname(os.path.realpath(__file__))
def __enter__(self):
os.chdir(self._temp_dir)
def __exit__(self, type, value, traceback):
os.chdir(self._return_dir)
def setup_pyquic():
with temp_cd('pyquic/py_quic'):
os.system('make')
if os.path.exists('quic/py_quic'):
shutil.rmtree('quic/py_quic')
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
def clean_pyquic():
shutil.rmtree('py_quic')
os.system('git submodule update --checkout --remote -f')
if __name__ == "__main__":
setup_pyquic()
| ...
if os.path.exists('quic/py_quic'):
shutil.rmtree('quic/py_quic')
shutil.copytree('pyquic/py_quic', 'quic/py_quic')
... |
7d0691eae614da96f8fe14a5f5338659ef9638df | ml/pytorch/image_classification/architectures.py | ml/pytorch/image_classification/architectures.py | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flatten(nn.Module):
""" Module to Flatten a layer """
def forward(self, input):
return input.view(input.size(0), -1)
def flatten(x):
return x.view(x.size(0), -1)
| import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flatten(nn.Module):
""" Module to Flatten a layer """
def forward(self, input):
return input.view(input.size(0), -1)
def flatten(x):
return x.view(x.size(0), -1)
################################################################################
# LAYERS
################################################################################
def conv(fin, out, k=3, s=1, d=1, bn=True, bias=False, dropout=None, activation=nn.ReLU):
""" Convolutional module
By default uses same padding
CONV > BatchNorm > Activation > Dropout
"""
# naive calculation of padding
p = (k-1)//2
# Conv
sq = nn.Sequential()
sq.add_module("conv", nn.Conv2d(fin, out, k, stride=s, padding=p, dilation=d, bias=bias))
# Optional components
if bn:
sq.add_module("bn", nn.BatchNorm2d(out))
if activation is not None:
sq.add_module("activation", activation())
if dropout is not None:
sq.add_module("dropout", nn.Dropout2d(p=dropout))
return sq
| Add custom conv layer module | FEAT: Add custom conv layer module
| Python | apache-2.0 | ronrest/convenience_py,ronrest/convenience_py | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flatten(nn.Module):
""" Module to Flatten a layer """
def forward(self, input):
return input.view(input.size(0), -1)
def flatten(x):
return x.view(x.size(0), -1)
+ ################################################################################
+ # LAYERS
+ ################################################################################
+ def conv(fin, out, k=3, s=1, d=1, bn=True, bias=False, dropout=None, activation=nn.ReLU):
+ """ Convolutional module
+ By default uses same padding
+ CONV > BatchNorm > Activation > Dropout
+ """
+ # naive calculation of padding
+ p = (k-1)//2
+ # Conv
+ sq = nn.Sequential()
+ sq.add_module("conv", nn.Conv2d(fin, out, k, stride=s, padding=p, dilation=d, bias=bias))
+
+ # Optional components
+ if bn:
+ sq.add_module("bn", nn.BatchNorm2d(out))
+ if activation is not None:
+ sq.add_module("activation", activation())
+ if dropout is not None:
+ sq.add_module("dropout", nn.Dropout2d(p=dropout))
+ return sq
+
+
+ | Add custom conv layer module | ## Code Before:
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flatten(nn.Module):
""" Module to Flatten a layer """
def forward(self, input):
return input.view(input.size(0), -1)
def flatten(x):
return x.view(x.size(0), -1)
## Instruction:
Add custom conv layer module
## Code After:
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
################################################################################
# SUPPORT
################################################################################
class Flatten(nn.Module):
""" Module to Flatten a layer """
def forward(self, input):
return input.view(input.size(0), -1)
def flatten(x):
return x.view(x.size(0), -1)
################################################################################
# LAYERS
################################################################################
def conv(fin, out, k=3, s=1, d=1, bn=True, bias=False, dropout=None, activation=nn.ReLU):
""" Convolutional module
By default uses same padding
CONV > BatchNorm > Activation > Dropout
"""
# naive calculation of padding
p = (k-1)//2
# Conv
sq = nn.Sequential()
sq.add_module("conv", nn.Conv2d(fin, out, k, stride=s, padding=p, dilation=d, bias=bias))
# Optional components
if bn:
sq.add_module("bn", nn.BatchNorm2d(out))
if activation is not None:
sq.add_module("activation", activation())
if dropout is not None:
sq.add_module("dropout", nn.Dropout2d(p=dropout))
return sq
| // ... existing code ...
################################################################################
# LAYERS
################################################################################
def conv(fin, out, k=3, s=1, d=1, bn=True, bias=False, dropout=None, activation=nn.ReLU):
""" Convolutional module
By default uses same padding
CONV > BatchNorm > Activation > Dropout
"""
# naive calculation of padding
p = (k-1)//2
# Conv
sq = nn.Sequential()
sq.add_module("conv", nn.Conv2d(fin, out, k, stride=s, padding=p, dilation=d, bias=bias))
# Optional components
if bn:
sq.add_module("bn", nn.BatchNorm2d(out))
if activation is not None:
sq.add_module("activation", activation())
if dropout is not None:
sq.add_module("dropout", nn.Dropout2d(p=dropout))
return sq
// ... rest of the code ... |
881ceeb7f814bf640caf2d7a803bfc2d350b082d | plumeria/storage/__init__.py | plumeria/storage/__init__.py | import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.create("storage", "user", fallback="plumeria", comment="The database server username")
password = config.create("storage", "password", fallback="", comment="The database server password")
db = config.create("storage", "db", fallback="plumeria", comment="The database name")
class Pool:
def __init__(self):
self.pool = None
def acquire(self):
return self.pool.acquire()
pool = Pool()
migrations = MigrationManager(pool)
@bus.event('preinit')
async def preinit():
pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True)
await migrations.setup()
| import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.create("storage", "user", fallback="plumeria", comment="The database server username")
password = config.create("storage", "password", fallback="", comment="The database server password")
db = config.create("storage", "db", fallback="plumeria", comment="The database name")
class Pool:
def __init__(self):
self.pool = None
def acquire(self):
return self.pool.acquire()
pool = Pool()
migrations = MigrationManager(pool)
@bus.event('preinit')
async def preinit():
pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(),
autocommit=True, charset='utf8mb4')
await migrations.setup()
| Make sure to set MySQL charset. | Make sure to set MySQL charset.
| Python | mit | sk89q/Plumeria,sk89q/Plumeria,sk89q/Plumeria | import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.create("storage", "user", fallback="plumeria", comment="The database server username")
password = config.create("storage", "password", fallback="", comment="The database server password")
db = config.create("storage", "db", fallback="plumeria", comment="The database name")
class Pool:
def __init__(self):
self.pool = None
def acquire(self):
return self.pool.acquire()
pool = Pool()
migrations = MigrationManager(pool)
@bus.event('preinit')
async def preinit():
- pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True)
+ pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(),
+ autocommit=True, charset='utf8mb4')
await migrations.setup()
| Make sure to set MySQL charset. | ## Code Before:
import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.create("storage", "user", fallback="plumeria", comment="The database server username")
password = config.create("storage", "password", fallback="", comment="The database server password")
db = config.create("storage", "db", fallback="plumeria", comment="The database name")
class Pool:
def __init__(self):
self.pool = None
def acquire(self):
return self.pool.acquire()
pool = Pool()
migrations = MigrationManager(pool)
@bus.event('preinit')
async def preinit():
pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(), autocommit=True)
await migrations.setup()
## Instruction:
Make sure to set MySQL charset.
## Code After:
import aiomysql
from .. import config
from ..event import bus
from .migration import MigrationManager
host = config.create("storage", "host", fallback="localhost", comment="The database server host")
port = config.create("storage", "port", type=int, fallback=3306, comment="The database server port")
user = config.create("storage", "user", fallback="plumeria", comment="The database server username")
password = config.create("storage", "password", fallback="", comment="The database server password")
db = config.create("storage", "db", fallback="plumeria", comment="The database name")
class Pool:
def __init__(self):
self.pool = None
def acquire(self):
return self.pool.acquire()
pool = Pool()
migrations = MigrationManager(pool)
@bus.event('preinit')
async def preinit():
pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(),
autocommit=True, charset='utf8mb4')
await migrations.setup()
| ...
async def preinit():
pool.pool = await aiomysql.create_pool(host=host(), port=port(), user=user(), password=password(), db=db(),
autocommit=True, charset='utf8mb4')
await migrations.setup()
... |
8143d0735bce0b542b369d84bf9be02d3e6582b6 | test_queue.py | test_queue.py | from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
| from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
| Add test for dequeue from empty list | Add test for dequeue from empty list
| Python | mit | jwarren116/data-structures | from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
+
+
+ def test_dequeue_empty():
+ queue = Queue()
+ with pytest.raises(ValueError):
+ queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
| Add test for dequeue from empty list | ## Code Before:
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
## Instruction:
Add test for dequeue from empty list
## Code After:
from queue import Queue
import pytest
def test_enqueue_first_item():
queue = Queue()
queue.enqueue("Bacon")
assert queue.last_item.data == "Bacon"
def test_enqueue_multi_last_item():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Steak")
queue.enqueue("Beer")
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
def test_dequeue():
queue = Queue()
queue.enqueue("Bacon")
assert queue.dequeue() == "Bacon"
assert queue.size() == 0
def test_dequeue_multi():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.dequeue() == "Bacon"
assert queue.last_item.data == "Beer"
assert queue.size() == 1
def test_size():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
assert queue.size() == 2
def test_size_with_remove():
queue = Queue()
queue.enqueue("Bacon")
queue.enqueue("Beer")
queue.enqueue("Cow")
queue.enqueue("Whiskey")
queue.dequeue()
assert queue.size() == 3
| # ... existing code ...
assert queue.first_item.data == "Beer"
def test_dequeue_empty():
queue = Queue()
with pytest.raises(ValueError):
queue.dequeue()
# ... rest of the code ... |
b06eb92ec878a06a2fa1ce9b7eb4d253d5481daa | tests/activity/test_activity_deposit_assets.py | tests/activity/test_activity_deposit_assets.py | import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.pdf.zip', 'application/x-zip-compressed'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| Change test data for mimetype to content_type. | Change test data for mimetype to content_type.
| Python | mit | gnott/elife-bot,gnott/elife-bot,jhroot/elife-bot,gnott/elife-bot,jhroot/elife-bot,jhroot/elife-bot | import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
- ('/folder/file.pdf.zip', 'application/x-zip-compressed'),
+ ('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| Change test data for mimetype to content_type. | ## Code Before:
import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.pdf.zip', 'application/x-zip-compressed'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
## Instruction:
Change test data for mimetype to content_type.
## Code After:
import unittest
from activity.activity_DepositAssets import activity_DepositAssets
import settings_mock
from ddt import ddt, data, unpack
@ddt
class TestDepositAssets(unittest.TestCase):
def setUp(self):
self.depositassets = activity_DepositAssets(settings_mock, None, None, None, None)
@unpack
@data({'input': '.tif', 'expected': ['.tif']},
{'input': '.jpg, .tiff, .png', 'expected':['.jpg', '.tiff', '.png']})
def test_get_no_download_extensions(self, input, expected):
result = self.depositassets.get_no_download_extensions(input)
self.assertListEqual(result, expected)
@unpack
@data(
(None, None),
('image.jpg', 'image/jpeg'),
('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
('a_file', 'binary/octet-stream')
)
def test_content_type_from_file_name(self, input, expected):
result = self.depositassets.content_type_from_file_name(input)
self.assertEqual(result, expected)
if __name__ == '__main__':
unittest.main()
| # ... existing code ...
('image.jpg', 'image/jpeg'),
('/folder/file.test.pdf', 'application/pdf'),
('/folder/weird_file.wdl', 'binary/octet-stream'),
# ... rest of the code ... |
95788f09949e83cf39588444b44eda55e13c6071 | wluopensource/accounts/models.py | wluopensource/accounts/models.py | from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True)
url = models.URLField("Website", blank=True, verify_exists=False)
def __unicode__(self):
return self.user.username
def profile_creation_handler(sender, **kwargs):
if kwargs.get('created', False):
UserProfile.objects.get_or_create(user=kwargs['instance'])
post_save.connect(profile_creation_handler, sender=User)
| from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True)
url = models.URLField("Website", blank=True)
def __unicode__(self):
return self.user.username
def profile_creation_handler(sender, **kwargs):
if kwargs.get('created', False):
UserProfile.objects.get_or_create(user=kwargs['instance'])
post_save.connect(profile_creation_handler, sender=User)
| Remove verify false from user URL to match up with comment URL | Remove verify false from user URL to match up with comment URL
| Python | bsd-3-clause | jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website,jeffcharles/Open-Source-at-Laurier-Website | from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True)
- url = models.URLField("Website", blank=True, verify_exists=False)
+ url = models.URLField("Website", blank=True)
def __unicode__(self):
return self.user.username
def profile_creation_handler(sender, **kwargs):
if kwargs.get('created', False):
UserProfile.objects.get_or_create(user=kwargs['instance'])
post_save.connect(profile_creation_handler, sender=User)
| Remove verify false from user URL to match up with comment URL | ## Code Before:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True)
url = models.URLField("Website", blank=True, verify_exists=False)
def __unicode__(self):
return self.user.username
def profile_creation_handler(sender, **kwargs):
if kwargs.get('created', False):
UserProfile.objects.get_or_create(user=kwargs['instance'])
post_save.connect(profile_creation_handler, sender=User)
## Instruction:
Remove verify false from user URL to match up with comment URL
## Code After:
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
class UserProfile(models.Model):
user = models.ForeignKey(User, blank=True, unique=True)
url = models.URLField("Website", blank=True)
def __unicode__(self):
return self.user.username
def profile_creation_handler(sender, **kwargs):
if kwargs.get('created', False):
UserProfile.objects.get_or_create(user=kwargs['instance'])
post_save.connect(profile_creation_handler, sender=User)
| ...
user = models.ForeignKey(User, blank=True, unique=True)
url = models.URLField("Website", blank=True)
... |
b0237011251815e883b4fa60839dafd513907227 | forum/templatetags/forum_extras.py | forum/templatetags/forum_extras.py | from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
levels.pop()
depth -= 1
except IndexError:
pass
html += ' ' * depth + '<li>' + post.subject
if post.right - post.left > 1:
html += '<ul>'
levels.append(post.right)
depth = len(levels)
else:
html += '</li>'
html += '</ul></li>' * depth
html += '</ul>'
return mark_safe(html)
| from django import template
from django.urls import reverse
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
levels.pop()
depth -= 1
except IndexError:
pass
html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format(
url=reverse('forum:post', kwargs={
'board':post.topic.board.slug,
'pk':post.pk
}),
title=post.subject,
user=post.user.username,
date='[date]',
)
if post.right - post.left > 1:
html += '<ul>'
levels.append(post.right)
depth = len(levels)
else:
html += '</li>'
html += '</ul></li>' * depth
html += '</ul>'
return mark_safe(html)
| Add formatting to post tree | Add formatting to post tree
| Python | mit | Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/fbxnano | from django import template
+ from django.urls import reverse
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
levels.pop()
depth -= 1
except IndexError:
pass
- html += ' ' * depth + '<li>' + post.subject
+ html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format(
+ url=reverse('forum:post', kwargs={
+ 'board':post.topic.board.slug,
+ 'pk':post.pk
+ }),
+ title=post.subject,
+ user=post.user.username,
+ date='[date]',
+ )
if post.right - post.left > 1:
html += '<ul>'
levels.append(post.right)
depth = len(levels)
else:
html += '</li>'
html += '</ul></li>' * depth
html += '</ul>'
return mark_safe(html)
| Add formatting to post tree | ## Code Before:
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
levels.pop()
depth -= 1
except IndexError:
pass
html += ' ' * depth + '<li>' + post.subject
if post.right - post.left > 1:
html += '<ul>'
levels.append(post.right)
depth = len(levels)
else:
html += '</li>'
html += '</ul></li>' * depth
html += '</ul>'
return mark_safe(html)
## Instruction:
Add formatting to post tree
## Code After:
from django import template
from django.urls import reverse
from django.utils.safestring import mark_safe
register = template.Library()
@register.simple_tag
def make_tree(posts):
levels = []
depth = 0
html = '<ul>'
for post in posts:
try:
while levels[-1] < post.left:
html += '</ul></li>'
levels.pop()
depth -= 1
except IndexError:
pass
html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format(
url=reverse('forum:post', kwargs={
'board':post.topic.board.slug,
'pk':post.pk
}),
title=post.subject,
user=post.user.username,
date='[date]',
)
if post.right - post.left > 1:
html += '<ul>'
levels.append(post.right)
depth = len(levels)
else:
html += '</li>'
html += '</ul></li>' * depth
html += '</ul>'
return mark_safe(html)
| // ... existing code ...
from django import template
from django.urls import reverse
from django.utils.safestring import mark_safe
// ... modified code ...
html += '<li><a href="{url}">{title}</a> by {user} on {date}'.format(
url=reverse('forum:post', kwargs={
'board':post.topic.board.slug,
'pk':post.pk
}),
title=post.subject,
user=post.user.username,
date='[date]',
)
// ... rest of the code ... |
9364cf8e738b048e16f8f6504674536a39be96e0 | graphiter/models.py | graphiter/models.py | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
| from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
| Add get_absolute_url to Page model | Add get_absolute_url to Page model | Python | bsd-2-clause | jwineinger/django-graphiter | from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
+
+ def get_absolute_url(self):
+ return reverse('page_detail', kwargs={'slug': self.slug})
| Add get_absolute_url to Page model | ## Code Before:
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
## Instruction:
Add get_absolute_url to Page model
## Code After:
from django.db import models
class Chart(models.Model):
title = models.CharField(max_length=50)
url = models.CharField(max_length=1024)
def __unicode__(self):
return self.title
class Page(models.Model):
title = models.CharField(max_length=50)
slug = models.SlugField()
charts = models.ManyToManyField(Chart)
time_from = models.CharField(max_length=50, default=u"-24h")
time_until = models.CharField(max_length=50, default=u"", blank=True)
image_width = models.PositiveIntegerField(default=1200)
image_height = models.PositiveIntegerField(default=400)
def __unicode__(self):
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
| ...
return self.title
def get_absolute_url(self):
return reverse('page_detail', kwargs={'slug': self.slug})
... |
72e509be8415e628613b2341c136018ff5bb0f44 | openpathsampling/engines/openmm/__init__.py | openpathsampling/engines/openmm/__init__.py | def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_openmm
snapshot_from_testsystem = missing_openmm
to_openmm_topology = missing_openmm
trajectory_from_mdtraj = missing_openmm
trajectory_to_mdtraj = missing_openmm
Snapshot = missing_openmm
MDSnapshot = missing_openmm
else:
from .engine import OpenMMEngine as Engine
from .tools import (
empty_snapshot_from_openmm_topology,
snapshot_from_pdb,
snapshot_from_testsystem,
to_openmm_topology,
trajectory_from_mdtraj,
trajectory_to_mdtraj
)
from . import features
from .snapshot import Snapshot, MDSnapshot
from openpathsampling.engines import NoEngine, SnapshotDescriptor
| def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_openmm
snapshot_from_testsystem = missing_openmm
to_openmm_topology = missing_openmm
trajectory_from_mdtraj = missing_openmm
trajectory_to_mdtraj = missing_openmm
Snapshot = missing_openmm
MDSnapshot = missing_openmm
else:
from .engine import OpenMMEngine as Engine
from .tools import (
empty_snapshot_from_openmm_topology,
snapshot_from_pdb,
snapshot_from_testsystem,
to_openmm_topology,
trajectory_from_mdtraj,
trajectory_to_mdtraj
)
from . import features
from .snapshot import Snapshot, MDSnapshot
from . import topology
from openpathsampling.engines import NoEngine, SnapshotDescriptor
| Fix backward compatiblity for MDTrajTopology | Fix backward compatiblity for MDTrajTopology
| Python | mit | openpathsampling/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,choderalab/openpathsampling,openpathsampling/openpathsampling,dwhswenson/openpathsampling | def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_openmm
snapshot_from_testsystem = missing_openmm
to_openmm_topology = missing_openmm
trajectory_from_mdtraj = missing_openmm
trajectory_to_mdtraj = missing_openmm
Snapshot = missing_openmm
MDSnapshot = missing_openmm
else:
from .engine import OpenMMEngine as Engine
from .tools import (
empty_snapshot_from_openmm_topology,
snapshot_from_pdb,
snapshot_from_testsystem,
to_openmm_topology,
trajectory_from_mdtraj,
trajectory_to_mdtraj
)
from . import features
from .snapshot import Snapshot, MDSnapshot
+ from . import topology
from openpathsampling.engines import NoEngine, SnapshotDescriptor
| Fix backward compatiblity for MDTrajTopology | ## Code Before:
def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_openmm
snapshot_from_testsystem = missing_openmm
to_openmm_topology = missing_openmm
trajectory_from_mdtraj = missing_openmm
trajectory_to_mdtraj = missing_openmm
Snapshot = missing_openmm
MDSnapshot = missing_openmm
else:
from .engine import OpenMMEngine as Engine
from .tools import (
empty_snapshot_from_openmm_topology,
snapshot_from_pdb,
snapshot_from_testsystem,
to_openmm_topology,
trajectory_from_mdtraj,
trajectory_to_mdtraj
)
from . import features
from .snapshot import Snapshot, MDSnapshot
from openpathsampling.engines import NoEngine, SnapshotDescriptor
## Instruction:
Fix backward compatiblity for MDTrajTopology
## Code After:
def missing_openmm(*args, **kwargs):
raise RuntimeError("Install OpenMM to use this feature")
try:
import simtk.openmm
import simtk.openmm.app
except ImportError:
HAS_OPENMM = False
Engine = missing_openmm
empty_snapshot_from_openmm_topology = missing_openmm
snapshot_from_pdb = missing_openmm
snapshot_from_testsystem = missing_openmm
to_openmm_topology = missing_openmm
trajectory_from_mdtraj = missing_openmm
trajectory_to_mdtraj = missing_openmm
Snapshot = missing_openmm
MDSnapshot = missing_openmm
else:
from .engine import OpenMMEngine as Engine
from .tools import (
empty_snapshot_from_openmm_topology,
snapshot_from_pdb,
snapshot_from_testsystem,
to_openmm_topology,
trajectory_from_mdtraj,
trajectory_to_mdtraj
)
from . import features
from .snapshot import Snapshot, MDSnapshot
from . import topology
from openpathsampling.engines import NoEngine, SnapshotDescriptor
| // ... existing code ...
from .snapshot import Snapshot, MDSnapshot
from . import topology
// ... rest of the code ... |
8e8a4360124a033ad3c5bd26bfe2b3896155f25a | tests/TestDBControl.py | tests/TestDBControl.py | import unittest
from blo.DBControl import DBControl
class TestDBControl(unittest.TestCase):
pass | import unittest
from pathlib import Path
from blo.DBControl import DBControl
class TestDBControlOnMemory(unittest.TestCase):
def setUp(self):
self.db_control = DBControl()
def test_initializer_for_file(self):
file_path = "./test.sqlite"
self.db_control.close_connect()
self.db_control = DBControl(file_path)
self.db_control.create_tables()
self.assertTrue(Path(file_path).exists())
self.db_control.close_connect()
Path(file_path).unlink()
self.assertFalse(Path(file_path).exists())
self.db_control = DBControl()
def test_create_table_and_select_all(self):
self.db_control.create_tables()
ret = self.db_control._select_all('Articles')
self.assertIsInstance(ret, list)
def doCleanups(self):
self.db_control.close_connect()
| Add test pattern of initializer for file. | Add test pattern of initializer for file.
| Python | mit | 10nin/blo,10nin/blo | import unittest
+ from pathlib import Path
from blo.DBControl import DBControl
- class TestDBControl(unittest.TestCase):
+ class TestDBControlOnMemory(unittest.TestCase):
- pass
+ def setUp(self):
+ self.db_control = DBControl()
+
+ def test_initializer_for_file(self):
+ file_path = "./test.sqlite"
+ self.db_control.close_connect()
+ self.db_control = DBControl(file_path)
+ self.db_control.create_tables()
+ self.assertTrue(Path(file_path).exists())
+ self.db_control.close_connect()
+ Path(file_path).unlink()
+ self.assertFalse(Path(file_path).exists())
+ self.db_control = DBControl()
+
+ def test_create_table_and_select_all(self):
+ self.db_control.create_tables()
+ ret = self.db_control._select_all('Articles')
+ self.assertIsInstance(ret, list)
+
+ def doCleanups(self):
+ self.db_control.close_connect()
+ | Add test pattern of initializer for file. | ## Code Before:
import unittest
from blo.DBControl import DBControl
class TestDBControl(unittest.TestCase):
pass
## Instruction:
Add test pattern of initializer for file.
## Code After:
import unittest
from pathlib import Path
from blo.DBControl import DBControl
class TestDBControlOnMemory(unittest.TestCase):
def setUp(self):
self.db_control = DBControl()
def test_initializer_for_file(self):
file_path = "./test.sqlite"
self.db_control.close_connect()
self.db_control = DBControl(file_path)
self.db_control.create_tables()
self.assertTrue(Path(file_path).exists())
self.db_control.close_connect()
Path(file_path).unlink()
self.assertFalse(Path(file_path).exists())
self.db_control = DBControl()
def test_create_table_and_select_all(self):
self.db_control.create_tables()
ret = self.db_control._select_all('Articles')
self.assertIsInstance(ret, list)
def doCleanups(self):
self.db_control.close_connect()
| ...
import unittest
from pathlib import Path
from blo.DBControl import DBControl
...
class TestDBControlOnMemory(unittest.TestCase):
def setUp(self):
self.db_control = DBControl()
def test_initializer_for_file(self):
file_path = "./test.sqlite"
self.db_control.close_connect()
self.db_control = DBControl(file_path)
self.db_control.create_tables()
self.assertTrue(Path(file_path).exists())
self.db_control.close_connect()
Path(file_path).unlink()
self.assertFalse(Path(file_path).exists())
self.db_control = DBControl()
def test_create_table_and_select_all(self):
self.db_control.create_tables()
ret = self.db_control._select_all('Articles')
self.assertIsInstance(ret, list)
def doCleanups(self):
self.db_control.close_connect()
... |
ec235e290b4428dec2db03a19d678eba52f02fb5 | keyring/getpassbackend.py | keyring/getpassbackend.py | """Specific support for getpass."""
import os
import getpass
from keyring.core import get_password as original_get_password
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return original_get_password(service_name, username)
| """Specific support for getpass."""
import os
import getpass
import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return keyring.core.get_password(service_name, username)
| Use module namespaces to distinguish names instead of 'original_' prefix | Use module namespaces to distinguish names instead of 'original_' prefix
| Python | mit | jaraco/keyring | """Specific support for getpass."""
import os
import getpass
- from keyring.core import get_password as original_get_password
+ import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
- return original_get_password(service_name, username)
+ return keyring.core.get_password(service_name, username)
| Use module namespaces to distinguish names instead of 'original_' prefix | ## Code Before:
"""Specific support for getpass."""
import os
import getpass
from keyring.core import get_password as original_get_password
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return original_get_password(service_name, username)
## Instruction:
Use module namespaces to distinguish names instead of 'original_' prefix
## Code After:
"""Specific support for getpass."""
import os
import getpass
import keyring.core
def get_password(prompt='Password: ', stream=None,
service_name='Python',
username=None):
if username is None:
username = getpass.getuser()
return keyring.core.get_password(service_name, username)
| # ... existing code ...
import keyring.core
# ... modified code ...
username = getpass.getuser()
return keyring.core.get_password(service_name, username)
# ... rest of the code ... |
76e1565200dda04e4091be761c737042f9a15e67 | synapse/media/v1/__init__.py | synapse/media/v1/__init__.py |
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
|
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
| Change error message for missing pillow libs. | Change error message for missing pillow libs.
| Python | apache-2.0 | illicitonion/synapse,howethomas/synapse,iot-factory/synapse,TribeMedia/synapse,matrix-org/synapse,iot-factory/synapse,illicitonion/synapse,matrix-org/synapse,matrix-org/synapse,rzr/synapse,howethomas/synapse,rzr/synapse,howethomas/synapse,howethomas/synapse,illicitonion/synapse,illicitonion/synapse,rzr/synapse,matrix-org/synapse,matrix-org/synapse,rzr/synapse,howethomas/synapse,TribeMedia/synapse,TribeMedia/synapse,illicitonion/synapse,iot-factory/synapse,TribeMedia/synapse,iot-factory/synapse,rzr/synapse,matrix-org/synapse,iot-factory/synapse,TribeMedia/synapse |
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
- " 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
+ " 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
+ " pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
- " 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
+ " 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
+ " pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
| Change error message for missing pillow libs. | ## Code Before:
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip install -I pillow'"
)
except Exception:
# any other exception is fine
pass
## Instruction:
Change error message for missing pillow libs.
## Code After:
import PIL.Image
# check for JPEG support.
try:
PIL.Image._getdecoder("rgb", "jpeg", None)
except IOError as e:
if str(e).startswith("decoder jpeg not available"):
raise Exception(
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
# check for PNG support.
try:
PIL.Image._getdecoder("rgb", "zip", None)
except IOError as e:
if str(e).startswith("decoder zip not available"):
raise Exception(
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
except Exception:
# any other exception is fine
pass
| // ... existing code ...
"FATAL: jpeg codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
// ... modified code ...
"FATAL: zip codec not supported. Install pillow correctly! "
" 'sudo apt-get install libjpeg-dev' then 'pip uninstall pillow &&"
" pip install pillow --user'"
)
// ... rest of the code ... |
b090c7ae0f5407562e3adc818d2f65ccd4ea7e02 | src/arc_utilities/listener.py | src/arc_utilities/listener.py | from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
| from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
callback (function taking msg_type): optional callback to be called on the data as we receive it
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.custom_callback = callback
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
if self.custom_callback is not None:
self.custom_callback(self.data)
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
| Allow optional callbacks for Listeners | Allow optional callbacks for Listeners
| Python | bsd-2-clause | WPI-ARC/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,UM-ARM-Lab/arc_utilities,WPI-ARC/arc_utilities,WPI-ARC/arc_utilities | from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
- def __init__(self, topic_name, topic_type, wait_for_data=False):
+ def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
+ callback (function taking msg_type): optional callback to be called on the data as we receive it
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
+ self.custom_callback = callback
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
+ if self.custom_callback is not None:
+ self.custom_callback(self.data)
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
| Allow optional callbacks for Listeners | ## Code Before:
from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
## Instruction:
Allow optional callbacks for Listeners
## Code After:
from copy import deepcopy
from threading import Lock
import rospy
from arc_utilities.ros_helpers import wait_for
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
Listener is a wrapper around a subscriber where the callback simply records the latest msg.
Listener does not consume the message
(for consuming behavior, use the standard ros callback pattern)
Listener does not check timestamps of message headers
Parameters:
topic_name (str): name of topic to subscribe to
topic_type (msg_type): type of message received on topic
wait_for_data (bool): block constructor until a message has been received
callback (function taking msg_type): optional callback to be called on the data as we receive it
"""
self.data = None
self.lock = Lock()
self.topic_name = topic_name
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.custom_callback = callback
self.get(wait_for_data)
def callback(self, msg):
with self.lock:
self.data = msg
if self.custom_callback is not None:
self.custom_callback(self.data)
def get(self, block_until_data=True):
"""
Returns the latest msg from the subscribed topic
Parameters:
block_until_data (bool): block if no message has been received yet.
Guarantees a msg is returned (not None)
"""
wait_for(lambda: not (block_until_data and self.data is None), 10, f"Listener({self.topic_name})")
with self.lock:
return deepcopy(self.data)
| ...
class Listener:
def __init__(self, topic_name, topic_type, wait_for_data=False, callback=None):
"""
...
wait_for_data (bool): block constructor until a message has been received
callback (function taking msg_type): optional callback to be called on the data as we receive it
"""
...
self.subscriber = rospy.Subscriber(topic_name, topic_type, self.callback)
self.custom_callback = callback
self.get(wait_for_data)
...
self.data = msg
if self.custom_callback is not None:
self.custom_callback(self.data)
... |
508ca596d46c08fdc9295769059f5de974b2d1df | base/components/accounts/admin.py | base/components/accounts/admin.py | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
class EditorAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': (('username', 'password'),)}),
('Personal Information', {'fields': (('name', 'email'),)}),
('Important Dates', {
'classes': ('grp-collapse grp-open',),
'fields': ('started', 'last_login', 'active_since')
}),
('Permissions', {
'classes': ('grp-collapse grp-open',),
'fields': (('is_active', 'is_staff', 'is_superuser'),)
}),
('OAuth', {
'classes': ('grp-collapse grp-closed',),
'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration'))
})
)
list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token']
list_filter = ['is_active', 'is_staff', 'is_superuser']
admin.site.register(Editor, EditorAdmin)
admin.site.unregister(Group)
| from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
super(ContributorMixin, self).save_model(request, obj, form, change)
class EditorAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': (('username', 'password'),)}),
('Personal Information', {'fields': (('name', 'email'),)}),
('Important Dates', {
'classes': ('grp-collapse grp-open',),
'fields': ('started', 'last_login', 'active_since')
}),
('Permissions', {
'classes': ('grp-collapse grp-open',),
'fields': (('is_active', 'is_staff', 'is_superuser'),)
}),
('OAuth', {
'classes': ('grp-collapse grp-closed',),
'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration'))
})
)
list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token']
list_filter = ['is_active', 'is_staff', 'is_superuser']
admin.site.register(Editor, EditorAdmin)
admin.site.unregister(Group)
| Move this to the bottom... | Move this to the bottom...
| Python | apache-2.0 | hello-base/web,hello-base/web,hello-base/web,hello-base/web | from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
- super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
+ super(ContributorMixin, self).save_model(request, obj, form, change)
class EditorAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': (('username', 'password'),)}),
('Personal Information', {'fields': (('name', 'email'),)}),
('Important Dates', {
'classes': ('grp-collapse grp-open',),
'fields': ('started', 'last_login', 'active_since')
}),
('Permissions', {
'classes': ('grp-collapse grp-open',),
'fields': (('is_active', 'is_staff', 'is_superuser'),)
}),
('OAuth', {
'classes': ('grp-collapse grp-closed',),
'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration'))
})
)
list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token']
list_filter = ['is_active', 'is_staff', 'is_superuser']
admin.site.register(Editor, EditorAdmin)
admin.site.unregister(Group)
| Move this to the bottom... | ## Code Before:
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
super(ContributorMixin, self).save_model(request, obj, form, change)
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
class EditorAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': (('username', 'password'),)}),
('Personal Information', {'fields': (('name', 'email'),)}),
('Important Dates', {
'classes': ('grp-collapse grp-open',),
'fields': ('started', 'last_login', 'active_since')
}),
('Permissions', {
'classes': ('grp-collapse grp-open',),
'fields': (('is_active', 'is_staff', 'is_superuser'),)
}),
('OAuth', {
'classes': ('grp-collapse grp-closed',),
'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration'))
})
)
list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token']
list_filter = ['is_active', 'is_staff', 'is_superuser']
admin.site.register(Editor, EditorAdmin)
admin.site.unregister(Group)
## Instruction:
Move this to the bottom...
## Code After:
from django.contrib import admin
from django.contrib.auth.models import Group
from .models import Editor
class ContributorMixin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not change:
obj.submitted_by = request.user
obj.edited_by.add(request.user)
obj.save()
super(ContributorMixin, self).save_model(request, obj, form, change)
class EditorAdmin(admin.ModelAdmin):
fieldsets = (
(None, {'fields': (('username', 'password'),)}),
('Personal Information', {'fields': (('name', 'email'),)}),
('Important Dates', {
'classes': ('grp-collapse grp-open',),
'fields': ('started', 'last_login', 'active_since')
}),
('Permissions', {
'classes': ('grp-collapse grp-open',),
'fields': (('is_active', 'is_staff', 'is_superuser'),)
}),
('OAuth', {
'classes': ('grp-collapse grp-closed',),
'fields': ('base_id', ('access_token', 'refresh_token', 'token_expiration'))
})
)
list_display = ['username', 'name', 'email', 'is_active', 'is_staff', 'is_superuser', 'base_id', 'access_token']
list_filter = ['is_active', 'is_staff', 'is_superuser']
admin.site.register(Editor, EditorAdmin)
admin.site.unregister(Group)
| # ... existing code ...
def save_model(self, request, obj, form, change):
if not change:
# ... modified code ...
obj.save()
super(ContributorMixin, self).save_model(request, obj, form, change)
# ... rest of the code ... |
68724546ba4f6063559ba14b8625c7e7ecdf9732 | src/read_key.py | src/read_key.py |
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
|
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
| Remove newline and carraige return characters from key files so that API calls work | Remove newline and carraige return characters from key files so that API calls work
| Python | mit | nilnullzip/StalkerBot,nilnullzip/StalkerBot |
def readKey(keyFileName):
- return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
+ return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
| Remove newline and carraige return characters from key files so that API calls work | ## Code Before:
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline()
## Instruction:
Remove newline and carraige return characters from key files so that API calls work
## Code After:
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
| ...
def readKey(keyFileName):
return open("../options-and-settings/api-keys/" + keyFileName, "r").readline().rstrip('\n').rstrip('\r')
... |
69d013b768edabb6bc7dbe78b1f219ea1b49db16 | sqlitebiter/_config.py | sqlitebiter/_config.py |
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value="",
),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
|
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
| Add default encoding parameter to configure subcommand | Add default encoding parameter to configure subcommand
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter |
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
+ DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
+ name=ConfigKey.DEFAULT_ENCODING,
+ prompt_text="Default encoding to load files",
+ initial_value="utf-8"),
+ appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
- initial_value="",
+ initial_value=""),
- ),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
| Add default encoding parameter to configure subcommand | ## Code Before:
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value="",
),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
## Instruction:
Add default encoding parameter to configure subcommand
## Code After:
from __future__ import absolute_import
from __future__ import unicode_literals
import appconfigpy
from ._const import PROGRAM_NAME
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
GS_CREDENTIALS_FILE_PATH = "gs_credentials_file_path"
app_config_manager = appconfigpy.ConfigManager(
config_name=PROGRAM_NAME,
config_item_list=[
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
# name="gs_credentials_file_path",
# prompt_text="Google Sheets credentials file path",
# initial_value="",
# ),
])
| ...
class ConfigKey(object):
DEFAULT_ENCODING = "default_encoding"
PROXY_SERVER = "proxy_server"
...
appconfigpy.ConfigItem(
name=ConfigKey.DEFAULT_ENCODING,
prompt_text="Default encoding to load files",
initial_value="utf-8"),
appconfigpy.ConfigItem(
name=ConfigKey.PROXY_SERVER,
...
prompt_text="HTTP/HTTPS proxy server URI",
initial_value=""),
# appconfigpy.ConfigItem(
... |
513c7a2f5c5fb5a8c47b3173a8d5854755f7928f | pylab/website/tests/test_about_page.py | pylab/website/tests/test_about_page.py | import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from pylab.core.models import Event
class AboutPageTests(WebTest):
def setUp(self):
self.user = User.objects.create(username='u1')
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
Event.objects.create(
author=self.user,
starts=datetime.datetime(2015, 9, 3),
ends=datetime.datetime(2015, 9, 3),
title='Test title',
osm_map_link='http://openstreetmap.org/',
description='Test description',
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Test title' in resp.content)
| import datetime
from django_webtest import WebTest
from pylab.core.models import Event
from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
| Use factories instead of creating instance from model | Use factories instead of creating instance from model
| Python | agpl-3.0 | python-dirbtuves/website,python-dirbtuves/website,python-dirbtuves/website | import datetime
from django_webtest import WebTest
- from django.contrib.auth.models import User
from pylab.core.models import Event
+ from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
-
- def setUp(self):
- self.user = User.objects.create(username='u1')
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
- Event.objects.create(
- author=self.user,
+ EventFactory(
+ event_type=Event.WEEKLY_MEETING,
+ title='Summer Python workshop',
+ slug='python-workshop',
- starts=datetime.datetime(2015, 9, 3),
+ starts=datetime.datetime(2015, 7, 30, 18, 0),
- ends=datetime.datetime(2015, 9, 3),
+ ends=datetime.datetime(2015, 7, 30, 20, 0),
- title='Test title',
- osm_map_link='http://openstreetmap.org/',
- description='Test description',
)
+
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
- self.assertTrue(b'Test title' in resp.content)
+ self.assertTrue(b'Summer Python workshop' in resp.content)
| Use factories instead of creating instance from model | ## Code Before:
import datetime
from django_webtest import WebTest
from django.contrib.auth.models import User
from pylab.core.models import Event
class AboutPageTests(WebTest):
def setUp(self):
self.user = User.objects.create(username='u1')
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
Event.objects.create(
author=self.user,
starts=datetime.datetime(2015, 9, 3),
ends=datetime.datetime(2015, 9, 3),
title='Test title',
osm_map_link='http://openstreetmap.org/',
description='Test description',
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Test title' in resp.content)
## Instruction:
Use factories instead of creating instance from model
## Code After:
import datetime
from django_webtest import WebTest
from pylab.core.models import Event
from pylab.core.factories import EventFactory
class AboutPageTests(WebTest):
def test_no_events_on_about_page(self):
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'No events yet.' in resp.content)
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
| # ... existing code ...
from django_webtest import WebTest
# ... modified code ...
from pylab.core.models import Event
from pylab.core.factories import EventFactory
...
class AboutPageTests(WebTest):
...
def test_event_list_on_about_page(self):
EventFactory(
event_type=Event.WEEKLY_MEETING,
title='Summer Python workshop',
slug='python-workshop',
starts=datetime.datetime(2015, 7, 30, 18, 0),
ends=datetime.datetime(2015, 7, 30, 20, 0),
)
resp = self.app.get('/about/')
...
self.assertEqual(resp.status_int, 200)
self.assertTrue(b'Summer Python workshop' in resp.content)
# ... rest of the code ... |
6cd9c7285d462311580754229d0b85af844dd387 | test/integration/test_cli.py | test/integration/test_cli.py | import unittest
class TestCLI(unittest.TestCase):
def test_kubos_installed(self):
self.assertEqual('foo'.upper(), 'FOO')
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
| import unittest
import re
import subprocess
class TestCLI(unittest.TestCase):
def test_latest_kubos_installed(self):
bashCommand = "vagrant ssh -c 'kubos update'"
process = subprocess.Popen(bashCommand.split())
output, error = process.communicate()
regex = re.compile(r"All up to date!")
self.assertTrue(regex.search( output ))
if __name__ == '__main__':
unittest.main()
| Update integration test with actual...integration test | Update integration test with actual...integration test
| Python | apache-2.0 | Psykar/kubos,kubostech/KubOS,Psykar/kubos,Psykar/kubos,Psykar/kubos,kubostech/KubOS,Psykar/kubos,Psykar/kubos,Psykar/kubos | import unittest
+ import re
+ import subprocess
class TestCLI(unittest.TestCase):
-
- def test_kubos_installed(self):
+ def test_latest_kubos_installed(self):
+ bashCommand = "vagrant ssh -c 'kubos update'"
+ process = subprocess.Popen(bashCommand.split())
+ output, error = process.communicate()
+ regex = re.compile(r"All up to date!")
+ self.assertTrue(regex.search( output ))
- self.assertEqual('foo'.upper(), 'FOO')
- self.assertTrue('FOO'.isupper())
- self.assertFalse('Foo'.isupper())
- s = 'hello world'
- self.assertEqual(s.split(), ['hello', 'world'])
- # check that s.split fails when the separator is not a string
- with self.assertRaises(TypeError):
- s.split(2)
if __name__ == '__main__':
unittest.main()
| Update integration test with actual...integration test | ## Code Before:
import unittest
class TestCLI(unittest.TestCase):
def test_kubos_installed(self):
self.assertEqual('foo'.upper(), 'FOO')
self.assertTrue('FOO'.isupper())
self.assertFalse('Foo'.isupper())
s = 'hello world'
self.assertEqual(s.split(), ['hello', 'world'])
# check that s.split fails when the separator is not a string
with self.assertRaises(TypeError):
s.split(2)
if __name__ == '__main__':
unittest.main()
## Instruction:
Update integration test with actual...integration test
## Code After:
import unittest
import re
import subprocess
class TestCLI(unittest.TestCase):
def test_latest_kubos_installed(self):
bashCommand = "vagrant ssh -c 'kubos update'"
process = subprocess.Popen(bashCommand.split())
output, error = process.communicate()
regex = re.compile(r"All up to date!")
self.assertTrue(regex.search( output ))
if __name__ == '__main__':
unittest.main()
| # ... existing code ...
import unittest
import re
import subprocess
# ... modified code ...
class TestCLI(unittest.TestCase):
def test_latest_kubos_installed(self):
bashCommand = "vagrant ssh -c 'kubos update'"
process = subprocess.Popen(bashCommand.split())
output, error = process.communicate()
regex = re.compile(r"All up to date!")
self.assertTrue(regex.search( output ))
# ... rest of the code ... |
6ccc4a267f939d60ab8948874d9b066ff2b2e5ee | grader/grader/test/test_build.py | grader/grader/test/test_build.py | import os
import pytest
from subprocess import Popen, PIPE
def has_installed(program):
"""Checks to see if a program is installed using ``which``.
:param str program: the name of the program we're looking for
:rtype bool:
:return: True if it's installed, otherwise False.
"""
proc = Popen(["which", program], stdout=PIPE, stderr=PIPE)
exit_code = proc.wait()
return exit_code == 0
hasdocker = pytest.mark.skipif(not has_installed("docker"),
reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""
@hasdocker
def test_build(parse_and_run):
"""Test vanilla assignment build
"""
path = parse_and_run(["init", "cpl"])
parse_and_run(["new", "a1"])
dockerfile_path = os.path.join(path, "assignments", "a1",
"gradesheet", "Dockerfile")
with open(dockerfile_path, 'w') as dockerfile:
dockerfile.write("FROM ubuntu:12.04")
parse_and_run(["build", "a1"])
| import os
import pytest
import shutil
hasdocker = pytest.mark.skipif(shutil.which("docker") is None,
reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""
@hasdocker
def test_build(parse_and_run):
"""Test vanilla assignment build
"""
path = parse_and_run(["init", "cpl"])
parse_and_run(["new", "a1"])
dockerfile_path = os.path.join(path, "assignments", "a1",
"gradesheet", "Dockerfile")
with open(dockerfile_path, 'w') as dockerfile:
dockerfile.write("FROM ubuntu:12.04")
parse_and_run(["build", "a1"])
| Use shutil for 'which docker' | Use shutil for 'which docker'
| Python | mit | redkyn/grader,redkyn/grader,grade-it/grader | import os
import pytest
+ import shutil
-
- from subprocess import Popen, PIPE
+ hasdocker = pytest.mark.skipif(shutil.which("docker") is None,
- def has_installed(program):
- """Checks to see if a program is installed using ``which``.
-
- :param str program: the name of the program we're looking for
-
- :rtype bool:
-
- :return: True if it's installed, otherwise False.
-
- """
- proc = Popen(["which", program], stdout=PIPE, stderr=PIPE)
- exit_code = proc.wait()
- return exit_code == 0
-
-
- hasdocker = pytest.mark.skipif(not has_installed("docker"),
reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""
@hasdocker
def test_build(parse_and_run):
"""Test vanilla assignment build
"""
path = parse_and_run(["init", "cpl"])
parse_and_run(["new", "a1"])
dockerfile_path = os.path.join(path, "assignments", "a1",
"gradesheet", "Dockerfile")
with open(dockerfile_path, 'w') as dockerfile:
dockerfile.write("FROM ubuntu:12.04")
parse_and_run(["build", "a1"])
| Use shutil for 'which docker' | ## Code Before:
import os
import pytest
from subprocess import Popen, PIPE
def has_installed(program):
"""Checks to see if a program is installed using ``which``.
:param str program: the name of the program we're looking for
:rtype bool:
:return: True if it's installed, otherwise False.
"""
proc = Popen(["which", program], stdout=PIPE, stderr=PIPE)
exit_code = proc.wait()
return exit_code == 0
hasdocker = pytest.mark.skipif(not has_installed("docker"),
reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""
@hasdocker
def test_build(parse_and_run):
"""Test vanilla assignment build
"""
path = parse_and_run(["init", "cpl"])
parse_and_run(["new", "a1"])
dockerfile_path = os.path.join(path, "assignments", "a1",
"gradesheet", "Dockerfile")
with open(dockerfile_path, 'w') as dockerfile:
dockerfile.write("FROM ubuntu:12.04")
parse_and_run(["build", "a1"])
## Instruction:
Use shutil for 'which docker'
## Code After:
import os
import pytest
import shutil
hasdocker = pytest.mark.skipif(shutil.which("docker") is None,
reason="Docker must be installed.")
"""A decorator to skip a test if docker is not installed."""
@hasdocker
def test_build(parse_and_run):
"""Test vanilla assignment build
"""
path = parse_and_run(["init", "cpl"])
parse_and_run(["new", "a1"])
dockerfile_path = os.path.join(path, "assignments", "a1",
"gradesheet", "Dockerfile")
with open(dockerfile_path, 'w') as dockerfile:
dockerfile.write("FROM ubuntu:12.04")
parse_and_run(["build", "a1"])
| # ... existing code ...
import pytest
import shutil
# ... modified code ...
hasdocker = pytest.mark.skipif(shutil.which("docker") is None,
reason="Docker must be installed.")
# ... rest of the code ... |
5d5f8e02efa6854bef0813e0e8383a3760cf93d2 | os_brick/privileged/__init__.py | os_brick/privileged/__init__.py |
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=[c.CAP_SYS_ADMIN],
)
|
import os
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
capabilities = [c.CAP_SYS_ADMIN]
# On virtual environments libraries are not owned by the Daemon user (root), so
# the Daemon needs the capability to bypass file read permission checks in
# order to dynamically load the code to run.
if os.environ.get('VIRTUAL_ENV'):
capabilities.append(c.CAP_DAC_READ_SEARCH)
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=capabilities,
)
| Fix os-brick in virtual environments | Fix os-brick in virtual environments
When running os-brick in a virtual environment created by a non root
user, we get the following error:
ModuleNotFoundError: No module named 'os_brick.privileged.rootwrap'
This happens because the privsep daemon drops all the privileged except
those defined in the context, and our current context doesn't bypass
file read permission checks, so the Daemon cannot read the file with the
code it was asked to run, because it belongs to a different user.
This patch adds the CAP_DAC_READ_SEARCH capability to our privsep
context so we can load the libraries, but only when we are running on a
virtual environment to follow the principle of least privilege.
This bug doesn't affect system-wide installations because the files
installed under /sys/python*/site-packages belong to the Daemon user
(root), so no special capabilities are necessary.
Change-Id: Ib191c075ad1250822f6ac842f39214af8f3a02f0
Close-Bug: #1884059
| Python | apache-2.0 | openstack/os-brick,openstack/os-brick | +
+ import os
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
+
+
+ capabilities = [c.CAP_SYS_ADMIN]
+
+ # On virtual environments libraries are not owned by the Daemon user (root), so
+ # the Daemon needs the capability to bypass file read permission checks in
+ # order to dynamically load the code to run.
+ if os.environ.get('VIRTUAL_ENV'):
+ capabilities.append(c.CAP_DAC_READ_SEARCH)
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
- capabilities=[c.CAP_SYS_ADMIN],
+ capabilities=capabilities,
)
| Fix os-brick in virtual environments | ## Code Before:
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=[c.CAP_SYS_ADMIN],
)
## Instruction:
Fix os-brick in virtual environments
## Code After:
import os
from oslo_privsep import capabilities as c
from oslo_privsep import priv_context
capabilities = [c.CAP_SYS_ADMIN]
# On virtual environments libraries are not owned by the Daemon user (root), so
# the Daemon needs the capability to bypass file read permission checks in
# order to dynamically load the code to run.
if os.environ.get('VIRTUAL_ENV'):
capabilities.append(c.CAP_DAC_READ_SEARCH)
# It is expected that most (if not all) os-brick operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep_osbrick',
pypath=__name__ + '.default',
capabilities=capabilities,
)
| # ... existing code ...
import os
# ... modified code ...
from oslo_privsep import priv_context
capabilities = [c.CAP_SYS_ADMIN]
# On virtual environments libraries are not owned by the Daemon user (root), so
# the Daemon needs the capability to bypass file read permission checks in
# order to dynamically load the code to run.
if os.environ.get('VIRTUAL_ENV'):
capabilities.append(c.CAP_DAC_READ_SEARCH)
...
pypath=__name__ + '.default',
capabilities=capabilities,
)
# ... rest of the code ... |
848d783bd988e0cdf31b690f17837ac02e77b43a | pypodio2/client.py | pypodio2/client.py |
from . import areas
class FailedRequest(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return repr(self.error)
class Client(object):
"""
The Podio API client. Callers should use the factory method OAuthClient to create instances.
"""
def __init__(self, transport):
self.transport = transport
def __getattr__(self, name):
new_trans = self.transport
area = getattr(areas, name)
return area(new_trans)
|
from . import areas
class FailedRequest(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return repr(self.error)
class Client(object):
"""
The Podio API client. Callers should use the factory method OAuthClient to create instances.
"""
def __init__(self, transport):
self.transport = transport
def __getattr__(self, name):
new_trans = self.transport
area = getattr(areas, name)
return area(new_trans)
def __dir__(self):
"""
Should return list of attribute names.
Since __getattr__ looks in areas, we simply list the content of the areas module
"""
return dir(areas)
| Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc. | Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
| Python | mit | podio/podio-py |
from . import areas
class FailedRequest(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return repr(self.error)
class Client(object):
"""
The Podio API client. Callers should use the factory method OAuthClient to create instances.
"""
def __init__(self, transport):
self.transport = transport
def __getattr__(self, name):
new_trans = self.transport
area = getattr(areas, name)
return area(new_trans)
+ def __dir__(self):
+ """
+ Should return list of attribute names.
+ Since __getattr__ looks in areas, we simply list the content of the areas module
+ """
+ return dir(areas)
+ | Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc. | ## Code Before:
from . import areas
class FailedRequest(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return repr(self.error)
class Client(object):
"""
The Podio API client. Callers should use the factory method OAuthClient to create instances.
"""
def __init__(self, transport):
self.transport = transport
def __getattr__(self, name):
new_trans = self.transport
area = getattr(areas, name)
return area(new_trans)
## Instruction:
Add __dir__ method to Client in order to allow autocompletion in interactive terminals, etc.
## Code After:
from . import areas
class FailedRequest(Exception):
def __init__(self, error):
self.error = error
def __str__(self):
return repr(self.error)
class Client(object):
"""
The Podio API client. Callers should use the factory method OAuthClient to create instances.
"""
def __init__(self, transport):
self.transport = transport
def __getattr__(self, name):
new_trans = self.transport
area = getattr(areas, name)
return area(new_trans)
def __dir__(self):
"""
Should return list of attribute names.
Since __getattr__ looks in areas, we simply list the content of the areas module
"""
return dir(areas)
| # ... existing code ...
return area(new_trans)
def __dir__(self):
"""
Should return list of attribute names.
Since __getattr__ looks in areas, we simply list the content of the areas module
"""
return dir(areas)
# ... rest of the code ... |
0722b517f5b5b9a84b7521b6b7d350cbc6537948 | src/core/models.py | src/core/models.py | from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
"""
presumed_type = super().db_type(connection)
if presumed_type == 'integer':
return 'bigint'
return presumed_type
| from django.apps import apps
from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
Django's AutoField is actually an IntegerField (SQL integer field),
but in some cases we are using bigint on PostgreSQL without Django
knowing it. So we continue to trick Django here, swapping its field
type detection, and just tells it to use bigint.
:seealso: Migrations in the ``postgres`` app.
"""
presumed_type = super().db_type(connection)
if apps.is_installed('postgres') and presumed_type == 'integer':
return 'bigint'
return presumed_type
| Add some explaination on BigForeignKey | Add some explaination on BigForeignKey
| Python | mit | uranusjr/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,pycontw/pycontw2016,uranusjr/pycontw2016,uranusjr/pycontw2016 | + from django.apps import apps
from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
+
+ Django's AutoField is actually an IntegerField (SQL integer field),
+ but in some cases we are using bigint on PostgreSQL without Django
+ knowing it. So we continue to trick Django here, swapping its field
+ type detection, and just tells it to use bigint.
+
+ :seealso: Migrations in the ``postgres`` app.
"""
presumed_type = super().db_type(connection)
- if presumed_type == 'integer':
+ if apps.is_installed('postgres') and presumed_type == 'integer':
return 'bigint'
return presumed_type
| Add some explaination on BigForeignKey | ## Code Before:
from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
"""
presumed_type = super().db_type(connection)
if presumed_type == 'integer':
return 'bigint'
return presumed_type
## Instruction:
Add some explaination on BigForeignKey
## Code After:
from django.apps import apps
from django.db import models
class BigForeignKey(models.ForeignKey):
def db_type(self, connection):
""" Adds support for foreign keys to big integers as primary keys.
Django's AutoField is actually an IntegerField (SQL integer field),
but in some cases we are using bigint on PostgreSQL without Django
knowing it. So we continue to trick Django here, swapping its field
type detection, and just tells it to use bigint.
:seealso: Migrations in the ``postgres`` app.
"""
presumed_type = super().db_type(connection)
if apps.is_installed('postgres') and presumed_type == 'integer':
return 'bigint'
return presumed_type
| // ... existing code ...
from django.apps import apps
from django.db import models
// ... modified code ...
""" Adds support for foreign keys to big integers as primary keys.
Django's AutoField is actually an IntegerField (SQL integer field),
but in some cases we are using bigint on PostgreSQL without Django
knowing it. So we continue to trick Django here, swapping its field
type detection, and just tells it to use bigint.
:seealso: Migrations in the ``postgres`` app.
"""
...
presumed_type = super().db_type(connection)
if apps.is_installed('postgres') and presumed_type == 'integer':
return 'bigint'
// ... rest of the code ... |
7a7856d9ec56de91325c7bf7c62ff25c0241badc | tests/test_connect.py | tests/test_connect.py | import pypuppetdb
def test_connect_api():
puppetdb = pypuppetdb.connect()
assert puppetdb.version == 'v4'
| import pypuppetdb
def test_connect_api():
puppetdb = pypuppetdb.connect()
assert puppetdb.version == 'v4'
def test_connect_with_statement():
with pypuppetdb.connect() as puppetdb:
assert puppetdb.version == 'v4'
| Add test for creating connection with 'with' statement. | Add test for creating connection with 'with' statement.
| Python | apache-2.0 | puppet-community/pypuppetdb,voxpupuli/pypuppetdb | import pypuppetdb
def test_connect_api():
puppetdb = pypuppetdb.connect()
assert puppetdb.version == 'v4'
+
+ def test_connect_with_statement():
+ with pypuppetdb.connect() as puppetdb:
+ assert puppetdb.version == 'v4'
+ | Add test for creating connection with 'with' statement. | ## Code Before:
import pypuppetdb
def test_connect_api():
puppetdb = pypuppetdb.connect()
assert puppetdb.version == 'v4'
## Instruction:
Add test for creating connection with 'with' statement.
## Code After:
import pypuppetdb
def test_connect_api():
puppetdb = pypuppetdb.connect()
assert puppetdb.version == 'v4'
def test_connect_with_statement():
with pypuppetdb.connect() as puppetdb:
assert puppetdb.version == 'v4'
| ...
assert puppetdb.version == 'v4'
def test_connect_with_statement():
with pypuppetdb.connect() as puppetdb:
assert puppetdb.version == 'v4'
... |
312bb90415218398ddbe9250cfe7dbc4bb013e14 | opal/core/lookuplists.py | opal/core/lookuplists.py | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
| from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| Delete commented out old code. | Delete commented out old code.
| Python | agpl-3.0 | khchine5/opal,khchine5/opal,khchine5/opal | from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
-
- # class LookupList(models.Model):
- # class Meta:
- # abstract = True
-
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
-
- # def lookup_list(name, module=__name__):
- # """
- # Given the name of a lookup list, return the tuple of class_name, bases, attrs
- # for the user to define the class
- # """
- # prefix = 'Lookup List: '
- # class_name = name.capitalize() # TODO handle camelcase properly
- # bases = (LookupList,)
- # attrs = {
- # 'name': models.CharField(max_length=255, unique=True),
- # 'synonyms': generic.GenericRelation('opal.Synonym'),
- # 'Meta': type('Meta', (object,), {'ordering': ['name'],
- # 'verbose_name': prefix+name}),
- # '__unicode__': lambda self: self.name,
- # '__module__': module,
- # }
- # return class_name, bases, attrs
- | Delete commented out old code. | ## Code Before:
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
# class LookupList(models.Model):
# class Meta:
# abstract = True
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
# def lookup_list(name, module=__name__):
# """
# Given the name of a lookup list, return the tuple of class_name, bases, attrs
# for the user to define the class
# """
# prefix = 'Lookup List: '
# class_name = name.capitalize() # TODO handle camelcase properly
# bases = (LookupList,)
# attrs = {
# 'name': models.CharField(max_length=255, unique=True),
# 'synonyms': generic.GenericRelation('opal.Synonym'),
# 'Meta': type('Meta', (object,), {'ordering': ['name'],
# 'verbose_name': prefix+name}),
# '__unicode__': lambda self: self.name,
# '__module__': module,
# }
# return class_name, bases, attrs
## Instruction:
Delete commented out old code.
## Code After:
from django.contrib.contenttypes.fields import GenericRelation
from django.db import models
class LookupList(models.Model):
name = models.CharField(max_length=255, unique=True)
synonyms = GenericRelation('opal.Synonym')
class Meta:
ordering = ['name']
abstract = True
def __unicode__(self):
return self.name
def to_dict(self, user):
return self.name
| # ... existing code ...
from django.db import models
# ... modified code ...
return self.name
# ... rest of the code ... |
1eab43e1b1402a53c2dec53abe61bcae5f4b3026 | robots/admin.py | robots/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
| from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
filter_horizontal = ('allowed', 'disallowed')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
| Add filter_horizontal for for allowed and disallowed | Add filter_horizontal for for allowed and disallowed
| Python | bsd-3-clause | jazzband/django-robots,jezdez/django-robots,jezdez/django-robots,jscott1971/django-robots,jscott1971/django-robots,jazzband/django-robots | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
+ filter_horizontal = ('allowed', 'disallowed')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
| Add filter_horizontal for for allowed and disallowed | ## Code Before:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
## Instruction:
Add filter_horizontal for for allowed and disallowed
## Code After:
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from robots.models import Url, Rule
from robots.forms import RuleAdminForm
class RuleAdmin(admin.ModelAdmin):
form = RuleAdminForm
fieldsets = (
(None, {'fields': ('robot', 'sites')}),
(_('URL patterns'), {
'fields': ('allowed', 'disallowed'),
}),
(_('Advanced options'), {
'classes': ('collapse',),
'fields': ('crawl_delay',),
}),
)
list_filter = ('sites',)
list_display = ('robot', 'allowed_urls', 'disallowed_urls')
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
filter_horizontal = ('allowed', 'disallowed')
admin.site.register(Url)
admin.site.register(Rule, RuleAdmin)
| ...
search_fields = ('robot', 'allowed__pattern', 'disallowed__pattern')
filter_horizontal = ('allowed', 'disallowed')
... |
828d03d7a49d65e8584d4bc373ae4d429b291104 | tests/test_tensorflow_addons.py | tests/test_tensorflow_addons.py | import unittest
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
mean = tfa.image.mean_filter2d(img, filter_shape=1)
self.assertEqual(1, len(mean)) | import unittest
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
mean = tfa.image.mean_filter2d(img, filter_shape=1)
self.assertEqual(1, len(mean))
# This test exercises TFA Custom Op. See: b/145555176
def test_gelu(self):
x = tf.constant([[0.5, 1.2, -0.3]])
layer = tfa.layers.GELU()
result = layer(x)
self.assertEqual((1, 3), result.shape) | Add a test exercising TFA custom op. | Add a test exercising TFA custom op.
To prevent future regression.
BUG=145555176
| Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | import unittest
+ import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
mean = tfa.image.mean_filter2d(img, filter_shape=1)
self.assertEqual(1, len(mean))
+
+ # This test exercises TFA Custom Op. See: b/145555176
+ def test_gelu(self):
+ x = tf.constant([[0.5, 1.2, -0.3]])
+ layer = tfa.layers.GELU()
+ result = layer(x)
+
+ self.assertEqual((1, 3), result.shape) | Add a test exercising TFA custom op. | ## Code Before:
import unittest
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
mean = tfa.image.mean_filter2d(img, filter_shape=1)
self.assertEqual(1, len(mean))
## Instruction:
Add a test exercising TFA custom op.
## Code After:
import unittest
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
class TestTensorflowAddons(unittest.TestCase):
def test_tfa_image(self):
img_raw = tf.io.read_file('/input/tests/data/dot.png')
img = tf.io.decode_image(img_raw)
img = tf.image.convert_image_dtype(img, tf.float32)
mean = tfa.image.mean_filter2d(img, filter_shape=1)
self.assertEqual(1, len(mean))
# This test exercises TFA Custom Op. See: b/145555176
def test_gelu(self):
x = tf.constant([[0.5, 1.2, -0.3]])
layer = tfa.layers.GELU()
result = layer(x)
self.assertEqual((1, 3), result.shape) | // ... existing code ...
import numpy as np
import tensorflow as tf
// ... modified code ...
self.assertEqual(1, len(mean))
# This test exercises TFA Custom Op. See: b/145555176
def test_gelu(self):
x = tf.constant([[0.5, 1.2, -0.3]])
layer = tfa.layers.GELU()
result = layer(x)
self.assertEqual((1, 3), result.shape)
// ... rest of the code ... |
f3df3b2b8e1167e953457a85f2297d28b6a39729 | examples/Micro.Blog/microblog.py | examples/Micro.Blog/microblog.py | from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', token=''):
self.token = token
super(self.__class__, self).__init__(path, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', path_params=None, token=''):
self.token = token
super(self.__class__, self).__init__(path, path_params, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| Include path_params in override constructor | Include path_params in override constructor
| Python | mit | andymitchhank/bessie | from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
- def __init__(self, path='', token=''):
+ def __init__(self, path='', path_params=None, token=''):
self.token = token
- super(self.__class__, self).__init__(path, token=token)
+ super(self.__class__, self).__init__(path, path_params, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| Include path_params in override constructor | ## Code Before:
from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', token=''):
self.token = token
super(self.__class__, self).__init__(path, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
## Instruction:
Include path_params in override constructor
## Code After:
from getpass import getpass
from bessie import BaseClient
import config
class MicroBlogApi(BaseClient):
endpoints = config.available_endpoints
separator = '/'
base_url='https://micro.blog'
def __init__(self, path='', path_params=None, token=''):
self.token = token
super(self.__class__, self).__init__(path, path_params, token=token)
# override method from BaseClient to inject Authorization header
def _prepare_request(self):
super(self.__class__, self)._prepare_request()
self.request.headers['Authorization'] = 'Token {}'.format(self.token)
if __name__ == '__main__':
token = getpass('Token... ')
mba = MicroBlogApi(token=token)
# GET - https://micro.blog/posts/all
posts = mba.posts.all.get()
print(posts.status_code, posts.reason)
print(posts.json())
| # ... existing code ...
def __init__(self, path='', path_params=None, token=''):
self.token = token
super(self.__class__, self).__init__(path, path_params, token=token)
# ... rest of the code ... |
d9d2c7d341894e28a5ad73469ec0d9d23d78429e | vispy/visuals/graphs/layouts/__init__.py | vispy/visuals/graphs/layouts/__init__.py | from .random import random # noqa
from .circular import circular # noqa
| import inspect
from .random import random
from .circular import circular
from .force_directed import fruchterman_reingold
_layout_map = {
'random': random,
'circular': circular,
'force_directed': fruchterman_reingold
}
def get(name, *args, **kwargs):
if name not in _layout_map:
raise KeyError("Graph layout '{}' not found.".format(name))
layout = _layout_map[name]
if inspect.isclass(layout):
layout = layout(*args, **kwargs)
return layout
| Add new way of retreiving graph layouts | Add new way of retreiving graph layouts
| Python | bsd-3-clause | ghisvail/vispy,michaelaye/vispy,Eric89GXL/vispy,michaelaye/vispy,Eric89GXL/vispy,Eric89GXL/vispy,drufat/vispy,drufat/vispy,ghisvail/vispy,michaelaye/vispy,drufat/vispy,ghisvail/vispy | + import inspect
- from .random import random # noqa
- from .circular import circular # noqa
+ from .random import random
+ from .circular import circular
+ from .force_directed import fruchterman_reingold
+
+
+ _layout_map = {
+ 'random': random,
+ 'circular': circular,
+ 'force_directed': fruchterman_reingold
+ }
+
+
+ def get(name, *args, **kwargs):
+ if name not in _layout_map:
+ raise KeyError("Graph layout '{}' not found.".format(name))
+
+ layout = _layout_map[name]
+
+ if inspect.isclass(layout):
+ layout = layout(*args, **kwargs)
+
+ return layout
+ | Add new way of retreiving graph layouts | ## Code Before:
from .random import random # noqa
from .circular import circular # noqa
## Instruction:
Add new way of retreiving graph layouts
## Code After:
import inspect
from .random import random
from .circular import circular
from .force_directed import fruchterman_reingold
_layout_map = {
'random': random,
'circular': circular,
'force_directed': fruchterman_reingold
}
def get(name, *args, **kwargs):
if name not in _layout_map:
raise KeyError("Graph layout '{}' not found.".format(name))
layout = _layout_map[name]
if inspect.isclass(layout):
layout = layout(*args, **kwargs)
return layout
| # ... existing code ...
import inspect
from .random import random
from .circular import circular
from .force_directed import fruchterman_reingold
_layout_map = {
'random': random,
'circular': circular,
'force_directed': fruchterman_reingold
}
def get(name, *args, **kwargs):
if name not in _layout_map:
raise KeyError("Graph layout '{}' not found.".format(name))
layout = _layout_map[name]
if inspect.isclass(layout):
layout = layout(*args, **kwargs)
return layout
# ... rest of the code ... |
3ffd3eb8f32fbac7df0f6967b9d6f0437ff3a317 | movieman2/__init__.py | movieman2/__init__.py | import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
| import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| Load API_KEY from django settings.py file as an alternative | Load API_KEY from django settings.py file as an alternative
| Python | mit | simon-andrews/movieman2,simon-andrews/movieman2 | import os
import tmdbsimple
+ from django.conf import settings
- tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
+ tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| Load API_KEY from django settings.py file as an alternative | ## Code Before:
import os
import tmdbsimple
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY']
## Instruction:
Load API_KEY from django settings.py file as an alternative
## Code After:
import os
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
| # ... existing code ...
import tmdbsimple
from django.conf import settings
tmdbsimple.API_KEY = os.environ['MM2_TMDB_API_KEY'] or settings.MM2_TMDB_API_KEY
# ... rest of the code ... |
58d11644b08a91ab1e71f697741197f1b697d817 | tests/request/test_request_header.py | tests/request/test_request_header.py | def test_multiple_same_headers():
pass
def test_header_case_insensitivity():
pass
def test_header_with_continuation_lines():
pass
def test_request_without_headers():
pass
def test_invalid_header_syntax():
pass
| from httoop import Headers, InvalidHeader
def test_multiple_same_headers():
pass
def test_header_case_insensitivity():
pass
def test_header_with_continuation_lines():
h = Headers()
h.parse('Foo: bar\r\n baz')
h.parse('Foo2: bar\r\n\tbaz')
h.parse('Foo3: bar\r\n baz')
h.parse('Foo4: bar\r\n\t baz')
assert h['Foo'] == 'barbaz'
assert h['Foo2'] == 'barbaz'
assert h['Foo3'] == 'bar baz'
assert h['Foo4'] == 'bar baz'
def test_request_without_headers():
pass
def test_invalid_header_syntax():
h = Headers()
invalid_headers = ['Foo']
for char in b"%s\x7F()<>@,;\\\\\"/\[\]?={} \t%s" % (b''.join(map(chr, range(0x00, 0x1F))), ''.join(map(chr, range(0x80, 0xFF)))):
invalid_headers.append(b'Fo%so: bar' % (char,))
for invalid in invalid_headers:
try:
h.parse(invalid)
except InvalidHeader:
pass
else:
assert False, 'Invalid header %r parsed successfully' % (invalid,)
| Add test case for invalid headers and continuation lines | Add test case for invalid headers and continuation lines
| Python | mit | spaceone/httoop,spaceone/httoop,spaceone/httoop | + from httoop import Headers, InvalidHeader
+
def test_multiple_same_headers():
pass
def test_header_case_insensitivity():
pass
def test_header_with_continuation_lines():
- pass
+ h = Headers()
+ h.parse('Foo: bar\r\n baz')
+ h.parse('Foo2: bar\r\n\tbaz')
+ h.parse('Foo3: bar\r\n baz')
+ h.parse('Foo4: bar\r\n\t baz')
+ assert h['Foo'] == 'barbaz'
+ assert h['Foo2'] == 'barbaz'
+ assert h['Foo3'] == 'bar baz'
+ assert h['Foo4'] == 'bar baz'
def test_request_without_headers():
pass
def test_invalid_header_syntax():
+ h = Headers()
+ invalid_headers = ['Foo']
+ for char in b"%s\x7F()<>@,;\\\\\"/\[\]?={} \t%s" % (b''.join(map(chr, range(0x00, 0x1F))), ''.join(map(chr, range(0x80, 0xFF)))):
+ invalid_headers.append(b'Fo%so: bar' % (char,))
+ for invalid in invalid_headers:
+ try:
+ h.parse(invalid)
+ except InvalidHeader:
- pass
+ pass
+ else:
+ assert False, 'Invalid header %r parsed successfully' % (invalid,)
| Add test case for invalid headers and continuation lines | ## Code Before:
def test_multiple_same_headers():
pass
def test_header_case_insensitivity():
pass
def test_header_with_continuation_lines():
pass
def test_request_without_headers():
pass
def test_invalid_header_syntax():
pass
## Instruction:
Add test case for invalid headers and continuation lines
## Code After:
from httoop import Headers, InvalidHeader
def test_multiple_same_headers():
pass
def test_header_case_insensitivity():
pass
def test_header_with_continuation_lines():
h = Headers()
h.parse('Foo: bar\r\n baz')
h.parse('Foo2: bar\r\n\tbaz')
h.parse('Foo3: bar\r\n baz')
h.parse('Foo4: bar\r\n\t baz')
assert h['Foo'] == 'barbaz'
assert h['Foo2'] == 'barbaz'
assert h['Foo3'] == 'bar baz'
assert h['Foo4'] == 'bar baz'
def test_request_without_headers():
pass
def test_invalid_header_syntax():
h = Headers()
invalid_headers = ['Foo']
for char in b"%s\x7F()<>@,;\\\\\"/\[\]?={} \t%s" % (b''.join(map(chr, range(0x00, 0x1F))), ''.join(map(chr, range(0x80, 0xFF)))):
invalid_headers.append(b'Fo%so: bar' % (char,))
for invalid in invalid_headers:
try:
h.parse(invalid)
except InvalidHeader:
pass
else:
assert False, 'Invalid header %r parsed successfully' % (invalid,)
| # ... existing code ...
from httoop import Headers, InvalidHeader
def test_multiple_same_headers():
# ... modified code ...
def test_header_with_continuation_lines():
h = Headers()
h.parse('Foo: bar\r\n baz')
h.parse('Foo2: bar\r\n\tbaz')
h.parse('Foo3: bar\r\n baz')
h.parse('Foo4: bar\r\n\t baz')
assert h['Foo'] == 'barbaz'
assert h['Foo2'] == 'barbaz'
assert h['Foo3'] == 'bar baz'
assert h['Foo4'] == 'bar baz'
...
def test_invalid_header_syntax():
h = Headers()
invalid_headers = ['Foo']
for char in b"%s\x7F()<>@,;\\\\\"/\[\]?={} \t%s" % (b''.join(map(chr, range(0x00, 0x1F))), ''.join(map(chr, range(0x80, 0xFF)))):
invalid_headers.append(b'Fo%so: bar' % (char,))
for invalid in invalid_headers:
try:
h.parse(invalid)
except InvalidHeader:
pass
else:
assert False, 'Invalid header %r parsed successfully' % (invalid,)
# ... rest of the code ... |
7a448c4df3feb717d0b1d8abbf9d32237751aab5 | nbgrader/tests/apps/test_nbgrader_extension.py | nbgrader/tests/apps/test_nbgrader_extension.py | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 3
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 2
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
| import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment'
| Fix tests for nbgrader extensions | Fix tests for nbgrader extensions
| Python | bsd-3-clause | jhamrick/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jupyter/nbgrader,jhamrick/nbgrader | import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
- assert len(nbexts) == 3
+ assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
+ assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
- assert len(serverexts) == 2
+ assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
+ assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment'
| Fix tests for nbgrader extensions | ## Code Before:
import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 3
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 2
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
## Instruction:
Fix tests for nbgrader extensions
## Code After:
import os
import nbgrader
def test_nbextension():
from nbgrader import _jupyter_nbextension_paths
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
assert nbexts[1]['section'] == 'notebook'
assert nbexts[2]['section'] == 'tree'
assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
for path in paths:
assert os.path.isdir(os.path.join(os.path.dirname(nbgrader.__file__), path))
def test_serverextension():
from nbgrader import _jupyter_server_extension_paths
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment'
| // ... existing code ...
nbexts = _jupyter_nbextension_paths()
assert len(nbexts) == 4
assert nbexts[0]['section'] == 'tree'
// ... modified code ...
assert nbexts[2]['section'] == 'tree'
assert nbexts[3]['section'] == 'notebook'
paths = [ext['src'] for ext in nbexts]
...
serverexts = _jupyter_server_extension_paths()
assert len(serverexts) == 3
assert serverexts[0]['module'] == 'nbgrader.server_extensions.assignment_list'
...
assert serverexts[1]['module'] == 'nbgrader.server_extensions.formgrader'
assert serverexts[2]['module'] == 'nbgrader.server_extensions.validate_assignment'
// ... rest of the code ... |
06cf113cc45e7eaa8ab63e2791c2f2a0990ac946 | EasyEuler/data.py | EasyEuler/data.py | import json
import os
from jinja2 import Environment, FileSystemLoader
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data')
TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates')
CONFIG_PATH = os.path.join(BASE_PATH, 'config.json')
templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH))
with open(CONFIG_PATH) as f:
config = json.load(f)
with open('%s/problems.json' % DATA_PATH) as f:
problems = json.load(f)
| import collections
import json
import os
from jinja2 import Environment, FileSystemLoader
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data')
TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates')
CONFIG_PATH = os.path.join(BASE_PATH, 'config.json')
with open('%s/problems.json' % DATA_PATH) as f:
problems = json.load(f)
class ConfigurationDictionary(collections.MutableMapping):
def __init__(self, config_paths):
self.config = {}
for config_path in config_paths:
if os.path.exists(config_path):
with open(config_path) as f:
self.config = self.update(self.config, json.load(f))
def update(self, config, updates):
for key, value in updates.items():
if isinstance(value, collections.Mapping):
updated = self.update(config.get(key, {}), value)
config[key] = updated
else:
config[key] = value
return config
def __getitem__(self, key):
return self.config[key]
def __setitem__(self, key, value):
self.config[key] = value
def __delitem__(self, key):
del self.config[key]
def __iter__(self):
return iter(self.config)
def __len__(self):
return len(self.config)
home = os.environ.get('HOME')
xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
os.path.join(home, '.config'))
xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg')
config_dirs = [xdg_config_home] + xdg_config_dirs.split(':')
config_paths = [os.path.join(config_dir, 'EasyEuler/config.json')
for config_dir in config_dirs if os.path.isabs(config_dir)]
template_paths = [os.path.join(config_dir, 'EasyEuler/templates')
for config_dir in config_dirs if os.path.isabs(config_dir)]
config_paths.append(CONFIG_PATH)
template_paths.append(TEMPLATE_PATH)
config = ConfigurationDictionary(reversed(config_paths))
templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
| Add support for XDG spec configuration | Add support for XDG spec configuration
| Python | mit | Encrylize/EasyEuler | + import collections
import json
import os
from jinja2 import Environment, FileSystemLoader
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data')
TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates')
CONFIG_PATH = os.path.join(BASE_PATH, 'config.json')
- templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH))
-
- with open(CONFIG_PATH) as f:
- config = json.load(f)
-
with open('%s/problems.json' % DATA_PATH) as f:
problems = json.load(f)
+
+ class ConfigurationDictionary(collections.MutableMapping):
+ def __init__(self, config_paths):
+ self.config = {}
+
+ for config_path in config_paths:
+ if os.path.exists(config_path):
+ with open(config_path) as f:
+ self.config = self.update(self.config, json.load(f))
+
+ def update(self, config, updates):
+ for key, value in updates.items():
+ if isinstance(value, collections.Mapping):
+ updated = self.update(config.get(key, {}), value)
+ config[key] = updated
+ else:
+ config[key] = value
+ return config
+
+ def __getitem__(self, key):
+ return self.config[key]
+
+ def __setitem__(self, key, value):
+ self.config[key] = value
+
+ def __delitem__(self, key):
+ del self.config[key]
+
+ def __iter__(self):
+ return iter(self.config)
+
+ def __len__(self):
+ return len(self.config)
+
+
+ home = os.environ.get('HOME')
+ xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
+ os.path.join(home, '.config'))
+ xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg')
+ config_dirs = [xdg_config_home] + xdg_config_dirs.split(':')
+ config_paths = [os.path.join(config_dir, 'EasyEuler/config.json')
+ for config_dir in config_dirs if os.path.isabs(config_dir)]
+ template_paths = [os.path.join(config_dir, 'EasyEuler/templates')
+ for config_dir in config_dirs if os.path.isabs(config_dir)]
+ config_paths.append(CONFIG_PATH)
+ template_paths.append(TEMPLATE_PATH)
+
+ config = ConfigurationDictionary(reversed(config_paths))
+ templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
+ | Add support for XDG spec configuration | ## Code Before:
import json
import os
from jinja2 import Environment, FileSystemLoader
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data')
TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates')
CONFIG_PATH = os.path.join(BASE_PATH, 'config.json')
templates = Environment(loader=FileSystemLoader(TEMPLATE_PATH))
with open(CONFIG_PATH) as f:
config = json.load(f)
with open('%s/problems.json' % DATA_PATH) as f:
problems = json.load(f)
## Instruction:
Add support for XDG spec configuration
## Code After:
import collections
import json
import os
from jinja2 import Environment, FileSystemLoader
BASE_PATH = os.path.abspath(os.path.dirname(__file__))
DATA_PATH = os.path.join(BASE_PATH, 'data')
TEMPLATE_PATH = os.path.join(BASE_PATH, 'templates')
CONFIG_PATH = os.path.join(BASE_PATH, 'config.json')
with open('%s/problems.json' % DATA_PATH) as f:
problems = json.load(f)
class ConfigurationDictionary(collections.MutableMapping):
def __init__(self, config_paths):
self.config = {}
for config_path in config_paths:
if os.path.exists(config_path):
with open(config_path) as f:
self.config = self.update(self.config, json.load(f))
def update(self, config, updates):
for key, value in updates.items():
if isinstance(value, collections.Mapping):
updated = self.update(config.get(key, {}), value)
config[key] = updated
else:
config[key] = value
return config
def __getitem__(self, key):
return self.config[key]
def __setitem__(self, key, value):
self.config[key] = value
def __delitem__(self, key):
del self.config[key]
def __iter__(self):
return iter(self.config)
def __len__(self):
return len(self.config)
home = os.environ.get('HOME')
xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
os.path.join(home, '.config'))
xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg')
config_dirs = [xdg_config_home] + xdg_config_dirs.split(':')
config_paths = [os.path.join(config_dir, 'EasyEuler/config.json')
for config_dir in config_dirs if os.path.isabs(config_dir)]
template_paths = [os.path.join(config_dir, 'EasyEuler/templates')
for config_dir in config_dirs if os.path.isabs(config_dir)]
config_paths.append(CONFIG_PATH)
template_paths.append(TEMPLATE_PATH)
config = ConfigurationDictionary(reversed(config_paths))
templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
| // ... existing code ...
import collections
import json
// ... modified code ...
with open('%s/problems.json' % DATA_PATH) as f:
...
problems = json.load(f)
class ConfigurationDictionary(collections.MutableMapping):
def __init__(self, config_paths):
self.config = {}
for config_path in config_paths:
if os.path.exists(config_path):
with open(config_path) as f:
self.config = self.update(self.config, json.load(f))
def update(self, config, updates):
for key, value in updates.items():
if isinstance(value, collections.Mapping):
updated = self.update(config.get(key, {}), value)
config[key] = updated
else:
config[key] = value
return config
def __getitem__(self, key):
return self.config[key]
def __setitem__(self, key, value):
self.config[key] = value
def __delitem__(self, key):
del self.config[key]
def __iter__(self):
return iter(self.config)
def __len__(self):
return len(self.config)
home = os.environ.get('HOME')
xdg_config_home = os.environ.get('XDG_CONFIG_HOME',
os.path.join(home, '.config'))
xdg_config_dirs = os.environ.get('XDG_CONFIG_DIRS', '/etc/xdg')
config_dirs = [xdg_config_home] + xdg_config_dirs.split(':')
config_paths = [os.path.join(config_dir, 'EasyEuler/config.json')
for config_dir in config_dirs if os.path.isabs(config_dir)]
template_paths = [os.path.join(config_dir, 'EasyEuler/templates')
for config_dir in config_dirs if os.path.isabs(config_dir)]
config_paths.append(CONFIG_PATH)
template_paths.append(TEMPLATE_PATH)
config = ConfigurationDictionary(reversed(config_paths))
templates = Environment(loader=FileSystemLoader(reversed(template_paths)))
// ... rest of the code ... |
530bd321f38a0131eb250148bd0a67d9a59da34c | uno_image.py | uno_image.py |
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = context
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
ImageExample,
'org.libreoffice.imageexample.ImageExample',
('com.sun.star.task.JobExecutor',))
|
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = context
self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")
def createUnoService(self, name):
return self.context.ServiceManager.createInstanceWithContext(name, self.context)
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
ImageExample,
'org.libreoffice.imageexample.ImageExample',
('com.sun.star.task.JobExecutor',))
| Add code to create needed uno services | Add code to create needed uno services
| Python | mpl-2.0 | JIghtuse/uno-image-manipulation-example |
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = context
+ self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
+ self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")
+
+ def createUnoService(self, name):
+ return self.context.ServiceManager.createInstanceWithContext(name, self.context)
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
ImageExample,
'org.libreoffice.imageexample.ImageExample',
('com.sun.star.task.JobExecutor',))
| Add code to create needed uno services | ## Code Before:
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = context
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
ImageExample,
'org.libreoffice.imageexample.ImageExample',
('com.sun.star.task.JobExecutor',))
## Instruction:
Add code to create needed uno services
## Code After:
import unohelper
from com.sun.star.task import XJobExecutor
class ImageExample(unohelper.Base, XJobExecutor):
'''Class that implements the service registered in LibreOffice'''
def __init__(self, context):
self.context = context
self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")
def createUnoService(self, name):
return self.context.ServiceManager.createInstanceWithContext(name, self.context)
g_ImplementationHelper = unohelper.ImplementationHelper()
g_ImplementationHelper.addImplementation(
ImageExample,
'org.libreoffice.imageexample.ImageExample',
('com.sun.star.task.JobExecutor',))
| ...
self.context = context
self.desktop = self.createUnoService("com.sun.star.frame.Desktop")
self.graphics = self.createUnoService("com.sun.star.graphic.GraphicProvider")
def createUnoService(self, name):
return self.context.ServiceManager.createInstanceWithContext(name, self.context)
... |
70aa7af1a5da51813a09da4f9671e293c4a01d91 | util/connection.py | util/connection.py | import os
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.pool import NullPool
DB_URL = os.environ.get('DB_URL')
if not DB_URL:
raise ValueError("DB_URL not present in the environment")
Base = automap_base()
engine = create_engine(DB_URL, poolclass=NullPool)
Base.prepare(engine, reflect=True)
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
Session = scoped_session(session_factory)
| import os
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.pool import NullPool
AIRFLOW_CONN_MYSQL_TRACKER = os.environ.get('AIRFLOW_CONN_MYSQL_TRACKER')
if not AIRFLOW_CONN_MYSQL_TRACKER:
raise ValueError("AIRFLOW_CONN_MYSQL_TRACKER not present in the environment")
Base = automap_base()
engine = create_engine(DB_URL, poolclass=NullPool)
Base.prepare(engine, reflect=True)
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
Session = scoped_session(session_factory)
| Add Mysql Tracker database to store our data | Add Mysql Tracker database to store our data
| Python | apache-2.0 | LREN-CHUV/data-factory-airflow-dags,LREN-CHUV/airflow-mri-preprocessing-dags,LREN-CHUV/data-factory-airflow-dags,LREN-CHUV/airflow-mri-preprocessing-dags | import os
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.pool import NullPool
- DB_URL = os.environ.get('DB_URL')
+ AIRFLOW_CONN_MYSQL_TRACKER = os.environ.get('AIRFLOW_CONN_MYSQL_TRACKER')
- if not DB_URL:
+ if not AIRFLOW_CONN_MYSQL_TRACKER:
- raise ValueError("DB_URL not present in the environment")
+ raise ValueError("AIRFLOW_CONN_MYSQL_TRACKER not present in the environment")
Base = automap_base()
engine = create_engine(DB_URL, poolclass=NullPool)
Base.prepare(engine, reflect=True)
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
Session = scoped_session(session_factory)
| Add Mysql Tracker database to store our data | ## Code Before:
import os
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.pool import NullPool
DB_URL = os.environ.get('DB_URL')
if not DB_URL:
raise ValueError("DB_URL not present in the environment")
Base = automap_base()
engine = create_engine(DB_URL, poolclass=NullPool)
Base.prepare(engine, reflect=True)
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
Session = scoped_session(session_factory)
## Instruction:
Add Mysql Tracker database to store our data
## Code After:
import os
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm.scoping import scoped_session
from sqlalchemy.pool import NullPool
AIRFLOW_CONN_MYSQL_TRACKER = os.environ.get('AIRFLOW_CONN_MYSQL_TRACKER')
if not AIRFLOW_CONN_MYSQL_TRACKER:
raise ValueError("AIRFLOW_CONN_MYSQL_TRACKER not present in the environment")
Base = automap_base()
engine = create_engine(DB_URL, poolclass=NullPool)
Base.prepare(engine, reflect=True)
session_factory = sessionmaker(bind=engine, expire_on_commit=False)
Session = scoped_session(session_factory)
| # ... existing code ...
AIRFLOW_CONN_MYSQL_TRACKER = os.environ.get('AIRFLOW_CONN_MYSQL_TRACKER')
if not AIRFLOW_CONN_MYSQL_TRACKER:
raise ValueError("AIRFLOW_CONN_MYSQL_TRACKER not present in the environment")
# ... rest of the code ... |
8ea90a83318e4c1cb01b773435ef4861a459ac0f | indra/sources/utils.py | indra/sources/utils.py |
"""Processor for remote INDRA JSON files."""
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------
url :
The URL of the INDRA JSON file to load
"""
#: The URL of the data
url: str
#: A list of statements
statements: List[Statement]
def __init__(self, url: str):
self.url = url
self.statements = []
def extract_statements(self) -> List[Statement]:
"""Extract statements from the remote JSON file."""
res = requests.get(self.url)
res.raise_for_status()
self.statements = stmts_from_json(res.json())
return self.statements
|
"""Processor for remote INDRA JSON files."""
from collections import Counter
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------
url :
The URL of the INDRA JSON file to load
"""
#: The URL of the data
url: str
def __init__(self, url: str):
self.url = url
self._statements = None
@property
def statements(self) -> List[Statement]:
"""The extracted statements."""
if self._statements is None:
self.extract_statements()
return self._statements
def extract_statements(self) -> List[Statement]:
"""Extract statements from the remote JSON file."""
res = requests.get(self.url)
res.raise_for_status()
self._statements = stmts_from_json(res.json())
return self._statements
def print_summary(self) -> None:
"""print a summary of the statements."""
from tabulate import tabulate
print(tabulate(
Counter(
statement.__class__.__name__
for statement in self.statements
).most_common(),
headers=["Statement Type", "Count"],
))
| Implement autoloading and summary function | Implement autoloading and summary function
| Python | bsd-2-clause | sorgerlab/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,bgyori/indra,bgyori/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra,sorgerlab/belpy,johnbachman/indra |
"""Processor for remote INDRA JSON files."""
+
+ from collections import Counter
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------
url :
The URL of the INDRA JSON file to load
"""
#: The URL of the data
url: str
- #: A list of statements
- statements: List[Statement]
-
def __init__(self, url: str):
self.url = url
- self.statements = []
+ self._statements = None
+
+ @property
+ def statements(self) -> List[Statement]:
+ """The extracted statements."""
+ if self._statements is None:
+ self.extract_statements()
+ return self._statements
def extract_statements(self) -> List[Statement]:
"""Extract statements from the remote JSON file."""
res = requests.get(self.url)
res.raise_for_status()
- self.statements = stmts_from_json(res.json())
+ self._statements = stmts_from_json(res.json())
- return self.statements
+ return self._statements
+ def print_summary(self) -> None:
+ """print a summary of the statements."""
+ from tabulate import tabulate
+ print(tabulate(
+ Counter(
+ statement.__class__.__name__
+ for statement in self.statements
+ ).most_common(),
+ headers=["Statement Type", "Count"],
+ ))
+ | Implement autoloading and summary function | ## Code Before:
"""Processor for remote INDRA JSON files."""
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------
url :
The URL of the INDRA JSON file to load
"""
#: The URL of the data
url: str
#: A list of statements
statements: List[Statement]
def __init__(self, url: str):
self.url = url
self.statements = []
def extract_statements(self) -> List[Statement]:
"""Extract statements from the remote JSON file."""
res = requests.get(self.url)
res.raise_for_status()
self.statements = stmts_from_json(res.json())
return self.statements
## Instruction:
Implement autoloading and summary function
## Code After:
"""Processor for remote INDRA JSON files."""
from collections import Counter
import requests
from typing import List
from ..statements import Statement, stmts_from_json
__all__ = [
'RemoteProcessor',
]
class RemoteProcessor:
"""A processor for INDRA JSON file to be retrieved by URL.
Parameters
----------
url :
The URL of the INDRA JSON file to load
"""
#: The URL of the data
url: str
def __init__(self, url: str):
self.url = url
self._statements = None
@property
def statements(self) -> List[Statement]:
"""The extracted statements."""
if self._statements is None:
self.extract_statements()
return self._statements
def extract_statements(self) -> List[Statement]:
"""Extract statements from the remote JSON file."""
res = requests.get(self.url)
res.raise_for_status()
self._statements = stmts_from_json(res.json())
return self._statements
def print_summary(self) -> None:
"""print a summary of the statements."""
from tabulate import tabulate
print(tabulate(
Counter(
statement.__class__.__name__
for statement in self.statements
).most_common(),
headers=["Statement Type", "Count"],
))
| // ... existing code ...
"""Processor for remote INDRA JSON files."""
from collections import Counter
// ... modified code ...
def __init__(self, url: str):
...
self.url = url
self._statements = None
@property
def statements(self) -> List[Statement]:
"""The extracted statements."""
if self._statements is None:
self.extract_statements()
return self._statements
...
res.raise_for_status()
self._statements = stmts_from_json(res.json())
return self._statements
def print_summary(self) -> None:
"""print a summary of the statements."""
from tabulate import tabulate
print(tabulate(
Counter(
statement.__class__.__name__
for statement in self.statements
).most_common(),
headers=["Statement Type", "Count"],
))
// ... rest of the code ... |
da3995150d6eacf7695c4606e83c24c82a17546d | autogenerate_config_docs/hooks.py | autogenerate_config_docs/hooks.py |
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
|
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
| Add a hook for nova.cmd.spicehtml5proxy | Add a hook for nova.cmd.spicehtml5proxy
The cmd/ folders are excluded from the autohelp imports to avoid ending
up with a bunch of CLI options. nova/cmd/spicehtml5proxy.py holds real
configuration options and needs to be imported.
Change-Id: Ic0f8066332a45cae253ad3e03f4717f1887e16ee
Partial-Bug: #1394595
| Python | apache-2.0 | openstack/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,savinash47/openstack-doc-tools,openstack/openstack-doc-tools |
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
+ def nova_spice():
+ import nova.cmd.spicehtml5proxy # noqa
+
+
HOOKS = {'keystone.common.config': keystone_config,
- 'glance.common.config': glance_store_config}
+ 'glance.common.config': glance_store_config,
+ 'nova.spice': nova_spice}
| Add a hook for nova.cmd.spicehtml5proxy | ## Code Before:
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config}
## Instruction:
Add a hook for nova.cmd.spicehtml5proxy
## Code After:
def keystone_config():
from keystone.common import config
config.configure()
def glance_store_config():
try:
import glance_store
from oslo.config import cfg
glance_store.backend.register_opts(cfg.CONF)
except ImportError:
# glance_store is not available before Juno
pass
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
| // ... existing code ...
def nova_spice():
import nova.cmd.spicehtml5proxy # noqa
HOOKS = {'keystone.common.config': keystone_config,
'glance.common.config': glance_store_config,
'nova.spice': nova_spice}
// ... rest of the code ... |
906a5ee2b6e20b09b12d36d61271cd63cac49418 | py2pack/utils.py | py2pack/utils.py |
from typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
|
from typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
| Raise a ValueError from _get_archive_filelist instead of Exception | Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
| Python | apache-2.0 | saschpe/py2pack |
from typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
- raise Exception("Can not get filenames from '%s'. "
+ raise ValueError("Can not get filenames from '{!s}'. "
- "Not a tar or zip file" % filename)
+ "Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
| Raise a ValueError from _get_archive_filelist instead of Exception | ## Code Before:
from typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise Exception("Can not get filenames from '%s'. "
"Not a tar or zip file" % filename)
if "./" in names:
names.remove("./")
return names
## Instruction:
Raise a ValueError from _get_archive_filelist instead of Exception
## Code After:
from typing import List # noqa: F401, pylint: disable=unused-import
import tarfile
import zipfile
def _get_archive_filelist(filename):
# type: (str) -> List[str]
names = [] # type: List[str]
if tarfile.is_tarfile(filename):
with tarfile.open(filename) as tar_file:
names = sorted(tar_file.getnames())
elif zipfile.is_zipfile(filename):
with zipfile.ZipFile(filename) as zip_file:
names = sorted(zip_file.namelist())
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
names.remove("./")
return names
| ...
else:
raise ValueError("Can not get filenames from '{!s}'. "
"Not a tar or zip file".format(filename))
if "./" in names:
... |
f4e5f0587c1214433de46fc5d86e77d849fdddc4 | src/robot/utils/robotio.py | src/robot/utils/robotio.py |
import io
from .platform import PY3
def file_writer(path=None, encoding='UTF-8', newline=None):
if path:
f = io.open(path, 'w', encoding=encoding, newline=newline)
else:
f = io.StringIO(newline=newline)
if PY3:
return f
# TODO: Consider removing this and using u'' or `from __future__ import
# unicode_literals` everywhere.
write = f.write
f.write = lambda text: write(unicode(text))
return f
def binary_file_writer(path=None):
if path:
return io.open(path, 'wb')
f = io.BytesIO()
getvalue = f.getvalue
f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
return f
|
import io
from .platform import PY3
def file_writer(path=None, encoding='UTF-8', newline=None):
if path:
f = io.open(path, 'w', encoding=encoding, newline=newline)
else:
f = io.StringIO(newline=newline)
if PY3:
return f
# These streams require written text to be Unicode. We don't want to add
# `u` prefix to all our strings in Python 2, and cannot really use
# `unicode_literals` either because many other Python 2 APIs accept only
# byte strings.
write = f.write
f.write = lambda text: write(unicode(text))
return f
def binary_file_writer(path=None):
if path:
return io.open(path, 'wb')
f = io.BytesIO()
getvalue = f.getvalue
f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
return f
| Replace TODO with comment explaining why it wasn't possible | Replace TODO with comment explaining why it wasn't possible
| Python | apache-2.0 | alexandrul-ci/robotframework,synsun/robotframework,jaloren/robotframework,snyderr/robotframework,joongh/robotframework,HelioGuilherme66/robotframework,HelioGuilherme66/robotframework,alexandrul-ci/robotframework,synsun/robotframework,synsun/robotframework,snyderr/robotframework,joongh/robotframework,synsun/robotframework,alexandrul-ci/robotframework,snyderr/robotframework,alexandrul-ci/robotframework,jaloren/robotframework,synsun/robotframework,jaloren/robotframework,joongh/robotframework,HelioGuilherme66/robotframework,robotframework/robotframework,snyderr/robotframework,robotframework/robotframework,joongh/robotframework,jaloren/robotframework,joongh/robotframework,snyderr/robotframework,robotframework/robotframework,jaloren/robotframework,alexandrul-ci/robotframework |
import io
from .platform import PY3
def file_writer(path=None, encoding='UTF-8', newline=None):
if path:
f = io.open(path, 'w', encoding=encoding, newline=newline)
else:
f = io.StringIO(newline=newline)
if PY3:
return f
- # TODO: Consider removing this and using u'' or `from __future__ import
- # unicode_literals` everywhere.
+ # These streams require written text to be Unicode. We don't want to add
+ # `u` prefix to all our strings in Python 2, and cannot really use
+ # `unicode_literals` either because many other Python 2 APIs accept only
+ # byte strings.
write = f.write
f.write = lambda text: write(unicode(text))
return f
def binary_file_writer(path=None):
if path:
return io.open(path, 'wb')
f = io.BytesIO()
getvalue = f.getvalue
f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
return f
| Replace TODO with comment explaining why it wasn't possible | ## Code Before:
import io
from .platform import PY3
def file_writer(path=None, encoding='UTF-8', newline=None):
if path:
f = io.open(path, 'w', encoding=encoding, newline=newline)
else:
f = io.StringIO(newline=newline)
if PY3:
return f
# TODO: Consider removing this and using u'' or `from __future__ import
# unicode_literals` everywhere.
write = f.write
f.write = lambda text: write(unicode(text))
return f
def binary_file_writer(path=None):
if path:
return io.open(path, 'wb')
f = io.BytesIO()
getvalue = f.getvalue
f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
return f
## Instruction:
Replace TODO with comment explaining why it wasn't possible
## Code After:
import io
from .platform import PY3
def file_writer(path=None, encoding='UTF-8', newline=None):
if path:
f = io.open(path, 'w', encoding=encoding, newline=newline)
else:
f = io.StringIO(newline=newline)
if PY3:
return f
# These streams require written text to be Unicode. We don't want to add
# `u` prefix to all our strings in Python 2, and cannot really use
# `unicode_literals` either because many other Python 2 APIs accept only
# byte strings.
write = f.write
f.write = lambda text: write(unicode(text))
return f
def binary_file_writer(path=None):
if path:
return io.open(path, 'wb')
f = io.BytesIO()
getvalue = f.getvalue
f.getvalue = lambda encoding='UTF-8': getvalue().decode(encoding)
return f
| // ... existing code ...
return f
# These streams require written text to be Unicode. We don't want to add
# `u` prefix to all our strings in Python 2, and cannot really use
# `unicode_literals` either because many other Python 2 APIs accept only
# byte strings.
write = f.write
// ... rest of the code ... |
c174e7bffbfbbb2fe4a1d13d37d9c056d44d95d2 | project/apps.py | project/apps.py |
__author__ = "Gavin M. Roy"
__email__ = "[email protected]"
__date__ = "2009-11-10"
__version__ = 0.1
import project.data
import project.handler
class Home(project.handler.RequestHandler):
def get(self):
foo
self.render('templates/apps/home.html', title='Hello, World!'); |
__author__ = "Gavin M. Roy"
__email__ = "[email protected]"
__date__ = "2009-11-10"
__version__ = 0.1
import project.data
import project.handler
class Home(project.handler.RequestHandler):
def get(self):
self.render('templates/apps/home.html', title='Hello, World!'); | Remove the errror intentionally left for debugging | Remove the errror intentionally left for debugging
| Python | bsd-3-clause | lucius-feng/tinman,gmr/tinman,lucius-feng/tinman,lucius-feng/tinman,gmr/tinman |
__author__ = "Gavin M. Roy"
__email__ = "[email protected]"
__date__ = "2009-11-10"
__version__ = 0.1
import project.data
import project.handler
class Home(project.handler.RequestHandler):
def get(self):
- foo
self.render('templates/apps/home.html', title='Hello, World!'); | Remove the errror intentionally left for debugging | ## Code Before:
__author__ = "Gavin M. Roy"
__email__ = "[email protected]"
__date__ = "2009-11-10"
__version__ = 0.1
import project.data
import project.handler
class Home(project.handler.RequestHandler):
def get(self):
foo
self.render('templates/apps/home.html', title='Hello, World!');
## Instruction:
Remove the errror intentionally left for debugging
## Code After:
__author__ = "Gavin M. Roy"
__email__ = "[email protected]"
__date__ = "2009-11-10"
__version__ = 0.1
import project.data
import project.handler
class Home(project.handler.RequestHandler):
def get(self):
self.render('templates/apps/home.html', title='Hello, World!'); | # ... existing code ...
def get(self):
self.render('templates/apps/home.html', title='Hello, World!');
# ... rest of the code ... |
5e2943b8e17ee753ddfafd1420c9e8155c496aba | example/tests/test_parsers.py | example/tests/test_parsers.py | import json
from django.test import TestCase
from io import BytesIO
from rest_framework_json_api.parsers import JSONParser
class TestJSONParser(TestCase):
def setUp(self):
class MockRequest(object):
def __init__(self):
self.method = 'GET'
request = MockRequest()
self.parser_context = {'request': request, 'kwargs': {}, 'view': 'BlogViewSet'}
data = {
'data': {
'id': 123,
'type': 'Blog'
},
'meta': {
'random_key': 'random_value'
}
}
self.string = json.dumps(data)
def test_parse_include_metadata(self):
parser = JSONParser()
stream = BytesIO(self.string.encode('utf-8'))
data = parser.parse(stream, None, self.parser_context)
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
| import json
from io import BytesIO
from django.test import TestCase
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
class TestJSONParser(TestCase):
def setUp(self):
class MockRequest(object):
def __init__(self):
self.method = 'GET'
request = MockRequest()
self.parser_context = {'request': request, 'kwargs': {}, 'view': 'BlogViewSet'}
data = {
'data': {
'id': 123,
'type': 'Blog'
},
'meta': {
'random_key': 'random_value'
}
}
self.string = json.dumps(data)
def test_parse_include_metadata(self):
parser = JSONParser()
stream = BytesIO(self.string.encode('utf-8'))
data = parser.parse(stream, None, self.parser_context)
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
def test_parse_include_metadata(self):
parser = JSONParser()
string = json.dumps([])
stream = BytesIO(string.encode('utf-8'))
with self.assertRaises(ParseError):
parser.parse(stream, None, self.parser_context)
| Test case for parsing invalid data. | Test case for parsing invalid data.
| Python | bsd-2-clause | django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api | import json
+ from io import BytesIO
from django.test import TestCase
- from io import BytesIO
+ from rest_framework.exceptions import ParseError
+
from rest_framework_json_api.parsers import JSONParser
class TestJSONParser(TestCase):
def setUp(self):
class MockRequest(object):
def __init__(self):
self.method = 'GET'
request = MockRequest()
self.parser_context = {'request': request, 'kwargs': {}, 'view': 'BlogViewSet'}
data = {
'data': {
'id': 123,
'type': 'Blog'
},
'meta': {
'random_key': 'random_value'
}
}
self.string = json.dumps(data)
def test_parse_include_metadata(self):
parser = JSONParser()
stream = BytesIO(self.string.encode('utf-8'))
data = parser.parse(stream, None, self.parser_context)
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
+
+ def test_parse_include_metadata(self):
+ parser = JSONParser()
+
+ string = json.dumps([])
+ stream = BytesIO(string.encode('utf-8'))
+
+ with self.assertRaises(ParseError):
+ parser.parse(stream, None, self.parser_context)
+ | Test case for parsing invalid data. | ## Code Before:
import json
from django.test import TestCase
from io import BytesIO
from rest_framework_json_api.parsers import JSONParser
class TestJSONParser(TestCase):
def setUp(self):
class MockRequest(object):
def __init__(self):
self.method = 'GET'
request = MockRequest()
self.parser_context = {'request': request, 'kwargs': {}, 'view': 'BlogViewSet'}
data = {
'data': {
'id': 123,
'type': 'Blog'
},
'meta': {
'random_key': 'random_value'
}
}
self.string = json.dumps(data)
def test_parse_include_metadata(self):
parser = JSONParser()
stream = BytesIO(self.string.encode('utf-8'))
data = parser.parse(stream, None, self.parser_context)
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
## Instruction:
Test case for parsing invalid data.
## Code After:
import json
from io import BytesIO
from django.test import TestCase
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
class TestJSONParser(TestCase):
def setUp(self):
class MockRequest(object):
def __init__(self):
self.method = 'GET'
request = MockRequest()
self.parser_context = {'request': request, 'kwargs': {}, 'view': 'BlogViewSet'}
data = {
'data': {
'id': 123,
'type': 'Blog'
},
'meta': {
'random_key': 'random_value'
}
}
self.string = json.dumps(data)
def test_parse_include_metadata(self):
parser = JSONParser()
stream = BytesIO(self.string.encode('utf-8'))
data = parser.parse(stream, None, self.parser_context)
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
def test_parse_include_metadata(self):
parser = JSONParser()
string = json.dumps([])
stream = BytesIO(string.encode('utf-8'))
with self.assertRaises(ParseError):
parser.parse(stream, None, self.parser_context)
| // ... existing code ...
import json
from io import BytesIO
// ... modified code ...
from django.test import TestCase
from rest_framework.exceptions import ParseError
from rest_framework_json_api.parsers import JSONParser
...
self.assertEqual(data['_meta'], {'random_key': 'random_value'})
def test_parse_include_metadata(self):
parser = JSONParser()
string = json.dumps([])
stream = BytesIO(string.encode('utf-8'))
with self.assertRaises(ParseError):
parser.parse(stream, None, self.parser_context)
// ... rest of the code ... |
0ca07405b864f761ae1d7ed659cac67c799bf39a | src/core/queue.py | src/core/queue.py |
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
|
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| Move those methods to own class | Move those methods to own class [ci skip]
| Python | mit | le717/ICU |
class ActionsQueue:
def __init__(self):
self.queue = []
+
+
+ class Responses:
+
+ def __init__(self):
+ pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| Move those methods to own class | ## Code Before:
class ActionsQueue:
def __init__(self):
self.queue = []
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
## Instruction:
Move those methods to own class
## Code After:
class ActionsQueue:
def __init__(self):
self.queue = []
class Responses:
def __init__(self):
pass
# Normal buttons
def btnBrowse(self, val):
print(val)
def actionReset(self, val):
print(val)
def btnRedirect(self, val):
print(val)
# Radio buttons
def radioColor256(self, val):
print(val)
def radioColor16b(self, val):
print(val)
def radioModelLow(self, val):
print(val)
def radioModelFast(self, val):
print(val)
def radioModelHigh(self, val):
print(val)
def radioTexFast(self, val):
print(val)
def radioTexHigh(self, val):
print(val)
# Check boxes
def chkCursor(self, val):
print(val)
def chkDraw3D(self, val):
print(val)
def chkFlipVideo(self, val):
print(val)
def chkFullscreen(self, val):
print(val)
def chkJoystick(self, val):
print(val)
def chkMusic(self, val):
print(val)
def chkSound(self, val):
print(val)
# Direct3D dropdown selection
def comboD3D(self, val):
print(val)
| // ... existing code ...
self.queue = []
class Responses:
def __init__(self):
pass
// ... rest of the code ... |
7461666cde3c0206058d10f2341e0a57bf33e504 | src/renderers/status.py | src/renderers/status.py | from flask import Blueprint
from models import db, Status
import json
status_renderer = Blueprint('status', __name__)
@status_renderer.route('/status/<int:user_id>')
def get_tweet(user_id):
status = db.session.query(Status).order_by(Status.id.desc()).one()
return json.dumps({'type' : 'text',
'status_text' : status.status_text,
'posted_by' : status.posted_by,
'image_url' : status.pic_url,
'profile_pic': status.profile_pic
})
| from flask import Blueprint
from models import db, Status
import json
status_renderer = Blueprint('status', __name__)
@status_renderer.route('/status')
def get_status():
status = db.session.query(Status).order_by(Status.id.desc()).one()
return json.dumps({'type' : 'text',
'status_text' : status.status_text,
'posted_by' : status.posted_by,
'image_url' : status.pic_url,
'profile_pic': status.profile_pic
})
| Remove user_id requirement for FB endpoint | Remove user_id requirement for FB endpoint
| Python | mit | ndm25/notifyable | from flask import Blueprint
from models import db, Status
import json
status_renderer = Blueprint('status', __name__)
- @status_renderer.route('/status/<int:user_id>')
+ @status_renderer.route('/status')
- def get_tweet(user_id):
+ def get_status():
status = db.session.query(Status).order_by(Status.id.desc()).one()
return json.dumps({'type' : 'text',
'status_text' : status.status_text,
'posted_by' : status.posted_by,
'image_url' : status.pic_url,
'profile_pic': status.profile_pic
})
| Remove user_id requirement for FB endpoint | ## Code Before:
from flask import Blueprint
from models import db, Status
import json
status_renderer = Blueprint('status', __name__)
@status_renderer.route('/status/<int:user_id>')
def get_tweet(user_id):
status = db.session.query(Status).order_by(Status.id.desc()).one()
return json.dumps({'type' : 'text',
'status_text' : status.status_text,
'posted_by' : status.posted_by,
'image_url' : status.pic_url,
'profile_pic': status.profile_pic
})
## Instruction:
Remove user_id requirement for FB endpoint
## Code After:
from flask import Blueprint
from models import db, Status
import json
status_renderer = Blueprint('status', __name__)
@status_renderer.route('/status')
def get_status():
status = db.session.query(Status).order_by(Status.id.desc()).one()
return json.dumps({'type' : 'text',
'status_text' : status.status_text,
'posted_by' : status.posted_by,
'image_url' : status.pic_url,
'profile_pic': status.profile_pic
})
| # ... existing code ...
@status_renderer.route('/status')
def get_status():
status = db.session.query(Status).order_by(Status.id.desc()).one()
# ... rest of the code ... |
6727bb98c91f1185042d08f3ff2a4c5ef625cae4 | mjstat/languages/__init__.py | mjstat/languages/__init__.py |
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a poor copy of the language framework of Docutils.
"""
if lang_code in module_cache:
return module_cache[lang_code]
for i in (1, 0):
try:
module = __import__(lang_code, globals(), locals(), level=i)
break
except ImportError:
continue
else:
module = __import__('en', globals(), locals(), level=1)
module_cache[lang_code] = module
return module
|
from importlib import import_module
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a revamped version of function docutils.languages.get_language.
"""
if lang_code in module_cache:
return module_cache[lang_code]
try:
module = import_module('.' + lang_code, __name__)
except ImportError:
from . import en
module = en
module_cache[lang_code] = module
return module
| Use importlib.import_module instead of built-in __import__. | Use importlib.import_module instead of built-in __import__.
| Python | mit | showa-yojyo/bin,showa-yojyo/bin | +
+ from importlib import import_module
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
- This is a poor copy of the language framework of Docutils.
+ This is a revamped version of function docutils.languages.get_language.
"""
if lang_code in module_cache:
return module_cache[lang_code]
- for i in (1, 0):
- try:
+ try:
+ module = import_module('.' + lang_code, __name__)
- module = __import__(lang_code, globals(), locals(), level=i)
- break
- except ImportError:
+ except ImportError:
+ from . import en
+ module = en
- continue
- else:
- module = __import__('en', globals(), locals(), level=1)
module_cache[lang_code] = module
return module
| Use importlib.import_module instead of built-in __import__. | ## Code Before:
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a poor copy of the language framework of Docutils.
"""
if lang_code in module_cache:
return module_cache[lang_code]
for i in (1, 0):
try:
module = __import__(lang_code, globals(), locals(), level=i)
break
except ImportError:
continue
else:
module = __import__('en', globals(), locals(), level=1)
module_cache[lang_code] = module
return module
## Instruction:
Use importlib.import_module instead of built-in __import__.
## Code After:
from importlib import import_module
module_cache = {}
def get_language(lang_code):
"""Return module with language localizations.
This is a revamped version of function docutils.languages.get_language.
"""
if lang_code in module_cache:
return module_cache[lang_code]
try:
module = import_module('.' + lang_code, __name__)
except ImportError:
from . import en
module = en
module_cache[lang_code] = module
return module
| # ... existing code ...
from importlib import import_module
# ... modified code ...
This is a revamped version of function docutils.languages.get_language.
"""
...
try:
module = import_module('.' + lang_code, __name__)
except ImportError:
from . import en
module = en
# ... rest of the code ... |
3a2d2934f61c496654281da7144f74713a9dea6f | devicehive/api.py | devicehive/api.py | from devicehive.transport import Request
from devicehive.transport import Response
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
return self._transport.name == 'websocket'
def _request(self, url, action, request, **params):
req = Request(url, action, request, **params)
response = self._transport.request(req.action, req.request,
**req.params)
return Response(response)
def refresh_token(self, refresh_token):
url = 'token/refresh'
action = url
request = {'refreshToken': refresh_token}
params = {'method': 'POST',
'merge_data': True}
return self._request(url, action, request, **params)
| class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
class ApiObject(object):
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
return self._transport.name == 'websocket'
def _request(self, url, action, request, **params):
req = Request(url, action, request, **params)
resp = self._transport.request(req.action, req.request, **req.params)
return Response(resp)
class Token(ApiObject):
def __init__(self, transport, refresh_toke, access_token=None):
ApiObject.__init__(self, transport)
self._refresh_token = refresh_toke
self._access_token = access_token
def refresh(self):
url = 'token/refresh'
action = url
request = {'refreshToken': self._refresh_token}
params = {'method': 'POST',
'merge_data': True}
response = self._request(url, action, request, **params)
self._access_token = response.data['accessToken']
def access_token(self):
return self._access_token
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def token(self, refresh_token, access_token):
return Token(self._transport, refresh_token, access_token)
| Add Request, Response and ApiObject and Token classes | Add Request, Response and ApiObject and Token classes
| Python | apache-2.0 | devicehive/devicehive-python | - from devicehive.transport import Request
- from devicehive.transport import Response
+ class Request(object):
+ """Request class."""
+
+ def __init__(self, url, action, request, **params):
+ self.action = action
+ self.request = request
+ self.params = params
+ self.params['url'] = url
+ class Response(object):
+ """Response class."""
+
+ def __init__(self, response):
+ self.action = response.pop('action')
+ self.is_success = response.pop('status') == 'success'
+ self.code = response.pop('code', None)
+ self.error = response.pop('error', None)
+ self.data = response
+
+
- class Api(object):
+ class ApiObject(object):
- """Api class."""
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
return self._transport.name == 'websocket'
def _request(self, url, action, request, **params):
req = Request(url, action, request, **params)
- response = self._transport.request(req.action, req.request,
+ resp = self._transport.request(req.action, req.request, **req.params)
- **req.params)
- return Response(response)
+ return Response(resp)
+
+ class Token(ApiObject):
+
+ def __init__(self, transport, refresh_toke, access_token=None):
+ ApiObject.__init__(self, transport)
- def refresh_token(self, refresh_token):
+ self._refresh_token = refresh_toke
+ self._access_token = access_token
+
+ def refresh(self):
url = 'token/refresh'
action = url
- request = {'refreshToken': refresh_token}
+ request = {'refreshToken': self._refresh_token}
params = {'method': 'POST',
'merge_data': True}
- return self._request(url, action, request, **params)
+ response = self._request(url, action, request, **params)
+ self._access_token = response.data['accessToken']
+ def access_token(self):
+ return self._access_token
+
+
+ class Api(object):
+ """Api class."""
+
+ def __init__(self, transport):
+ self._transport = transport
+
+ def token(self, refresh_token, access_token):
+ return Token(self._transport, refresh_token, access_token)
+ | Add Request, Response and ApiObject and Token classes | ## Code Before:
from devicehive.transport import Request
from devicehive.transport import Response
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
return self._transport.name == 'websocket'
def _request(self, url, action, request, **params):
req = Request(url, action, request, **params)
response = self._transport.request(req.action, req.request,
**req.params)
return Response(response)
def refresh_token(self, refresh_token):
url = 'token/refresh'
action = url
request = {'refreshToken': refresh_token}
params = {'method': 'POST',
'merge_data': True}
return self._request(url, action, request, **params)
## Instruction:
Add Request, Response and ApiObject and Token classes
## Code After:
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
class Response(object):
"""Response class."""
def __init__(self, response):
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
class ApiObject(object):
def __init__(self, transport):
self._transport = transport
def is_http_transport(self):
return self._transport.name == 'http'
def is_websocket_transport(self):
return self._transport.name == 'websocket'
def _request(self, url, action, request, **params):
req = Request(url, action, request, **params)
resp = self._transport.request(req.action, req.request, **req.params)
return Response(resp)
class Token(ApiObject):
def __init__(self, transport, refresh_toke, access_token=None):
ApiObject.__init__(self, transport)
self._refresh_token = refresh_toke
self._access_token = access_token
def refresh(self):
url = 'token/refresh'
action = url
request = {'refreshToken': self._refresh_token}
params = {'method': 'POST',
'merge_data': True}
response = self._request(url, action, request, **params)
self._access_token = response.data['accessToken']
def access_token(self):
return self._access_token
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def token(self, refresh_token, access_token):
return Token(self._transport, refresh_token, access_token)
| ...
class Request(object):
"""Request class."""
def __init__(self, url, action, request, **params):
self.action = action
self.request = request
self.params = params
self.params['url'] = url
...
class Response(object):
"""Response class."""
def __init__(self, response):
self.action = response.pop('action')
self.is_success = response.pop('status') == 'success'
self.code = response.pop('code', None)
self.error = response.pop('error', None)
self.data = response
class ApiObject(object):
...
req = Request(url, action, request, **params)
resp = self._transport.request(req.action, req.request, **req.params)
return Response(resp)
class Token(ApiObject):
def __init__(self, transport, refresh_toke, access_token=None):
ApiObject.__init__(self, transport)
self._refresh_token = refresh_toke
self._access_token = access_token
def refresh(self):
url = 'token/refresh'
...
action = url
request = {'refreshToken': self._refresh_token}
params = {'method': 'POST',
...
'merge_data': True}
response = self._request(url, action, request, **params)
self._access_token = response.data['accessToken']
def access_token(self):
return self._access_token
class Api(object):
"""Api class."""
def __init__(self, transport):
self._transport = transport
def token(self, refresh_token, access_token):
return Token(self._transport, refresh_token, access_token)
... |
b6e532f01d852738f40eb8bedc89f5c056b2f62c | netbox/generate_secret_key.py | netbox/generate_secret_key.py | import random
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
secure_random = random.SystemRandom()
print(''.join(secure_random.sample(charset, 50)))
| import secrets
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
print(''.join(secrets.choice(charset) for _ in range(50)))
| Fix how SECRET_KEY is generated | Fix how SECRET_KEY is generated
Use secrets.choice instead of random.sample to generate the secret key. | Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox | - import random
+ import secrets
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
+ print(''.join(secrets.choice(charset) for _ in range(50)))
- secure_random = random.SystemRandom()
- print(''.join(secure_random.sample(charset, 50)))
| Fix how SECRET_KEY is generated | ## Code Before:
import random
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
secure_random = random.SystemRandom()
print(''.join(secure_random.sample(charset, 50)))
## Instruction:
Fix how SECRET_KEY is generated
## Code After:
import secrets
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
print(''.join(secrets.choice(charset) for _ in range(50)))
| ...
import secrets
...
charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)'
print(''.join(secrets.choice(charset) for _ in range(50)))
... |
5a45a312eebe9e432b066b99d914b49a2adb920c | openfaas/yaml2json/function/handler.py | openfaas/yaml2json/function/handler.py |
import os
import sys
import json
import yaml
def handle(data, **parms):
def yaml2json(ydata):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(ydata, Loader=yaml.BaseLoader)
except Exception as e:
d = {'error': '{}'.format(e)}
return json.dumps(d)
def json2yaml(jdata):
"""
Convert JSON to YAML (output: YAML)
"""
try:
d = json.loads(jdata)
except Exception as e:
d = {'error': '{}'.format(e)}
return yaml.dump(d, default_flow_style=False)
if parms.get('reverse') == 'true':
print(json2yaml(data))
else:
print(yaml2json(data))
|
import os
import sys
import json
import yaml
def yaml2json(data):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(data, Loader=yaml.BaseLoader)
except Exception as e:
d = {'error': '{}'.format(e)}
return json.dumps(d)
def json2yaml(data):
"""
Convert JSON to YAML (output: YAML)
"""
try:
d = json.loads(data)
except Exception as e:
d = {'error': '{}'.format(e)}
return yaml.dump(d, default_flow_style=False)
def handle(data, **parms):
if parms.get('reverse') == 'true':
print(json2yaml(data))
else:
print(yaml2json(data))
| Make handle function to behave similar as main function | Make handle function to behave similar as main function
| Python | mit | psyhomb/serverless |
import os
import sys
import json
import yaml
- def handle(data, **parms):
- def yaml2json(ydata):
+ def yaml2json(data):
- """
+ """
- Convert YAML to JSON (output: JSON)
+ Convert YAML to JSON (output: JSON)
- """
+ """
- try:
+ try:
- d = yaml.load(ydata, Loader=yaml.BaseLoader)
+ d = yaml.load(data, Loader=yaml.BaseLoader)
- except Exception as e:
+ except Exception as e:
- d = {'error': '{}'.format(e)}
+ d = {'error': '{}'.format(e)}
- return json.dumps(d)
+ return json.dumps(d)
- def json2yaml(jdata):
+ def json2yaml(data):
- """
+ """
- Convert JSON to YAML (output: YAML)
+ Convert JSON to YAML (output: YAML)
- """
+ """
- try:
+ try:
- d = json.loads(jdata)
+ d = json.loads(data)
- except Exception as e:
+ except Exception as e:
- d = {'error': '{}'.format(e)}
+ d = {'error': '{}'.format(e)}
- return yaml.dump(d, default_flow_style=False)
+ return yaml.dump(d, default_flow_style=False)
+ def handle(data, **parms):
if parms.get('reverse') == 'true':
print(json2yaml(data))
else:
print(yaml2json(data))
| Make handle function to behave similar as main function | ## Code Before:
import os
import sys
import json
import yaml
def handle(data, **parms):
def yaml2json(ydata):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(ydata, Loader=yaml.BaseLoader)
except Exception as e:
d = {'error': '{}'.format(e)}
return json.dumps(d)
def json2yaml(jdata):
"""
Convert JSON to YAML (output: YAML)
"""
try:
d = json.loads(jdata)
except Exception as e:
d = {'error': '{}'.format(e)}
return yaml.dump(d, default_flow_style=False)
if parms.get('reverse') == 'true':
print(json2yaml(data))
else:
print(yaml2json(data))
## Instruction:
Make handle function to behave similar as main function
## Code After:
import os
import sys
import json
import yaml
def yaml2json(data):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(data, Loader=yaml.BaseLoader)
except Exception as e:
d = {'error': '{}'.format(e)}
return json.dumps(d)
def json2yaml(data):
"""
Convert JSON to YAML (output: YAML)
"""
try:
d = json.loads(data)
except Exception as e:
d = {'error': '{}'.format(e)}
return yaml.dump(d, default_flow_style=False)
def handle(data, **parms):
if parms.get('reverse') == 'true':
print(json2yaml(data))
else:
print(yaml2json(data))
| // ... existing code ...
def yaml2json(data):
"""
Convert YAML to JSON (output: JSON)
"""
try:
d = yaml.load(data, Loader=yaml.BaseLoader)
except Exception as e:
d = {'error': '{}'.format(e)}
return json.dumps(d)
// ... modified code ...
def json2yaml(data):
"""
Convert JSON to YAML (output: YAML)
"""
try:
d = json.loads(data)
except Exception as e:
d = {'error': '{}'.format(e)}
return yaml.dump(d, default_flow_style=False)
...
def handle(data, **parms):
if parms.get('reverse') == 'true':
// ... rest of the code ... |
b9701cfb65c4c641231bef385dde74b8d940f901 | gimlet/backends/sql.py | gimlet/backends/sql.py | from sqlalchemy import MetaData, Table, Column, types, create_engine, select
from .base import BaseBackend
class SQLBackend(BaseBackend):
def __init__(self, url, table_name='gimlet_channels', **engine_kwargs):
meta = MetaData(bind=create_engine(url, **engine_kwargs))
self.table = Table(table_name, meta,
Column('id', types.Integer, primary_key=True),
Column('key', types.CHAR(32), nullable=False,
unique=True),
Column('data', types.LargeBinary, nullable=False))
self.table.create(checkfirst=True)
def __setitem__(self, key, value):
raw = self.serialize(value)
# Check if this key exists with a SELECT FOR UPDATE, to protect
# against a race with other concurrent writers of this key.
r = self.table.select('1', for_update=True).\
where(self.table.c.key == key).execute().fetchone()
if r:
# If it exists, use an UPDATE.
self.table.update().values(data=raw).\
where(self.table.c.key == key).execute()
else:
# Otherwise INSERT.
self.table.insert().values(key=key, data=raw).execute()
def __getitem__(self, key):
r = select([self.table.c.data], self.table.c.key == key).\
execute().fetchone()
if r:
raw = r[0]
return self.deserialize(raw)
else:
raise KeyError('key %r not found' % key)
| from sqlalchemy import MetaData, Table, Column, types, create_engine, select
from .base import BaseBackend
class SQLBackend(BaseBackend):
def __init__(self, url, table_name='gimlet_channels', **engine_kwargs):
meta = MetaData(bind=create_engine(url, **engine_kwargs))
self.table = Table(table_name, meta,
Column('id', types.Integer, primary_key=True),
Column('key', types.CHAR(32), nullable=False,
unique=True),
Column('data', types.LargeBinary, nullable=False))
self.table.create(checkfirst=True)
def __setitem__(self, key, value):
table = self.table
key_col = table.c.key
raw = self.serialize(value)
# Check if this key exists with a SELECT FOR UPDATE, to protect
# against a race with other concurrent writers of this key.
r = table.count(key_col == key, for_update=True).scalar()
if r:
# If it exists, use an UPDATE.
table.update().values(data=raw).where(key_col == key).execute()
else:
# Otherwise INSERT.
table.insert().values(key=key, data=raw).execute()
def __getitem__(self, key):
r = select([self.table.c.data], self.table.c.key == key).\
execute().fetchone()
if r:
raw = r[0]
return self.deserialize(raw)
else:
raise KeyError('key %r not found' % key)
| Use count/scalar to test if key is present in SQL back end | Use count/scalar to test if key is present in SQL back end
This is simpler than using select/execute/fetchone. Also, scalar automatically
closes the result set whereas fetchone does not. This may fix some performance
issues.
| Python | mit | storborg/gimlet | from sqlalchemy import MetaData, Table, Column, types, create_engine, select
from .base import BaseBackend
class SQLBackend(BaseBackend):
def __init__(self, url, table_name='gimlet_channels', **engine_kwargs):
meta = MetaData(bind=create_engine(url, **engine_kwargs))
self.table = Table(table_name, meta,
Column('id', types.Integer, primary_key=True),
Column('key', types.CHAR(32), nullable=False,
unique=True),
Column('data', types.LargeBinary, nullable=False))
self.table.create(checkfirst=True)
def __setitem__(self, key, value):
+ table = self.table
+ key_col = table.c.key
raw = self.serialize(value)
-
# Check if this key exists with a SELECT FOR UPDATE, to protect
# against a race with other concurrent writers of this key.
+ r = table.count(key_col == key, for_update=True).scalar()
- r = self.table.select('1', for_update=True).\
- where(self.table.c.key == key).execute().fetchone()
-
if r:
# If it exists, use an UPDATE.
+ table.update().values(data=raw).where(key_col == key).execute()
- self.table.update().values(data=raw).\
- where(self.table.c.key == key).execute()
else:
# Otherwise INSERT.
- self.table.insert().values(key=key, data=raw).execute()
+ table.insert().values(key=key, data=raw).execute()
def __getitem__(self, key):
r = select([self.table.c.data], self.table.c.key == key).\
execute().fetchone()
if r:
raw = r[0]
return self.deserialize(raw)
else:
raise KeyError('key %r not found' % key)
| Use count/scalar to test if key is present in SQL back end | ## Code Before:
from sqlalchemy import MetaData, Table, Column, types, create_engine, select
from .base import BaseBackend
class SQLBackend(BaseBackend):
def __init__(self, url, table_name='gimlet_channels', **engine_kwargs):
meta = MetaData(bind=create_engine(url, **engine_kwargs))
self.table = Table(table_name, meta,
Column('id', types.Integer, primary_key=True),
Column('key', types.CHAR(32), nullable=False,
unique=True),
Column('data', types.LargeBinary, nullable=False))
self.table.create(checkfirst=True)
def __setitem__(self, key, value):
raw = self.serialize(value)
# Check if this key exists with a SELECT FOR UPDATE, to protect
# against a race with other concurrent writers of this key.
r = self.table.select('1', for_update=True).\
where(self.table.c.key == key).execute().fetchone()
if r:
# If it exists, use an UPDATE.
self.table.update().values(data=raw).\
where(self.table.c.key == key).execute()
else:
# Otherwise INSERT.
self.table.insert().values(key=key, data=raw).execute()
def __getitem__(self, key):
r = select([self.table.c.data], self.table.c.key == key).\
execute().fetchone()
if r:
raw = r[0]
return self.deserialize(raw)
else:
raise KeyError('key %r not found' % key)
## Instruction:
Use count/scalar to test if key is present in SQL back end
## Code After:
from sqlalchemy import MetaData, Table, Column, types, create_engine, select
from .base import BaseBackend
class SQLBackend(BaseBackend):
def __init__(self, url, table_name='gimlet_channels', **engine_kwargs):
meta = MetaData(bind=create_engine(url, **engine_kwargs))
self.table = Table(table_name, meta,
Column('id', types.Integer, primary_key=True),
Column('key', types.CHAR(32), nullable=False,
unique=True),
Column('data', types.LargeBinary, nullable=False))
self.table.create(checkfirst=True)
def __setitem__(self, key, value):
table = self.table
key_col = table.c.key
raw = self.serialize(value)
# Check if this key exists with a SELECT FOR UPDATE, to protect
# against a race with other concurrent writers of this key.
r = table.count(key_col == key, for_update=True).scalar()
if r:
# If it exists, use an UPDATE.
table.update().values(data=raw).where(key_col == key).execute()
else:
# Otherwise INSERT.
table.insert().values(key=key, data=raw).execute()
def __getitem__(self, key):
r = select([self.table.c.data], self.table.c.key == key).\
execute().fetchone()
if r:
raw = r[0]
return self.deserialize(raw)
else:
raise KeyError('key %r not found' % key)
| ...
def __setitem__(self, key, value):
table = self.table
key_col = table.c.key
raw = self.serialize(value)
# Check if this key exists with a SELECT FOR UPDATE, to protect
...
# against a race with other concurrent writers of this key.
r = table.count(key_col == key, for_update=True).scalar()
if r:
...
# If it exists, use an UPDATE.
table.update().values(data=raw).where(key_col == key).execute()
else:
...
# Otherwise INSERT.
table.insert().values(key=key, data=raw).execute()
... |
637953efa1f71b123bb28c8404b79219a6bd6b3e | fablab-businessplan.py | fablab-businessplan.py |
import xlsxwriter
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet('Activities')
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Total')
# Add content to the Expenses worksheet
expenses.write('A1', 'Hello world')
# Save and close the file
workbook.close() |
import xlsxwriter
# Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet('Activities')
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Total')
# Create styles -------------------------------------------------------------
# Add a bold style to highlight heading cells
bold_style = workbook.add_format()
bold_style.set_font_color('white')
bold_style.set_bg_color('F56A2F')
bold_style.set_bold()
# Add a total style to highlight total cells
total_style = workbook.add_format()
total_style.set_font_color('red')
total_style.set_bg_color('FAECC5')
total_style.set_bold()
# Add a style for money
money_style = workbook.add_format({'num_format': u'€#,##0'})
# Add green/red color for positive/negative numbers
#money_style.set_num_format('[Green]General;[Red]-General;General')
# Add a number format for cells with money
#money_style.set_num_format('0 "dollar and" .00 "cents"')
# Add content -------------------------------------------------------------
# Add content to the Expenses worksheet
expenses.write('A1', 'Hello world', bold_style)
expenses.write('A2', '12.33', money_style)
expenses.write('A3', 'Total', total_style)
# Save document -------------------------------------------------------------
# Save and close the file
workbook.close() | Add structure and first styles | Add structure and first styles
| Python | mit | openp2pdesign/FabLab-BusinessPlan |
import xlsxwriter
+
+ # Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet('Activities')
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Total')
+
+ # Create styles -------------------------------------------------------------
+
+ # Add a bold style to highlight heading cells
+ bold_style = workbook.add_format()
+ bold_style.set_font_color('white')
+ bold_style.set_bg_color('F56A2F')
+ bold_style.set_bold()
+
+ # Add a total style to highlight total cells
+ total_style = workbook.add_format()
+ total_style.set_font_color('red')
+ total_style.set_bg_color('FAECC5')
+ total_style.set_bold()
+
+ # Add a style for money
+ money_style = workbook.add_format({'num_format': u'€#,##0'})
+ # Add green/red color for positive/negative numbers
+ #money_style.set_num_format('[Green]General;[Red]-General;General')
+ # Add a number format for cells with money
+ #money_style.set_num_format('0 "dollar and" .00 "cents"')
+
+
+ # Add content -------------------------------------------------------------
+
# Add content to the Expenses worksheet
- expenses.write('A1', 'Hello world')
+ expenses.write('A1', 'Hello world', bold_style)
+ expenses.write('A2', '12.33', money_style)
+ expenses.write('A3', 'Total', total_style)
+
+
+ # Save document -------------------------------------------------------------
# Save and close the file
workbook.close() | Add structure and first styles | ## Code Before:
import xlsxwriter
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet('Activities')
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Total')
# Add content to the Expenses worksheet
expenses.write('A1', 'Hello world')
# Save and close the file
workbook.close()
## Instruction:
Add structure and first styles
## Code After:
import xlsxwriter
# Create document -------------------------------------------------------------
# Create the file
workbook = xlsxwriter.Workbook('FabLab-BusinessPlan.xlsx')
# Create the worksheets
expenses = workbook.add_worksheet('Expenses')
activities = workbook.add_worksheet('Activities')
membership = workbook.add_worksheet('Membership')
total = workbook.add_worksheet('Total')
# Create styles -------------------------------------------------------------
# Add a bold style to highlight heading cells
bold_style = workbook.add_format()
bold_style.set_font_color('white')
bold_style.set_bg_color('F56A2F')
bold_style.set_bold()
# Add a total style to highlight total cells
total_style = workbook.add_format()
total_style.set_font_color('red')
total_style.set_bg_color('FAECC5')
total_style.set_bold()
# Add a style for money
money_style = workbook.add_format({'num_format': u'€#,##0'})
# Add green/red color for positive/negative numbers
#money_style.set_num_format('[Green]General;[Red]-General;General')
# Add a number format for cells with money
#money_style.set_num_format('0 "dollar and" .00 "cents"')
# Add content -------------------------------------------------------------
# Add content to the Expenses worksheet
expenses.write('A1', 'Hello world', bold_style)
expenses.write('A2', '12.33', money_style)
expenses.write('A3', 'Total', total_style)
# Save document -------------------------------------------------------------
# Save and close the file
workbook.close() | ...
import xlsxwriter
# Create document -------------------------------------------------------------
...
# Create styles -------------------------------------------------------------
# Add a bold style to highlight heading cells
bold_style = workbook.add_format()
bold_style.set_font_color('white')
bold_style.set_bg_color('F56A2F')
bold_style.set_bold()
# Add a total style to highlight total cells
total_style = workbook.add_format()
total_style.set_font_color('red')
total_style.set_bg_color('FAECC5')
total_style.set_bold()
# Add a style for money
money_style = workbook.add_format({'num_format': u'€#,##0'})
# Add green/red color for positive/negative numbers
#money_style.set_num_format('[Green]General;[Red]-General;General')
# Add a number format for cells with money
#money_style.set_num_format('0 "dollar and" .00 "cents"')
# Add content -------------------------------------------------------------
# Add content to the Expenses worksheet
expenses.write('A1', 'Hello world', bold_style)
expenses.write('A2', '12.33', money_style)
expenses.write('A3', 'Total', total_style)
# Save document -------------------------------------------------------------
... |
598e21a7c397c0c429a78f008a36e5800c1b23e3 | conftest.py | conftest.py | import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
default=os.environ.get("PYTEST_DB_URL"), conn_max_age=600
),
}
| import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
env="PYTEST_DB_URL", conn_max_age=600
),
}
| Fix picking invalid env variable for tests | Fix picking invalid env variable for tests
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor | import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
- default=os.environ.get("PYTEST_DB_URL"), conn_max_age=600
+ env="PYTEST_DB_URL", conn_max_age=600
),
}
| Fix picking invalid env variable for tests | ## Code Before:
import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
default=os.environ.get("PYTEST_DB_URL"), conn_max_age=600
),
}
## Instruction:
Fix picking invalid env variable for tests
## Code After:
import os
import dj_database_url
import pytest
from django.conf import settings
pytest_plugins = [
"saleor.tests.fixtures",
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
"saleor.graphql.webhook.tests.benchmark.fixtures",
"saleor.plugins.webhook.tests.subscription_webhooks.fixtures",
]
if os.environ.get("PYTEST_DB_URL"):
@pytest.fixture(scope="session")
def django_db_setup():
settings.DATABASES = {
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
env="PYTEST_DB_URL", conn_max_age=600
),
}
| ...
settings.DATABASE_CONNECTION_DEFAULT_NAME: dj_database_url.config(
env="PYTEST_DB_URL", conn_max_age=600
),
... |
95421d1b71d2f5847bcea439cde79af2a984eda6 | src/sentry/api/endpoints/project_releases.py | src/sentry/api/endpoints/project_releases.py | from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import Release
class ProjectReleasesEndpoint(ProjectEndpoint):
doc_section = DocSection.RELEASES
def get(self, request, project):
"""
List a project's releases
Retrieve a list of releases for a given project.
{method} {path}
"""
queryset = Release.objects.filter(
project=project,
).order_by('-date_added')
return self.paginate(
request=request,
queryset=queryset,
# TODO(dcramer): we want to sort by date_added
order_by='-id',
on_results=lambda x: serialize(x, request.user),
)
| from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import Release
class ProjectReleasesEndpoint(ProjectEndpoint):
doc_section = DocSection.RELEASES
def get(self, request, project):
"""
List a project's releases
Retrieve a list of releases for a given project.
{method} {path}
"""
queryset = Release.objects.filter(
project=project,
)
return self.paginate(
request=request,
queryset=queryset,
order_by='-id',
on_results=lambda x: serialize(x, request.user),
)
| Maintain project release sort order | Maintain project release sort order
| Python | bsd-3-clause | zenefits/sentry,ewdurbin/sentry,fotinakis/sentry,wong2/sentry,alexm92/sentry,gencer/sentry,Natim/sentry,1tush/sentry,hongliang5623/sentry,daevaorn/sentry,BuildingLink/sentry,daevaorn/sentry,ngonzalvez/sentry,zenefits/sentry,JamesMura/sentry,ngonzalvez/sentry,pauloschilling/sentry,argonemyth/sentry,wong2/sentry,JamesMura/sentry,jokey2k/sentry,Kryz/sentry,gg7/sentry,kevinlondon/sentry,mvaled/sentry,TedaLIEz/sentry,daevaorn/sentry,Kryz/sentry,gencer/sentry,korealerts1/sentry,korealerts1/sentry,hongliang5623/sentry,jokey2k/sentry,gencer/sentry,wujuguang/sentry,imankulov/sentry,pauloschilling/sentry,drcapulet/sentry,JackDanger/sentry,kevinastone/sentry,JamesMura/sentry,nicholasserra/sentry,jean/sentry,jokey2k/sentry,alexm92/sentry,beeftornado/sentry,looker/sentry,BayanGroup/sentry,fuziontech/sentry,imankulov/sentry,gg7/sentry,drcapulet/sentry,BuildingLink/sentry,felixbuenemann/sentry,JTCunning/sentry,mvaled/sentry,mitsuhiko/sentry,llonchj/sentry,ifduyue/sentry,ifduyue/sentry,vperron/sentry,Natim/sentry,daevaorn/sentry,ifduyue/sentry,looker/sentry,BayanGroup/sentry,felixbuenemann/sentry,ewdurbin/sentry,1tush/sentry,zenefits/sentry,songyi199111/sentry,BuildingLink/sentry,fotinakis/sentry,TedaLIEz/sentry,vperron/sentry,JackDanger/sentry,llonchj/sentry,mvaled/sentry,wujuguang/sentry,gg7/sentry,1tush/sentry,nicholasserra/sentry,songyi199111/sentry,argonemyth/sentry,kevinlondon/sentry,hongliang5623/sentry,boneyao/sentry,wong2/sentry,BayanGroup/sentry,jean/sentry,BuildingLink/sentry,gencer/sentry,mvaled/sentry,boneyao/sentry,fuziontech/sentry,Natim/sentry,drcapulet/sentry,felixbuenemann/sentry,ifduyue/sentry,ngonzalvez/sentry,TedaLIEz/sentry,kevinastone/sentry,nicholasserra/sentry,boneyao/sentry,kevinlondon/sentry,alexm92/sentry,mvaled/sentry,beeftornado/sentry,JamesMura/sentry,wujuguang/sentry,JTCunning/sentry,fotinakis/sentry,zenefits/sentry,JTCunning/sentry,Kryz/sentry,pauloschilling/sentry,BuildingLink/sentry,looker/sentry,fotinakis/sentry,zenefits/sentry,imankulov/sentry,fuziontech/sentry,looker/sentry,vperron/sentry,looker/sentry,JackDanger/sentry,songyi199111/sentry,gencer/sentry,mvaled/sentry,beeftornado/sentry,jean/sentry,ifduyue/sentry,kevinastone/sentry,llonchj/sentry,jean/sentry,ewdurbin/sentry,mitsuhiko/sentry,jean/sentry,argonemyth/sentry,korealerts1/sentry,JamesMura/sentry | from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import Release
class ProjectReleasesEndpoint(ProjectEndpoint):
doc_section = DocSection.RELEASES
def get(self, request, project):
"""
List a project's releases
Retrieve a list of releases for a given project.
{method} {path}
"""
queryset = Release.objects.filter(
project=project,
- ).order_by('-date_added')
+ )
return self.paginate(
request=request,
queryset=queryset,
- # TODO(dcramer): we want to sort by date_added
order_by='-id',
on_results=lambda x: serialize(x, request.user),
)
| Maintain project release sort order | ## Code Before:
from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import Release
class ProjectReleasesEndpoint(ProjectEndpoint):
doc_section = DocSection.RELEASES
def get(self, request, project):
"""
List a project's releases
Retrieve a list of releases for a given project.
{method} {path}
"""
queryset = Release.objects.filter(
project=project,
).order_by('-date_added')
return self.paginate(
request=request,
queryset=queryset,
# TODO(dcramer): we want to sort by date_added
order_by='-id',
on_results=lambda x: serialize(x, request.user),
)
## Instruction:
Maintain project release sort order
## Code After:
from __future__ import absolute_import
from sentry.api.base import DocSection
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import Release
class ProjectReleasesEndpoint(ProjectEndpoint):
doc_section = DocSection.RELEASES
def get(self, request, project):
"""
List a project's releases
Retrieve a list of releases for a given project.
{method} {path}
"""
queryset = Release.objects.filter(
project=project,
)
return self.paginate(
request=request,
queryset=queryset,
order_by='-id',
on_results=lambda x: serialize(x, request.user),
)
| ...
project=project,
)
...
queryset=queryset,
order_by='-id',
... |
3024a35626118e5fcf504bde9785992aa7e3eea5 | apps/members/models.py | apps/members/models.py | from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
pass
class UserAddress(Address):
class AddressType(DjangoChoices):
primary = ChoiceItem('primary', label=_("Primary"))
secondary = ChoiceItem('secondary', label=_("Secondary"))
address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices,
default=AddressType.primary)
user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address")
class Meta:
verbose_name = _("user address")
verbose_name_plural = _("user addresses")
#default_serializer = 'members.serializers.UserProfileSerializer' | from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
# Create an address if none exists
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super(Member, self).save(force_insert=False, force_update=False, using=None, update_fields=None)
try:
self.address
except UserAddress.DoesNotExist:
self.address = UserAddress.objects.create(user=self)
self.address.save()
class UserAddress(Address):
class AddressType(DjangoChoices):
primary = ChoiceItem('primary', label=_("Primary"))
secondary = ChoiceItem('secondary', label=_("Secondary"))
address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices,
default=AddressType.primary)
user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address")
class Meta:
verbose_name = _("user address")
verbose_name_plural = _("user addresses")
#default_serializer = 'members.serializers.UserProfileSerializer' | Create an address if none exists for a user | Create an address if none exists for a user
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site | from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
- pass
+
+ # Create an address if none exists
+ def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
+ super(Member, self).save(force_insert=False, force_update=False, using=None, update_fields=None)
+ try:
+ self.address
+ except UserAddress.DoesNotExist:
+ self.address = UserAddress.objects.create(user=self)
+ self.address.save()
class UserAddress(Address):
class AddressType(DjangoChoices):
primary = ChoiceItem('primary', label=_("Primary"))
secondary = ChoiceItem('secondary', label=_("Secondary"))
address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices,
default=AddressType.primary)
user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address")
class Meta:
verbose_name = _("user address")
verbose_name_plural = _("user addresses")
#default_serializer = 'members.serializers.UserProfileSerializer' | Create an address if none exists for a user | ## Code Before:
from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
pass
class UserAddress(Address):
class AddressType(DjangoChoices):
primary = ChoiceItem('primary', label=_("Primary"))
secondary = ChoiceItem('secondary', label=_("Secondary"))
address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices,
default=AddressType.primary)
user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address")
class Meta:
verbose_name = _("user address")
verbose_name_plural = _("user addresses")
#default_serializer = 'members.serializers.UserProfileSerializer'
## Instruction:
Create an address if none exists for a user
## Code After:
from django.db import models
from bluebottle.bb_accounts.models import BlueBottleBaseUser
from bluebottle.utils.models import Address
from djchoices.choices import DjangoChoices, ChoiceItem
from django.conf import settings
from django.utils.translation import ugettext as _
class Member(BlueBottleBaseUser):
# Create an address if none exists
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super(Member, self).save(force_insert=False, force_update=False, using=None, update_fields=None)
try:
self.address
except UserAddress.DoesNotExist:
self.address = UserAddress.objects.create(user=self)
self.address.save()
class UserAddress(Address):
class AddressType(DjangoChoices):
primary = ChoiceItem('primary', label=_("Primary"))
secondary = ChoiceItem('secondary', label=_("Secondary"))
address_type = models.CharField(_("address type"),max_length=10, blank=True, choices=AddressType.choices,
default=AddressType.primary)
user = models.OneToOneField(settings.AUTH_USER_MODEL, verbose_name=_("user"), related_name="address")
class Meta:
verbose_name = _("user address")
verbose_name_plural = _("user addresses")
#default_serializer = 'members.serializers.UserProfileSerializer' | // ... existing code ...
class Member(BlueBottleBaseUser):
# Create an address if none exists
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
super(Member, self).save(force_insert=False, force_update=False, using=None, update_fields=None)
try:
self.address
except UserAddress.DoesNotExist:
self.address = UserAddress.objects.create(user=self)
self.address.save()
// ... rest of the code ... |
a8112a8ee3723d5ae097998efc7c43bd27cbee95 | engineer/processors.py | engineer/processors.py | import logging
import subprocess
from path import path
from engineer.conf import settings
__author__ = '[email protected]'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file)
css_file = path("%s.css" % str(input_file)[:-5])
if not css_file.exists():
cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split()
try:
result = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
logger.critical(e.cmd)
logger.critical(e.output)
raise
logger.info("Preprocessed LESS file %s." % file)
return ""
| import logging
import platform
import subprocess
from path import path
from engineer.conf import settings
__author__ = '[email protected]'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file)
css_file = path("%s.css" % str(input_file)[:-5])
if not css_file.exists():
cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split()
try:
result = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
logger.critical("Error pre-processing LESS file %s." % file)
logger.critical(e.output)
exit(1355)
except WindowsError as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.strerror)
exit(1355)
except Exception as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.message)
if platform.system() != 'Windows':
logger.critical("Are you sure lessc is on your path?")
exit(1355)
logger.info("Preprocessed LESS file %s." % file)
return ""
| Handle LESS preprocessor errors more gracefully. | Handle LESS preprocessor errors more gracefully.
| Python | mit | tylerbutler/engineer,tylerbutler/engineer,tylerbutler/engineer | import logging
+ import platform
import subprocess
from path import path
from engineer.conf import settings
__author__ = '[email protected]'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file)
css_file = path("%s.css" % str(input_file)[:-5])
if not css_file.exists():
cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split()
try:
result = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
- logger.critical(e.cmd)
+ logger.critical("Error pre-processing LESS file %s." % file)
logger.critical(e.output)
- raise
+ exit(1355)
+ except WindowsError as e:
+ logger.critical("Unexpected error pre-processing LESS file %s." % file)
+ logger.critical(e.strerror)
+ exit(1355)
+ except Exception as e:
+ logger.critical("Unexpected error pre-processing LESS file %s." % file)
+ logger.critical(e.message)
+ if platform.system() != 'Windows':
+ logger.critical("Are you sure lessc is on your path?")
+ exit(1355)
logger.info("Preprocessed LESS file %s." % file)
return ""
| Handle LESS preprocessor errors more gracefully. | ## Code Before:
import logging
import subprocess
from path import path
from engineer.conf import settings
__author__ = '[email protected]'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file)
css_file = path("%s.css" % str(input_file)[:-5])
if not css_file.exists():
cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split()
try:
result = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
logger.critical(e.cmd)
logger.critical(e.output)
raise
logger.info("Preprocessed LESS file %s." % file)
return ""
## Instruction:
Handle LESS preprocessor errors more gracefully.
## Code After:
import logging
import platform
import subprocess
from path import path
from engineer.conf import settings
__author__ = '[email protected]'
logger = logging.getLogger(__name__)
# Helper function to preprocess LESS files on demand
def preprocess_less(file):
input_file = path(settings.OUTPUT_CACHE_DIR / settings.ENGINEER.STATIC_DIR.basename() / file)
css_file = path("%s.css" % str(input_file)[:-5])
if not css_file.exists():
cmd = str.format(str(settings.LESS_PREPROCESSOR), infile=input_file, outfile=css_file).split()
try:
result = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
logger.critical("Error pre-processing LESS file %s." % file)
logger.critical(e.output)
exit(1355)
except WindowsError as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.strerror)
exit(1355)
except Exception as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.message)
if platform.system() != 'Windows':
logger.critical("Are you sure lessc is on your path?")
exit(1355)
logger.info("Preprocessed LESS file %s." % file)
return ""
| // ... existing code ...
import logging
import platform
import subprocess
// ... modified code ...
except subprocess.CalledProcessError as e:
logger.critical("Error pre-processing LESS file %s." % file)
logger.critical(e.output)
exit(1355)
except WindowsError as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.strerror)
exit(1355)
except Exception as e:
logger.critical("Unexpected error pre-processing LESS file %s." % file)
logger.critical(e.message)
if platform.system() != 'Windows':
logger.critical("Are you sure lessc is on your path?")
exit(1355)
logger.info("Preprocessed LESS file %s." % file)
// ... rest of the code ... |
e64b8fcb9854edcc689bf4b8fec5b3c589e7226f | netdisco/discoverables/belkin_wemo.py | netdisco/discoverables/belkin_wemo.py | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''),
device['serialNumber'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| Add serialnumber to wemo discovery info tuple | Add serialnumber to wemo discovery info tuple
| Python | mit | sfam/netdisco,brburns/netdisco,balloob/netdisco | """ Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
- entry.values['location'], device.get('macAddress', ''))
+ entry.values['location'], device.get('macAddress', ''),
+ device['serialNumber'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| Add serialnumber to wemo discovery info tuple | ## Code Before:
""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''))
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
## Instruction:
Add serialnumber to wemo discovery info tuple
## Code After:
""" Discovers Belkin Wemo devices. """
from . import SSDPDiscoverable
class Discoverable(SSDPDiscoverable):
""" Adds support for discovering Belkin WeMo platform devices. """
def info_from_entry(self, entry):
""" Returns most important info from a uPnP entry. """
device = entry.description['device']
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''),
device['serialNumber'])
def get_entries(self):
""" Returns all Belkin Wemo entries. """
return self.find_by_device_description(
{'manufacturer': 'Belkin International Inc.'})
| // ... existing code ...
return (device['friendlyName'], device['modelName'],
entry.values['location'], device.get('macAddress', ''),
device['serialNumber'])
// ... rest of the code ... |
da71a95586f17de48cb1067a8809da1e583b42cf | other/wrapping-cpp/swig/cpointerproblem/test_examples.py | other/wrapping-cpp/swig/cpointerproblem/test_examples.py |
import os
os.system('make all')
import example1
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.system('make alternate')
import example2
def test2_f():
assert example2.f(1) - 1 <= 10 ** -7
def test2_myfun():
assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7
os.system('make clean')
|
import os
import pytest
#print("pwd:")
#os.system('pwd')
#import subprocess
#subprocess.check_output('pwd')
os.system('make all')
import example1
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
"""Demonstrate that calling code with wrong object type results
in TypeError exception."""
with pytest.raises(TypeError):
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.system('make alternate')
import example2
def test2_f():
assert example2.f(1) - 1 <= 10 ** -7
def test2_myfun():
assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7
os.system('make clean')
| Add pytest.raises for test that fails on purpose. | Add pytest.raises for test that fails on purpose.
| Python | bsd-2-clause | ryanpepper/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python,ryanpepper/oommf-python,fangohr/oommf-python |
import os
+ import pytest
+
+ #print("pwd:")
+ #os.system('pwd')
+ #import subprocess
+ #subprocess.check_output('pwd')
+
+
os.system('make all')
import example1
+
+
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
+ """Demonstrate that calling code with wrong object type results
+ in TypeError exception."""
+ with pytest.raises(TypeError):
- assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
+ assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.system('make alternate')
import example2
def test2_f():
assert example2.f(1) - 1 <= 10 ** -7
def test2_myfun():
assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7
os.system('make clean')
| Add pytest.raises for test that fails on purpose. | ## Code Before:
import os
os.system('make all')
import example1
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.system('make alternate')
import example2
def test2_f():
assert example2.f(1) - 1 <= 10 ** -7
def test2_myfun():
assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7
os.system('make clean')
## Instruction:
Add pytest.raises for test that fails on purpose.
## Code After:
import os
import pytest
#print("pwd:")
#os.system('pwd')
#import subprocess
#subprocess.check_output('pwd')
os.system('make all')
import example1
def test_f():
assert example1.f(1) - 1 <= 10 ** -7
def test_myfun():
"""Demonstrate that calling code with wrong object type results
in TypeError exception."""
with pytest.raises(TypeError):
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
os.system('make alternate')
import example2
def test2_f():
assert example2.f(1) - 1 <= 10 ** -7
def test2_myfun():
assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7
os.system('make clean')
| # ... existing code ...
import pytest
#print("pwd:")
#os.system('pwd')
#import subprocess
#subprocess.check_output('pwd')
os.system('make all')
# ... modified code ...
import example1
def test_f():
...
def test_myfun():
"""Demonstrate that calling code with wrong object type results
in TypeError exception."""
with pytest.raises(TypeError):
assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7
# ... rest of the code ... |
d4e7571b1d361a9d24650a74fffbc1980c2bbc70 | blaze/compute/air/frontend/ckernel_impls.py | blaze/compute/air/frontend/ckernel_impls.py |
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
try:
overload = function.best_match('ckernel', argtypes)
except datashape.CoercionError:
return op
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
|
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
# Default overload is CKERNEL, so no need to look it up again
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
| Remove redundant 'ckernel' overload match | Remove redundant 'ckernel' overload match
| Python | bsd-3-clause | jdmcbr/blaze,alexmojaki/blaze,FrancescAlted/blaze,aterrel/blaze,xlhtc007/blaze,mwiebe/blaze,cowlicks/blaze,ChinaQuants/blaze,mwiebe/blaze,mwiebe/blaze,LiaoPan/blaze,xlhtc007/blaze,dwillmer/blaze,FrancescAlted/blaze,scls19fr/blaze,cpcloud/blaze,scls19fr/blaze,caseyclements/blaze,mrocklin/blaze,FrancescAlted/blaze,ContinuumIO/blaze,FrancescAlted/blaze,LiaoPan/blaze,dwillmer/blaze,nkhuyu/blaze,jdmcbr/blaze,cowlicks/blaze,alexmojaki/blaze,aterrel/blaze,jcrist/blaze,maxalbert/blaze,mrocklin/blaze,caseyclements/blaze,ContinuumIO/blaze,nkhuyu/blaze,mwiebe/blaze,ChinaQuants/blaze,aterrel/blaze,jcrist/blaze,cpcloud/blaze,maxalbert/blaze |
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
+ # Default overload is CKERNEL, so no need to look it up again
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
-
- try:
- overload = function.best_match('ckernel', argtypes)
- except datashape.CoercionError:
- return op
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
| Remove redundant 'ckernel' overload match | ## Code Before:
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
try:
overload = function.best_match('ckernel', argtypes)
except datashape.CoercionError:
return op
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
## Instruction:
Remove redundant 'ckernel' overload match
## Code After:
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
# Default overload is CKERNEL, so no need to look it up again
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
| ...
# Default overload is CKERNEL, so no need to look it up again
func = overload.func
...
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
... |
f919aa183d1a82ba745df6a5640e8a7a83f8e87e | stix/indicator/valid_time.py | stix/indicator/valid_time.py | from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
self._fields = {}
self.start_time = start_time
self.end_time = end_time
| from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
| Change ValidTime to a mixbox Entity | Change ValidTime to a mixbox Entity
| Python | bsd-3-clause | STIXProject/python-stix | from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
+ from mixbox.entities import Entity
- class ValidTime(stix.Entity):
+ class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
- self._fields = {}
+ super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
| Change ValidTime to a mixbox Entity | ## Code Before:
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
class ValidTime(stix.Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
self._fields = {}
self.start_time = start_time
self.end_time = end_time
## Instruction:
Change ValidTime to a mixbox Entity
## Code After:
from mixbox import fields
import stix
from stix.common import DateTimeWithPrecision
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
_binding = indicator_binding
_binding_class = _binding.ValidTimeType
start_time = fields.TypedField("Start_Time", DateTimeWithPrecision)
end_time = fields.TypedField("End_Time", DateTimeWithPrecision)
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
self.end_time = end_time
| ...
import stix.bindings.indicator as indicator_binding
from mixbox.entities import Entity
class ValidTime(Entity):
_namespace = "http://stix.mitre.org/Indicator-2"
...
def __init__(self, start_time=None, end_time=None):
super(ValidTime, self).__init__()
self.start_time = start_time
... |
817d9c78f939de2b01ff518356ed0414178aaa6d | avalonstar/apps/api/serializers.py | avalonstar/apps/api/serializers.py | from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class SeriesSerializer(serializers.ModelSerializer):
class Meta:
model = Series
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
| from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class RaidSerializer(serializers.ModelSerializer):
class Meta:
model = Raid
class SeriesSerializer(serializers.ModelSerializer):
class Meta:
model = Series
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
| Add Raid to the API. | Add Raid to the API.
| Python | apache-2.0 | bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv | from rest_framework import serializers
- from apps.broadcasts.models import Broadcast, Series
+ from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
+
+
+ class RaidSerializer(serializers.ModelSerializer):
+ class Meta:
+ model = Raid
class SeriesSerializer(serializers.ModelSerializer):
class Meta:
model = Series
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
| Add Raid to the API. | ## Code Before:
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class SeriesSerializer(serializers.ModelSerializer):
class Meta:
model = Series
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
## Instruction:
Add Raid to the API.
## Code After:
from rest_framework import serializers
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
class BroadcastSerializer(serializers.ModelSerializer):
class Meta:
depth = 1
model = Broadcast
class RaidSerializer(serializers.ModelSerializer):
class Meta:
model = Raid
class SeriesSerializer(serializers.ModelSerializer):
class Meta:
model = Series
class GameSerializer(serializers.ModelSerializer):
class Meta:
model = Game
| ...
from apps.broadcasts.models import Broadcast, Raid, Series
from apps.games.models import Game
...
model = Broadcast
class RaidSerializer(serializers.ModelSerializer):
class Meta:
model = Raid
... |
3ff24c90c9f50c849ea22e7d2d0a5fa11d1e777a | examples/hello-world.py | examples/hello-world.py | from glumpy import app, gl, gloo, glm, data, text
window = app.Window(width=512, height=512)
@window.event
def on_draw(dt):
window.clear()
label.draw(x=256, y=256, color=(1,1,1,1))
font = text.TextureFont(data.get("OpenSans-Regular.ttf"), 64)
label = text.Label("Hello World !", font,
anchor_x = 'center', anchor_y = 'center')
app.run()
| from glumpy import app, gl, gloo, glm, data
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection
window = app.Window(width=512, height=512)
@window.event
def on_draw(dt):
window.clear()
label.draw()
x,y,z = 256,256,0
font = FontManager.get("OpenSans-Regular.ttf", 64, mode='agg')
label = GlyphCollection('agg', transform=OrthographicProjection(Position()))
label.append("Hello World !", font,
anchor_x = 'center', anchor_y = 'center',
origin=(x,y,z), color=(1,1,1,1))
window.attach(label["transform"])
app.run()
| Fix hello world example broken imports | Fix hello world example broken imports
| Python | bsd-3-clause | glumpy/glumpy,glumpy/glumpy | - from glumpy import app, gl, gloo, glm, data, text
+ from glumpy import app, gl, gloo, glm, data
+ from glumpy.graphics.text import FontManager
+ from glumpy.graphics.collections import GlyphCollection
+ from glumpy.transforms import Position, OrthographicProjection
window = app.Window(width=512, height=512)
@window.event
def on_draw(dt):
window.clear()
- label.draw(x=256, y=256, color=(1,1,1,1))
+ label.draw()
- font = text.TextureFont(data.get("OpenSans-Regular.ttf"), 64)
+ x,y,z = 256,256,0
+ font = FontManager.get("OpenSans-Regular.ttf", 64, mode='agg')
+ label = GlyphCollection('agg', transform=OrthographicProjection(Position()))
- label = text.Label("Hello World !", font,
+ label.append("Hello World !", font,
- anchor_x = 'center', anchor_y = 'center')
+ anchor_x = 'center', anchor_y = 'center',
+ origin=(x,y,z), color=(1,1,1,1))
+
+ window.attach(label["transform"])
+
app.run()
| Fix hello world example broken imports | ## Code Before:
from glumpy import app, gl, gloo, glm, data, text
window = app.Window(width=512, height=512)
@window.event
def on_draw(dt):
window.clear()
label.draw(x=256, y=256, color=(1,1,1,1))
font = text.TextureFont(data.get("OpenSans-Regular.ttf"), 64)
label = text.Label("Hello World !", font,
anchor_x = 'center', anchor_y = 'center')
app.run()
## Instruction:
Fix hello world example broken imports
## Code After:
from glumpy import app, gl, gloo, glm, data
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection
window = app.Window(width=512, height=512)
@window.event
def on_draw(dt):
window.clear()
label.draw()
x,y,z = 256,256,0
font = FontManager.get("OpenSans-Regular.ttf", 64, mode='agg')
label = GlyphCollection('agg', transform=OrthographicProjection(Position()))
label.append("Hello World !", font,
anchor_x = 'center', anchor_y = 'center',
origin=(x,y,z), color=(1,1,1,1))
window.attach(label["transform"])
app.run()
| # ... existing code ...
from glumpy import app, gl, gloo, glm, data
from glumpy.graphics.text import FontManager
from glumpy.graphics.collections import GlyphCollection
from glumpy.transforms import Position, OrthographicProjection
# ... modified code ...
window.clear()
label.draw()
x,y,z = 256,256,0
font = FontManager.get("OpenSans-Regular.ttf", 64, mode='agg')
label = GlyphCollection('agg', transform=OrthographicProjection(Position()))
label.append("Hello World !", font,
anchor_x = 'center', anchor_y = 'center',
origin=(x,y,z), color=(1,1,1,1))
window.attach(label["transform"])
app.run()
# ... rest of the code ... |
d69ced31c6dd174b1149f97a08de0ec5e8805d13 | env_modifiers.py | env_modifiers.py | def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
env.render(*render_args, **render_kwargs)
return base_step(action)
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
| def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
| Call _render before _step to support BipedalWalker | Call _render before _step to support BipedalWalker
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
+ ret = base_step(action)
env.render(*render_args, **render_kwargs)
- return base_step(action)
+ return ret
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
| Call _render before _step to support BipedalWalker | ## Code Before:
def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
env.render(*render_args, **render_kwargs)
return base_step(action)
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
## Instruction:
Call _render before _step to support BipedalWalker
## Code After:
def make_rendered(env, *render_args, **render_kwargs):
base_step = env._step
def _step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
env._step = _step
def make_timestep_limited(env, timestep_limit):
t = 1
old__step = env._step
old__reset = env._reset
def _step(action):
nonlocal t
observation, reward, done, info = old__step(action)
if t >= timestep_limit:
done = True
t += 1
return observation, reward, done, info
def _reset():
nonlocal t
t = 1
return old__reset()
env._step = _step
env._reset = _reset
def make_action_filtered(env, action_filter):
old_step = env.step
def step(action):
return old_step(action_filter(action))
env.step = step
def make_reward_filtered(env, reward_filter):
old__step = env._step
def _step(action):
observation, reward, done, info = old__step(action)
reward = reward_filter(reward)
return observation, reward, done, info
env._step = _step
| ...
def _step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
... |
6c157525bc32f1e6005be69bd6fde61d0d002ad3 | wizard/post_function.py | wizard/post_function.py | from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context['post_function_args'],
**context['post_function_kwargs']
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
| from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context.get('post_function_args', []),
**context.get('post_function_kwargs', {})
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
| Remove some required arguments in post function context | Remove some required arguments in post function context
| Python | agpl-3.0 | xcgd/account_move_reversal | from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
- *context['post_function_args'],
+ *context.get('post_function_args', []),
- **context['post_function_kwargs']
+ **context.get('post_function_kwargs', {})
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
| Remove some required arguments in post function context | ## Code Before:
from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context['post_function_args'],
**context['post_function_kwargs']
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
## Instruction:
Remove some required arguments in post function context
## Code After:
from openerp import pooler
def call_post_function(cr, uid, context):
"""This functionality allows users of module account.move.reversal
to call a function of the desired openerp model, after the
reversal of the move.
The call automatically sends at least the database cursor (cr) and
the user id (uid) for security reasons.
Two key parameters are required in the context to do so:
- 'post_function_obj': the osv model where the function is defined,
- 'post_function_name': the name of the function to call,
And two optional key parameters:
- 'post_function_args': an iterable object listing the required
arguments to pass after 'cr, uid',
- 'post_function_kwargs': a dictionary object listing the
optionnal keyword args to pass.
"""
if 'post_function_obj' in context:
# We get the function addr by its name,
# and call it with (cr, uid, *args, **kwargs)
getattr(
pooler.get_pool(cr.dbname)[context['post_function_obj']],
context['post_function_name']
)(
cr, uid,
*context.get('post_function_args', []),
**context.get('post_function_kwargs', {})
)
# We clean the context to avoid multiple calls of the function.
context.pop('post_function_obj')
context.pop('post_function_name')
context.pop('post_function_args')
context.pop('post_function_kwargs')
| ...
cr, uid,
*context.get('post_function_args', []),
**context.get('post_function_kwargs', {})
)
... |
65c712464813ba41b564aa3e0116e60805f6681e | storyboard/api/v1/system_info.py | storyboard/api/v1/system_info.py |
from oslo_config import cfg
from pbr.version import VersionInfo
from pecan import rest
from pecan.secure import secure
from storyboard.api.auth import authorization_checks as checks
from storyboard.api.v1 import wmodels
import wsmeext.pecan as wsme_pecan
CONF = cfg.CONF
class SystemInfoController(rest.RestController):
"""REST controller for sysinfo endpoint.
Provides Get methods for System information.
"""
@secure(checks.guest)
@wsme_pecan.wsexpose(wmodels.SystemInfo)
def get(self):
"""Retrieve the Storyboard system information.
"""
sb_ver = VersionInfo('storyboard')
return wmodels.SystemInfo(version=sb_ver.version_string())
|
from oslo_config import cfg
from pbr.version import VersionInfo
from pecan import rest
from pecan.secure import secure
from storyboard.api.auth import authorization_checks as checks
from storyboard.api.v1 import wmodels
import wsmeext.pecan as wsme_pecan
CONF = cfg.CONF
class SystemInfoController(rest.RestController):
"""REST controller for sysinfo endpoint.
Provides Get methods for System information.
"""
@secure(checks.guest)
@wsme_pecan.wsexpose(wmodels.SystemInfo)
def get(self):
"""Retrieve the Storyboard system information.
Example::
curl https://my.example.org/api/v1/systeminfo
"""
sb_ver = VersionInfo('storyboard')
return wmodels.SystemInfo(version=sb_ver.version_string())
| Add example commands for the Systeminfo api | Add example commands for the Systeminfo api
Currently the api documentation does not include example commands.
It would be very friendly for our users to have some example commands
to follow and use the api.
This patch adds examples to the Systeminfo section of the api documentation.
Change-Id: Ic3d56d207db696100754a5a1fd5764f2f3f0a7f3
| Python | apache-2.0 | ColdrickSotK/storyboard,ColdrickSotK/storyboard,ColdrickSotK/storyboard |
from oslo_config import cfg
from pbr.version import VersionInfo
from pecan import rest
from pecan.secure import secure
from storyboard.api.auth import authorization_checks as checks
from storyboard.api.v1 import wmodels
import wsmeext.pecan as wsme_pecan
CONF = cfg.CONF
class SystemInfoController(rest.RestController):
"""REST controller for sysinfo endpoint.
Provides Get methods for System information.
"""
@secure(checks.guest)
@wsme_pecan.wsexpose(wmodels.SystemInfo)
def get(self):
"""Retrieve the Storyboard system information.
+
+ Example::
+
+ curl https://my.example.org/api/v1/systeminfo
+
"""
sb_ver = VersionInfo('storyboard')
return wmodels.SystemInfo(version=sb_ver.version_string())
| Add example commands for the Systeminfo api | ## Code Before:
from oslo_config import cfg
from pbr.version import VersionInfo
from pecan import rest
from pecan.secure import secure
from storyboard.api.auth import authorization_checks as checks
from storyboard.api.v1 import wmodels
import wsmeext.pecan as wsme_pecan
CONF = cfg.CONF
class SystemInfoController(rest.RestController):
"""REST controller for sysinfo endpoint.
Provides Get methods for System information.
"""
@secure(checks.guest)
@wsme_pecan.wsexpose(wmodels.SystemInfo)
def get(self):
"""Retrieve the Storyboard system information.
"""
sb_ver = VersionInfo('storyboard')
return wmodels.SystemInfo(version=sb_ver.version_string())
## Instruction:
Add example commands for the Systeminfo api
## Code After:
from oslo_config import cfg
from pbr.version import VersionInfo
from pecan import rest
from pecan.secure import secure
from storyboard.api.auth import authorization_checks as checks
from storyboard.api.v1 import wmodels
import wsmeext.pecan as wsme_pecan
CONF = cfg.CONF
class SystemInfoController(rest.RestController):
"""REST controller for sysinfo endpoint.
Provides Get methods for System information.
"""
@secure(checks.guest)
@wsme_pecan.wsexpose(wmodels.SystemInfo)
def get(self):
"""Retrieve the Storyboard system information.
Example::
curl https://my.example.org/api/v1/systeminfo
"""
sb_ver = VersionInfo('storyboard')
return wmodels.SystemInfo(version=sb_ver.version_string())
| # ... existing code ...
"""Retrieve the Storyboard system information.
Example::
curl https://my.example.org/api/v1/systeminfo
"""
# ... rest of the code ... |
7baac2883aa6abc0f1f458882025ba1d0e9baab2 | app/migrations/versions/4ef20b76cab1_.py | app/migrations/versions/4ef20b76cab1_.py |
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION postgis;")
op.execute("CREATE EXTENSION postgis_topology;")
def downgrade():
op.execute("DROP EXTENSION postgis_topology;")
op.execute("DROP EXTENSION postgis;")
|
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
op.execute("CREATE EXTENSION IF NOT EXISTS postgis_topology;")
def downgrade():
op.execute("DROP EXTENSION IF EXISTS postgis_topology;")
op.execute("DROP EXTENSION IF EXISTS postgis;")
| Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist. | Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist.
| Python | mit | openchattanooga/cpd-zones-old,openchattanooga/cpd-zones-old |
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
- op.execute("CREATE EXTENSION postgis;")
+ op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
- op.execute("CREATE EXTENSION postgis_topology;")
+ op.execute("CREATE EXTENSION IF NOT EXISTS postgis_topology;")
def downgrade():
- op.execute("DROP EXTENSION postgis_topology;")
+ op.execute("DROP EXTENSION IF EXISTS postgis_topology;")
- op.execute("DROP EXTENSION postgis;")
+ op.execute("DROP EXTENSION IF EXISTS postgis;")
| Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist. | ## Code Before:
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION postgis;")
op.execute("CREATE EXTENSION postgis_topology;")
def downgrade():
op.execute("DROP EXTENSION postgis_topology;")
op.execute("DROP EXTENSION postgis;")
## Instruction:
Add extra code to PostGIS migration to only create extensions if they're not already there. Drop on rollback only if extensions exist.
## Code After:
# revision identifiers, used by Alembic.
revision = '4ef20b76cab1'
down_revision = '55004b0f00d6'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
op.execute("CREATE EXTENSION IF NOT EXISTS postgis_topology;")
def downgrade():
op.execute("DROP EXTENSION IF EXISTS postgis_topology;")
op.execute("DROP EXTENSION IF EXISTS postgis;")
| // ... existing code ...
def upgrade():
op.execute("CREATE EXTENSION IF NOT EXISTS postgis;")
op.execute("CREATE EXTENSION IF NOT EXISTS postgis_topology;")
// ... modified code ...
def downgrade():
op.execute("DROP EXTENSION IF EXISTS postgis_topology;")
op.execute("DROP EXTENSION IF EXISTS postgis;")
// ... rest of the code ... |
afd27c62049e87eaefbfb5f38c6b61b461656384 | formulae/token.py | formulae/token.py | class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
| class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __hash__(self):
return hash((self.type, self.lexeme, self.literal))
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return (
self.type == other.type
and self.lexeme == other.lexeme
and self.literal == other.literal
)
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
| Add hash and eq methods to Token | Add hash and eq methods to Token
| Python | mit | bambinos/formulae | class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
+
+ def __hash__(self):
+ return hash((self.type, self.lexeme, self.literal))
+
+ def __eq__(self, other):
+ if not isinstance(other, type(self)):
+ return False
+ return (
+ self.type == other.type
+ and self.lexeme == other.lexeme
+ and self.literal == other.literal
+ )
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
| Add hash and eq methods to Token | ## Code Before:
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
## Instruction:
Add hash and eq methods to Token
## Code After:
class Token:
"""Representation of a single Token"""
def __init__(self, _type, lexeme, literal=None):
self.type = _type
self.lexeme = lexeme
self.literal = literal
def __hash__(self):
return hash((self.type, self.lexeme, self.literal))
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return (
self.type == other.type
and self.lexeme == other.lexeme
and self.literal == other.literal
)
def __repr__(self):
string_list = [
"'type': " + str(self.type),
"'lexeme': " + str(self.lexeme),
"'literal': " + str(self.literal),
]
return "{" + ", ".join(string_list) + "}"
def __str__(self):
string_list = [
"type= " + str(self.type),
"lexeme= " + str(self.lexeme),
"literal= " + str(self.literal),
]
return "Token(" + ", ".join(string_list) + ")"
| ...
self.literal = literal
def __hash__(self):
return hash((self.type, self.lexeme, self.literal))
def __eq__(self, other):
if not isinstance(other, type(self)):
return False
return (
self.type == other.type
and self.lexeme == other.lexeme
and self.literal == other.literal
)
... |
bb8d9aa91b6d1bf2a765113d5845402c059e6969 | IPython/core/payloadpage.py | IPython/core/payloadpage.py | """A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
text=strng,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
| """A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
| Remove leftover text key from our own payload creation | Remove leftover text key from our own payload creation
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | """A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
- text=strng,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
| Remove leftover text key from our own payload creation | ## Code Before:
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
text=strng,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
## Instruction:
Remove leftover text key from our own payload creation
## Code After:
"""A payload based version of page."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from IPython.core.getipython import get_ipython
#-----------------------------------------------------------------------------
# Classes and functions
#-----------------------------------------------------------------------------
def page(strng, start=0, screen_lines=0, pager_cmd=None):
"""Print a string, piping through a pager.
This version ignores the screen_lines and pager_cmd arguments and uses
IPython's payload system instead.
Parameters
----------
strng : str or mime-dict
Text to page, or a mime-type keyed dict of already formatted data.
start : int
Starting line at which to place the display.
"""
# Some routines may auto-compute start offsets incorrectly and pass a
# negative value. Offset to 0 for robustness.
start = max(0, start)
shell = get_ipython()
if isinstance(strng, dict):
data = strng
else:
data = {'text/plain' : strng}
payload = dict(
source='page',
data=data,
start=start,
screen_lines=screen_lines,
)
shell.payload_manager.write_payload(payload)
def install_payload_page():
"""Install this version of page as IPython.core.page.page."""
from IPython.core import page as corepage
corepage.page = page
| # ... existing code ...
data=data,
start=start,
# ... rest of the code ... |
511a133599b86deae83d9ad8a3f7a7c5c45e07bf | core/views.py | core/views.py | from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
| from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
form = ContactForm()
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
| Clear the contact form after it has been successfully posted. | Clear the contact form after it has been successfully posted.
| Python | bsd-3-clause | PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari | from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
+ form = ContactForm()
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
| Clear the contact form after it has been successfully posted. | ## Code Before:
from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
## Instruction:
Clear the contact form after it has been successfully posted.
## Code After:
from django.shortcuts import render
from django.http import Http404
from django.contrib.messages import success
from django.utils.translation import ugettext_lazy as _
from wagtail.wagtailcore.models import Page
from .models import HomePage, StaticPage
from category.models import Category
from .forms import ContactForm
def home_page(request, slug="home-page"):
home_page = HomePage.objects.get(slug=slug)
return render(request, "core/home_page.html", {
"page": home_page,
"categories": Category.objects.all()[:9]
})
def static_page(request, slug=None):
try:
page = Page.objects.get(slug=slug)
except Page.DoesNotExist:
raise Http404
if page.specific_class == HomePage:
return home_page(request, page.slug)
return render(request, "core/static_page.html", {
"self": page.specific
})
def contribute(request, slug=None):
page = StaticPage.objects.get(slug=slug)
return render(request, "core/contribute.html", {
"self": page
})
def contact_us(request):
if request.method == "POST":
form = ContactForm(request.POST)
if form.is_valid():
form.save()
success(request, _("Your query has successfully been sent"))
form = ContactForm()
else:
form = ContactForm()
return render(request, "core/contact_us.html", {
"contact_form": form
})
| // ... existing code ...
success(request, _("Your query has successfully been sent"))
form = ContactForm()
else:
// ... rest of the code ... |
3d95d4e69e927e6f21ebad1b9730142df19eeef7 | my_button.py | my_button.py |
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, *args, **kwargs):
a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self):
self.state = "normal"
a_m.instance.click()
|
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, *args, **kwargs):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
| Allow buttons to be silenced | Allow buttons to be silenced
| Python | mit | cropleyb/pentai,cropleyb/pentai,cropleyb/pentai |
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, *args, **kwargs):
+ if not hasattr(self, "silent"):
- a_m.instance.click()
+ a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self):
self.state = "normal"
+ if not hasattr(self, "silent"):
- a_m.instance.click()
+ a_m.instance.click()
| Allow buttons to be silenced | ## Code Before:
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, *args, **kwargs):
a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self):
self.state = "normal"
a_m.instance.click()
## Instruction:
Allow buttons to be silenced
## Code After:
from kivy.uix.button import Button
import audio as a_m
class MyButton(Button):
def on_touch_up(self, *args, **kwargs):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
def sim_press(self):
self.state = "down"
def sim_release(self):
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
| ...
def on_touch_up(self, *args, **kwargs):
if not hasattr(self, "silent"):
a_m.instance.click()
super(MyButton, self).on_touch_up(*args, **kwargs)
...
self.state = "normal"
if not hasattr(self, "silent"):
a_m.instance.click()
... |
429ffd7f41dda00f662167f179aea73b7d018807 | pi_setup/system.py | pi_setup/system.py | import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "install", "avahi-daemon"])
subprocess.call(["apt-get", "-y", "install", "rpi-update"])
subprocess.call(["pip", "install", "virtualenv"])
if __name__ == '__main__':
main()
| import subprocess
from utils.installation import OptionalInstall
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "install", "avahi-daemon"])
subprocess.call(["apt-get", "-y", "install", "rpi-update"])
subprocess.call(["pip", "install", "virtualenv"])
optional_install_upstart()
def optional_install_upstart():
prompt_txt = "Want to install Upstart (Y/N): "
skip_txt = "Skipping Upstart server..."
def action():
subprocess.call(["apt-get", "-y", "install", "upstart"])
OptionalInstall(prompt_txt, skip_txt, action).run()
if __name__ == '__main__':
main()
| Make upstart an optional install | Make upstart an optional install
| Python | mit | projectweekend/Pi-Setup,projectweekend/Pi-Setup | import subprocess
+ from utils.installation import OptionalInstall
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "install", "avahi-daemon"])
subprocess.call(["apt-get", "-y", "install", "rpi-update"])
subprocess.call(["pip", "install", "virtualenv"])
+ optional_install_upstart()
+
+
+ def optional_install_upstart():
+ prompt_txt = "Want to install Upstart (Y/N): "
+ skip_txt = "Skipping Upstart server..."
+
+ def action():
+ subprocess.call(["apt-get", "-y", "install", "upstart"])
+
+ OptionalInstall(prompt_txt, skip_txt, action).run()
if __name__ == '__main__':
main()
| Make upstart an optional install | ## Code Before:
import subprocess
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "install", "avahi-daemon"])
subprocess.call(["apt-get", "-y", "install", "rpi-update"])
subprocess.call(["pip", "install", "virtualenv"])
if __name__ == '__main__':
main()
## Instruction:
Make upstart an optional install
## Code After:
import subprocess
from utils.installation import OptionalInstall
def main():
subprocess.call(["apt-get", "update"])
subprocess.call(["apt-get", "-y", "upgrade"])
subprocess.call(["apt-get", "-y", "install", "python-dev"])
subprocess.call(["apt-get", "-y", "install", "python-pip"])
subprocess.call(["apt-get", "-y", "install", "avahi-daemon"])
subprocess.call(["apt-get", "-y", "install", "rpi-update"])
subprocess.call(["pip", "install", "virtualenv"])
optional_install_upstart()
def optional_install_upstart():
prompt_txt = "Want to install Upstart (Y/N): "
skip_txt = "Skipping Upstart server..."
def action():
subprocess.call(["apt-get", "-y", "install", "upstart"])
OptionalInstall(prompt_txt, skip_txt, action).run()
if __name__ == '__main__':
main()
| ...
import subprocess
from utils.installation import OptionalInstall
...
subprocess.call(["pip", "install", "virtualenv"])
optional_install_upstart()
def optional_install_upstart():
prompt_txt = "Want to install Upstart (Y/N): "
skip_txt = "Skipping Upstart server..."
def action():
subprocess.call(["apt-get", "-y", "install", "upstart"])
OptionalInstall(prompt_txt, skip_txt, action).run()
... |
4eae42a542c67e4b47e4b7fffc0b746fdb934f51 | librarypaste/mongostore.py | librarypaste/mongostore.py | import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid, data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
| import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
doc.update(data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
| Allow data=None, even though the spec doesn't allow it | Allow data=None, even though the spec doesn't allow it
| Python | mit | yougov/librarypaste,yougov/librarypaste | import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
- def _store(self, uid, content, data):
+ def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
+ doc = dict(uid=uid)
+ if data:
- doc = dict(uid=uid, data=bson.Binary(data))
+ doc.update(data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
| Allow data=None, even though the spec doesn't allow it | ## Code Before:
import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid, data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
## Instruction:
Allow data=None, even though the spec doesn't allow it
## Code After:
import pymongo
import bson
from datastore import DataStore
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
doc.update(data=bson.Binary(data))
doc.update(content)
self.librarypaste.pastes.save(doc)
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.librarypaste.pastes.update(query, update)
def _retrieve(self, uid):
"""Return a dict with the contents of the paste, including the raw
data, if any, as the key 'data'. Must pass in uid, not shortid."""
query = dict(uid=uid)
return self.librarypaste.pastes.find_one(query)
def lookup(self, nick):
"""Looks for the most recent paste by a given nick.
Returns the uid or None"""
query = dict(nick=nick)
order = dict(time=pymongo.DESCENDING)
recs = self.librarypaste.pastes.find(query).order(order).limit(1)
try:
return next(recs)['uid']
except StopIteration:
pass
def _lookupUid(self, shortid):
query = dict(shortid=shortid)
rec = self.librarypaste.pastes.find_one(query)
return rec['uid']
| # ... existing code ...
class MongoDBDataStore(pymongo.Connection, DataStore):
def _store(self, uid, content, data=None):
"""Store the given dict of content at uid. Nothing returned."""
doc = dict(uid=uid)
if data:
doc.update(data=bson.Binary(data))
doc.update(content)
# ... rest of the code ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.