commit stringlengths 40 40 | old_file stringlengths 4 106 | new_file stringlengths 4 106 | old_contents stringlengths 10 2.94k | new_contents stringlengths 21 2.95k | subject stringlengths 16 444 | message stringlengths 17 2.63k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 43k | ndiff stringlengths 52 3.31k | instruction stringlengths 16 444 | content stringlengths 133 4.32k | diff stringlengths 49 3.61k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bc5abf988956235b48aeb1234d9944fe70be619a | pytest_hidecaptured.py | pytest_hidecaptured.py | def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report)))
# print("PLUG... | import pytest
@pytest.mark.tryfirst
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".f... | Fix interop issues with pytest-instafail | Fix interop issues with pytest-instafail
| Python | mit | hamzasheikh/pytest-hidecaptured | + import pytest
+
+ @pytest.mark.tryfirst
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(r... | Fix interop issues with pytest-instafail | ## Code Before:
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(report) -> {0}".format(dir(report)))
... | + import pytest
+
+ @pytest.mark.tryfirst
def pytest_runtest_logreport(report):
"""Overwrite report by removing any captured stderr."""
# print("PLUGIN SAYS -> report -> {0}".format(report))
# print("PLUGIN SAYS -> report.sections -> {0}".format(report.sections))
# print("PLUGIN SAYS -> dir(r... |
cc93d6b9ade1d15236904978f012f91b0a9d567d | examples/manage.py | examples/manage.py | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_manager(manager, ap... | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# [from aiopg.sa import create_engine]
# s... | Update sqlalchemy command configuration example | Update sqlalchemy command configuration example
| Python | bsd-3-clause | rrader/aio_manager | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
+ # [from aiopg.sa... | Update sqlalchemy command configuration example | ## Code Before:
import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
# sqlalchemy.configure_man... | import logging
from aio_manager import Manager
from aioapp.app import build_application
logging.basicConfig(level=logging.WARNING)
app = build_application()
manager = Manager(app)
# To support SQLAlchemy commands, use this
#
# from aio_manager.commands.ext import sqlalchemy
+ # [from aiopg.sa... |
47d9a8df136e235f49921d4782c5e392b0101107 | migrations/versions/147_add_cleaned_subject.py | migrations/versions/147_add_cleaned_subject.py |
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_column('thread', sa.Column('_clea... |
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_column('thread', sa.Column('_clea... | Make _cleaned_subject migration match declared schema. | Make _cleaned_subject migration match declared schema.
Test Plan: Upgrade old database to head.
Reviewers: kav-ya
Reviewed By: kav-ya
Differential Revision: https://review.inboxapp.com/D1394
| Python | agpl-3.0 | Eagles2F/sync-engine,Eagles2F/sync-engine,EthanBlackburn/sync-engine,PriviPK/privipk-sync-engine,PriviPK/privipk-sync-engine,nylas/sync-engine,closeio/nylas,jobscore/sync-engine,jobscore/sync-engine,jobscore/sync-engine,wakermahmud/sync-engine,PriviPK/privipk-sync-engine,wakermahmud/sync-engine,gale320/sync-engine,Eagl... |
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_col... | Make _cleaned_subject migration match declared schema. | ## Code Before:
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_column('thread', ... |
# revision identifiers, used by Alembic.
revision = '486c7fa5b533'
down_revision = 'c77a90d524'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.sql import text
def upgrade():
conn = op.get_bind()
conn.execute(text("set @@lock_wait_timeout = 20;"))
op.add_col... |
1ef76b4f4395c9b5e3c2338822947999d5581013 | labs/lab-3/ex-3-2.events.py | labs/lab-3/ex-3-2.events.py | import tspapi
api = tspapi.API()
source = tspapi.Source(ref='myhost')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)
| import tspapi
api = tspapi.API()
source = tspapi.Source(ref='myhost', _type='host')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)
| Add type field to source | Add type field to source
| Python | apache-2.0 | jdgwartney/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,boundary/tsi-lab,boundary/tsi-lab,boundary/tsi-lab,jdgwartney/tsi-lab,jdgwartney/tsi-lab | import tspapi
api = tspapi.API()
- source = tspapi.Source(ref='myhost')
+ source = tspapi.Source(ref='myhost', _type='host')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)
| Add type field to source | ## Code Before:
import tspapi
api = tspapi.API()
source = tspapi.Source(ref='myhost')
api.event_create(title="bar", fingerprint_fields=['@title'], source=source)
## Instruction:
Add type field to source
## Code After:
import tspapi
api = tspapi.API()
source = tspapi.Source(ref='myhost', _type='host')
api.event_cre... | import tspapi
api = tspapi.API()
- source = tspapi.Source(ref='myhost')
+ source = tspapi.Source(ref='myhost', _type='host')
? ++++++++++++++
api.event_create(title="bar", fingerprint_fields=['@title'], source=source) |
6ea9d0c4b4e2a117e3e74c34cc77f83d262e62d8 | sendgrid_events/models.py | sendgrid_events/models.py | import json
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from sendgrid_events.signals import batch_processed
class Event(models.Model):
kind = models.CharField(max_length=75)
email = models.CharField(max_length=150)
data = JSONField(blank=True)
crea... | import json
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from sendgrid_events.signals import batch_processed
class Event(models.Model):
kind = models.CharField(max_length=75)
email = models.CharField(max_length=150)
data = JSONField(blank=True)
crea... | Update for latest Sendgrid webhook format | Update for latest Sendgrid webhook format | Python | bsd-3-clause | digital-eskimo/django-sendgrid-events,kronok/django-sendgrid-events,eldarion/django-sendgrid-events,rorito/django-sendgrid-events | import json
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from sendgrid_events.signals import batch_processed
class Event(models.Model):
kind = models.CharField(max_length=75)
email = models.CharField(max_length=150)
data = JS... | Update for latest Sendgrid webhook format | ## Code Before:
import json
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from sendgrid_events.signals import batch_processed
class Event(models.Model):
kind = models.CharField(max_length=75)
email = models.CharField(max_length=150)
data = JSONField(blan... | import json
from django.db import models
from django.utils import timezone
from jsonfield import JSONField
from sendgrid_events.signals import batch_processed
class Event(models.Model):
kind = models.CharField(max_length=75)
email = models.CharField(max_length=150)
data = JS... |
e14b3fad26dce8dad3ca97c06e624f1d6b0764f9 | mqueue/__init__.py | mqueue/__init__.py | __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
| __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
| Set default encoding to fix unicode errors | Set default encoding to fix unicode errors
| Python | mit | synw/django-mqueue,synw/django-mqueue,synw/django-mqueue | __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
+
+ import sys
+ reload(sys)
+ sys.setdefaultencoding("utf-8")
| Set default encoding to fix unicode errors | ## Code Before:
__version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
## Instruction:
Set default encoding to fix unicode errors
## Code After:
__version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
| __version__ = '0.5.5'
default_app_config = 'mqueue.apps.MqueueConfig'
+ import sys
+ reload(sys)
+ sys.setdefaultencoding("utf-8")
+ |
49e95022577eb40bcf9e1d1c9f95be7269fd0e3b | scripts/update_acq_stats.py | scripts/update_acq_stats.py |
from mica.stats import update_acq_stats
update_acq_stats.main()
import os
table_file = mica.stats.acq_stats.table_file
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {tfile} is larger than 50MB and may need
Warning: to be manually repacked (i.e.):
Warning:
Warning: ptrepack --chun... | import os
from mica.stats import update_acq_stats
import mica.stats.acq_stats
update_acq_stats.main()
table_file = mica.stats.acq_stats.TABLE_FILE
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {tfile} is larger than 50MB and may need
Warning: to be manually repacked (i.e.):
Warni... | Fix reference to acq table file in script | Fix reference to acq table file in script
| Python | bsd-3-clause | sot/mica,sot/mica | -
+ import os
from mica.stats import update_acq_stats
+ import mica.stats.acq_stats
update_acq_stats.main()
- import os
+
- table_file = mica.stats.acq_stats.table_file
+ table_file = mica.stats.acq_stats.TABLE_FILE
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {tf... | Fix reference to acq table file in script | ## Code Before:
from mica.stats import update_acq_stats
update_acq_stats.main()
import os
table_file = mica.stats.acq_stats.table_file
file_stat = os.stat(table_file)
if file_stat.st_size > 50e6:
print("""
Warning: {tfile} is larger than 50MB and may need
Warning: to be manually repacked (i.e.):
Warning:
Warning:... | -
+ import os
from mica.stats import update_acq_stats
+ import mica.stats.acq_stats
update_acq_stats.main()
- import os
+
- table_file = mica.stats.acq_stats.table_file
? ^^^^^ ^^^^
+ table_file = mica.stats.acq_stats.TABLE_FILE
? ^^^^^ ^^^^
... |
9fb89f885dd26b530b4cc95427373f06ddc7d13d | emptiness.py | emptiness.py |
import argparse
import requests
import timetable
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday")
parser.add_argument("-t", "--time", default='', required=True, help="The time the block ... |
import argparse
import requests
import timetable
import datetime
import time
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--day", default='', required=False, help="Day to check the timetable on. eg: Thursday")
parser.add_argument("-t", "--time", default='', required=Fa... | Use current time if no arguments given | Use current time if no arguments given
| Python | mit | egeldenhuys/emptiness,egeldenhuys/emptiness,egeldenhuys/emptiness |
import argparse
import requests
import timetable
+ import datetime
+ import time
if __name__ == '__main__':
parser = argparse.ArgumentParser()
- parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday")
+ parser.add_argument("-d", "--day",... | Use current time if no arguments given | ## Code Before:
import argparse
import requests
import timetable
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday")
parser.add_argument("-t", "--time", default='', required=True, help="The... |
import argparse
import requests
import timetable
+ import datetime
+ import time
if __name__ == '__main__':
parser = argparse.ArgumentParser()
- parser.add_argument("-d", "--day", default='', required=True, help="Day to check the timetable on. eg: Thursday")
? ... |
592ffbcd7fbbc29bfd377b5abadb39aa29f1c88d | foyer/tests/conftest.py | foyer/tests/conftest.py | import pytest
@pytest.fixture(scope="session")
def initdir(tmpdir):
tmpdir.chdir()
| import pytest
@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| Switch from scope="session" to autouse=True | Switch from scope="session" to autouse=True
| Python | mit | iModels/foyer,mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer | import pytest
- @pytest.fixture(scope="session")
+ @pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| Switch from scope="session" to autouse=True | ## Code Before:
import pytest
@pytest.fixture(scope="session")
def initdir(tmpdir):
tmpdir.chdir()
## Instruction:
Switch from scope="session" to autouse=True
## Code After:
import pytest
@pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir()
| import pytest
- @pytest.fixture(scope="session")
+ @pytest.fixture(autouse=True)
def initdir(tmpdir):
tmpdir.chdir() |
1e90db8de39bd8c4b1a4d58148b991af8b5c32dd | storage/models/fighter.py | storage/models/fighter.py | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = Column(String(STR_SIZE... | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = Column(String(STR_SIZE... | Add restriction for specialization string in db | Add restriction for specialization string in db
| Python | apache-2.0 | Some1Nebo/ufcpy | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = ... | Add restriction for specialization string in db | ## Code Before:
from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = Column... | from storage.models.base import *
class Fighter(Base):
__tablename__ = 'fighters'
id = Column(Integer, primary_key=True)
ref = Column(String(STR_SIZE), unique=True, nullable=False)
name = Column(String(STR_SIZE), nullable=False)
country = Column(String(STR_SIZE))
city = ... |
d70ccd856bb4ddb061ff608716ef15f778380d62 | gnsq/stream/defalte.py | gnsq/stream/defalte.py | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
self._decompressor = zlib.decompressobj(level)
self._compressor = zlib.compressobj(level)
super(DefalteSocket, self).__i... | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
wbits = -zlib.MAX_WBITS
self._decompressor = zlib.decompressobj(wbits)
self._compressor = zlib.compressobj(level, zlib.D... | Set correct waits for deflate. | Set correct waits for deflate.
| Python | bsd-3-clause | wtolson/gnsq,hiringsolved/gnsq,wtolson/gnsq | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
+ wbits = -zlib.MAX_WBITS
- self._decompressor = zlib.decompressobj(level)
+ self._decompressor = zlib.d... | Set correct waits for deflate. | ## Code Before:
from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
self._decompressor = zlib.decompressobj(level)
self._compressor = zlib.compressobj(level)
super(DefalteS... | from __future__ import absolute_import
import zlib
from .compression import CompressionSocket
class DefalteSocket(CompressionSocket):
def __init__(self, socket, level):
+ wbits = -zlib.MAX_WBITS
- self._decompressor = zlib.decompressobj(level)
? ... |
eaa13f9005a8aaf8c748a98de697b03eee9e675b | salt/client/netapi.py | salt/client/netapi.py | '''
The main entry point for salt-api
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt-api libs
import salt.loader
import salt.utils.process
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
... | '''
The main entry point for salt-api
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt-api libs
import salt.loader
import salt.utils.process
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is configured to run
... | Add log error if we run salt-api w/ no config | Add log error if we run salt-api w/ no config
Currently, the salt-api script will exit with no error or hint of why it
failed if there is no netapi module configured. Added a short line if
we find no api modules to start, warning the user that the config may be
missing.
Fixes #28240
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
The main entry point for salt-api
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt-api libs
import salt.loader
import salt.utils.process
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi mo... | Add log error if we run salt-api w/ no config | ## Code Before:
'''
The main entry point for salt-api
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt-api libs
import salt.loader
import salt.utils.process
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi module that is confi... | '''
The main entry point for salt-api
'''
from __future__ import absolute_import
# Import python libs
import logging
# Import salt-api libs
import salt.loader
import salt.utils.process
logger = logging.getLogger(__name__)
class NetapiClient(object):
'''
Start each netapi mo... |
888584a49e697551c4f680cc8651be2fe80fc65d | configgen/generators/ppsspp/ppssppGenerator.py | configgen/generators/ppsspp/ppssppGenerator.py | import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
def generate(self, system,... | import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
def generate(self, system,... | Remove a bad typo from reicast | Remove a bad typo from reicast
| Python | mit | nadenislamarre/recalbox-configgen,recalbox/recalbox-configgen,digitalLumberjack/recalbox-configgen | import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
... | Remove a bad typo from reicast | ## Code Before:
import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
def genera... | import Command
#~ import reicastControllers
import recalboxFiles
from generators.Generator import Generator
import ppssppControllers
import shutil
import os.path
import ConfigParser
class PPSSPPGenerator(Generator):
# Main entry of the module
# Configure fba and return a command
... |
cc09da295d61965af1552b35b7ece0caf4e5a399 | accountant/interface/forms.py | accountant/interface/forms.py | from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash = forms.IntegerField(re... | from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash = forms.IntegerField(re... | Hide Game ID input since it is automatically set | Hide Game ID input since it is automatically set
| Python | mit | XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant,XeryusTC/18xx-accountant | from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash = f... | Hide Game ID input since it is automatically set | ## Code Before:
from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash = forms... | from django import forms
from django.core.exceptions import NON_FIELD_ERRORS
from django.utils.translation import ugettext_lazy as _
from core import models
DUPLICATE_PLAYER_ERROR = \
_('There is already a player with this name in your game')
class CreateGameForm(forms.Form):
bank_cash = f... |
2f635e890414f777fbe3ddde1aea74ab13558313 | llvmlite/tests/test_dylib.py | llvmlite/tests/test_dylib.py | import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def test_bad_library(self)... | from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
from ctypes.util import find_library
import unittest
@unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(TestCase):
def setUp(self):
ll... | Add tests to check loading library. | Add tests to check loading library.
| Python | bsd-2-clause | m-labs/llvmlite,pitrou/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,markdewing/llvmlite,pitrou/llvmlite,numba/llvmlite,markdewing/llvmlite,sklam/llvmlite,sklam/llvmlite,pitrou/llvmlite,numba/llvmlite,ssarangi/llvmlite,markdewing/llvmlite,squisher/llvmlite,ssarangi/llvmlite,m-labs/llvmlite,numba/llvmlite,numba/llvmlite,sq... | - import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
+ from ctypes.util import find_library
+ import unittest
-
+ @unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(T... | Add tests to check loading library. | ## Code Before:
import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
class TestDylib(TestCase):
def setUp(self):
llvm.initialize()
llvm.initialize_native_target()
llvm.initialize_native_asmprinter()
def test_b... | - import unittest
from . import TestCase
from llvmlite import binding as llvm
from llvmlite.binding import dylib
import platform
+ from ctypes.util import find_library
+ import unittest
-
+ @unittest.skipUnless(platform.system() in {"Linux", "Darwin"}, "Unsupport test for current OS")
class TestDylib(T... |
77a5ecc7c406e4a6acf814a2f0381dc605e0d14c | leds/led_dance.py | leds/led_dance.py |
import pyb
def led_dance(delay):
dots = {}
control = pyb.Switch(1)
while True:
if not control.value():
dots[pyb.millis() % 25] = 16
for d in dots:
pyb.pixel(d, dots[d])
if dots[d] == 0:
del(dots[d])
else:
dots[... |
import microbit
def led_dance(delay):
dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
microbit.display.set_display_mode(1)
while True:
dots[microbit.random(5)][microbit.random(5)] = 128
for i in range(5):
for j in range(5):
microbit.display.image.set_pixel_value(i,... | Update for new version of micropython for microbit | Update for new version of micropython for microbit
| Python | mit | jrmhaig/microbit_playground |
- import pyb
+ import microbit
def led_dance(delay):
- dots = {}
- control = pyb.Switch(1)
+ dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
+ microbit.display.set_display_mode(1)
while True:
+ dots[microbit.random(5)][microbit.random(5)] = 128
+ for i in range(5):
+ ... | Update for new version of micropython for microbit | ## Code Before:
import pyb
def led_dance(delay):
dots = {}
control = pyb.Switch(1)
while True:
if not control.value():
dots[pyb.millis() % 25] = 16
for d in dots:
pyb.pixel(d, dots[d])
if dots[d] == 0:
del(dots[d])
else:
... |
- import pyb
+ import microbit
def led_dance(delay):
- dots = {}
- control = pyb.Switch(1)
+ dots = [ [0]*5, [0]*5, [0]*5, [0]*5, [0]*5 ]
+ microbit.display.set_display_mode(1)
while True:
+ dots[microbit.random(5)][microbit.random(5)] = 128
+ for i in range(5):
+ ... |
606b2b6c84e9f9f67606a4d7e521cf4805855a98 | migrations/versions/0311_populate_returned_letters.py | migrations/versions/0311_populate_returned_letters.py | from alembic import op
from app.dao.returned_letters_dao import insert_or_update_returned_letters
revision = '0311_populate_returned_letters'
down_revision = '0310_returned_letters_table'
def upgrade():
conn = op.get_bind()
sql = """
select id, service_id, reference
from notification_histor... | from alembic import op
revision = '0311_populate_returned_letters'
down_revision = '0310_returned_letters_table'
def upgrade():
conn = op.get_bind()
sql = """
select id, service_id, reference, updated_at
from notification_history
where notification_type = 'letter'
and notific... | Change the insert to use updated_at as the reported_at date | Change the insert to use updated_at as the reported_at date
| Python | mit | alphagov/notifications-api,alphagov/notifications-api | from alembic import op
-
- from app.dao.returned_letters_dao import insert_or_update_returned_letters
revision = '0311_populate_returned_letters'
down_revision = '0310_returned_letters_table'
def upgrade():
conn = op.get_bind()
sql = """
- select id, service_id, reference
+ ... | Change the insert to use updated_at as the reported_at date | ## Code Before:
from alembic import op
from app.dao.returned_letters_dao import insert_or_update_returned_letters
revision = '0311_populate_returned_letters'
down_revision = '0310_returned_letters_table'
def upgrade():
conn = op.get_bind()
sql = """
select id, service_id, reference
from not... | from alembic import op
-
- from app.dao.returned_letters_dao import insert_or_update_returned_letters
revision = '0311_populate_returned_letters'
down_revision = '0310_returned_letters_table'
def upgrade():
conn = op.get_bind()
sql = """
- select id, service_id, reference
+ ... |
7a21d2bccbcff2eb6a8b7cfd00c38a28553c0bcd | gratipay/models/country.py | gratipay/models/country.py | from __future__ import absolute_import, division, print_function, unicode_literals
from postgres.orm import Model
class Country(Model):
"""Represent country records from our database (read-only).
:var int id: the record's primary key in our ``countries`` table
:var unicode code: the country's `ISO 3166-... | from __future__ import absolute_import, division, print_function, unicode_literals
from postgres.orm import Model
class Country(Model):
"""Represent country records from our database (read-only).
:var int id: the record's primary key in our ``countries`` table
:var unicode code: the country's `ISO 3166-... | Add a helper to Country; should go upstream prolly | Add a helper to Country; should go upstream prolly
| Python | mit | gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com | from __future__ import absolute_import, division, print_function, unicode_literals
from postgres.orm import Model
class Country(Model):
"""Represent country records from our database (read-only).
:var int id: the record's primary key in our ``countries`` table
:var unicode code: the ... | Add a helper to Country; should go upstream prolly | ## Code Before:
from __future__ import absolute_import, division, print_function, unicode_literals
from postgres.orm import Model
class Country(Model):
"""Represent country records from our database (read-only).
:var int id: the record's primary key in our ``countries`` table
:var unicode code: the coun... | from __future__ import absolute_import, division, print_function, unicode_literals
from postgres.orm import Model
class Country(Model):
"""Represent country records from our database (read-only).
:var int id: the record's primary key in our ``countries`` table
:var unicode code: the ... |
0eb20c8025a838d93a5854442640550d5bf05b0b | settings.py | settings.py |
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'replace with Android client ID'
IOS_CLIENT_ID = 'replace with iOS client ID'
ANDROID_AUDIENCE = WEB_CLIENT_ID
|
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com'
ANDROID_CLIENT_ID = '757224007118-dpqfa375ra8rgbpslig7beh4jb6qd03s.apps.googleusercontent.com'
IOS_CLIENT_ID = '757224007118-nfgr65... | Add android and ios client IDs | Add android and ios client IDs
| Python | apache-2.0 | elbernante/conference-central,elbernante/conference-central,elbernante/conference-central |
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com'
- ANDROID_CLIENT_ID = 'replace with Android client ID'
- IOS_CLIENT_ID = 'replace with iOS client ID'
+ ANDROID_CLIENT_ID =... | Add android and ios client IDs | ## Code Before:
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'replace with Android client ID'
IOS_CLIENT_ID = 'replace with iOS client ID'
ANDROID_AUDIENCE ... |
# Replace the following lines with client IDs obtained from the APIs
# Console or Cloud Console.
WEB_CLIENT_ID = '757224007118-0lblpo8abqeantp8mvckmabupik9edk4.apps.googleusercontent.com'
- ANDROID_CLIENT_ID = 'replace with Android client ID'
- IOS_CLIENT_ID = 'replace with iOS client ID'
+ ANDROID_CLIENT_ID =... |
2eb07ae9b98c36dc94e143003a7c44c7fbfb54f7 | stronghold/middleware.py | stronghold/middleware.py | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public if listed in in d... | Refactor away unnecessary multiple return None | Refactor away unnecessary multiple return None
| Python | mit | SunilMohanAdapa/django-stronghold,SunilMohanAdapa/django-stronghold,mgrouchy/django-stronghold | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Pu... | Refactor away unnecessary multiple return None | ## Code Before:
from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Public i... | from django.contrib.auth.decorators import login_required
from stronghold import conf, utils
class LoginRequiredMiddleware(object):
"""
Force all views to use login required
View is deemed to be public if the @public decorator is applied to the view
View is also deemed to be Pu... |
39d0c335759781de8cf1644cdf499588441b434d | tviserrys/urls.py | tviserrys/urls.py | from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from django.conf.urls import url
from django.contrib import admin
from . import views
from tviserrys.settings import MEDIA_ROOT
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^adm... | from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from django.conf.urls import url
from django.contrib import admin
from . import views
from tviserrys.settings import MEDIA_ROOT
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^tvi... | Add Tviit and profile url patterns | Add Tviit and profile url patterns
| Python | mit | DeWaster/Tviserrys,DeWaster/Tviserrys | from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from django.conf.urls import url
from django.contrib import admin
from . import views
from tviserrys.settings import MEDIA_ROOT
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index... | Add Tviit and profile url patterns | ## Code Before:
from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from django.conf.urls import url
from django.contrib import admin
from . import views
from tviserrys.settings import MEDIA_ROOT
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index')... | from django.contrib.auth import views as auth_views
from django.conf.urls import patterns, include, url
from django.conf.urls import url
from django.contrib import admin
from . import views
from tviserrys.settings import MEDIA_ROOT
urlpatterns = [
url(r'^$', views.IndexView.as_view(), name='index... |
df8ae0415f9bf10c04472fb3009e91d7c3d7e24f | teuthology/sentry.py | teuthology/sentry.py | from raven import Client
client = None
def get_client(ctx):
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
| from raven import Client
client = None
def get_client(ctx):
global client
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
| Make client a global variable | Make client a global variable
| Python | mit | robbat2/teuthology,ceph/teuthology,tchaikov/teuthology,zhouyuan/teuthology,dmick/teuthology,michaelsevilla/teuthology,dreamhost/teuthology,SUSE/teuthology,t-miyamae/teuthology,caibo2014/teuthology,yghannam/teuthology,SUSE/teuthology,SUSE/teuthology,tchaikov/teuthology,michaelsevilla/teuthology,dmick/teuthology,ktdreyer... | from raven import Client
client = None
def get_client(ctx):
+ global client
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
| Make client a global variable | ## Code Before:
from raven import Client
client = None
def get_client(ctx):
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
## Instruction:
Make client a global variable
## Code After:
from raven import Client
... | from raven import Client
client = None
def get_client(ctx):
+ global client
if client:
return client
dsn = ctx.teuthology_config.get('sentry_dsn')
if dsn:
client = Client(dsn=dsn)
return client
|
76166f243b9f5f21582c95a843ddfa174ded8602 | PyFVCOM/__init__.py | PyFVCOM/__init__.py |
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd... |
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from PyFVCOM import ctd... | Put things in in alphabetical order. | Put things in in alphabetical order.
| Python | mit | pwcazenave/PyFVCOM |
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_t... | Put things in in alphabetical order. | ## Code Before:
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_tools
from Py... |
__version__ = '1.6.2'
__author__ = 'Pierre Cazenave'
__credits__ = ['Pierre Cazenave']
__license__ = 'MIT'
__maintainer__ = 'Pierre Cazenave'
__email__ = 'pica@pml.ac.uk'
import inspect
from warnings import warn
# Import everything!
from PyFVCOM import buoy_tools
from PyFVCOM import cst_t... |
c97e5cf11fc21e2ef4ee04779a424e4d6a2b96ae | tools/perf/metrics/__init__.py | tools/perf/metrics/__init__.py |
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring something. Metrics are
helper classes used by PageMeasurements. Each PageMeasurement may use
multiple metrics; each metric should be focussed on collecting data
abo... |
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring something. Metrics are
helper classes used by PageMeasurements. Each PageMeasurement may use
multiple metrics; each metric should be focussed on collecting data
abo... | Add CustomizeBrowserOptions method to Metric base class | Add CustomizeBrowserOptions method to Metric base class
BUG=271177
Review URL: https://chromiumcodereview.appspot.com/22938004
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@217198 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | mogoweb/chromium-crosswalk,Just-D/chromium-1,M4sse/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,Just-D/chromium-1,ChromiumWebApps/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,M4sse/chr... |
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring something. Metrics are
helper classes used by PageMeasurements. Each PageMeasurement may use
multiple metrics; each metric should be focussed on collect... | Add CustomizeBrowserOptions method to Metric base class | ## Code Before:
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring something. Metrics are
helper classes used by PageMeasurements. Each PageMeasurement may use
multiple metrics; each metric should be focussed on colle... |
class Metric(object):
"""Base class for all the metrics that are used by telemetry measurements.
The Metric class represents a way of measuring something. Metrics are
helper classes used by PageMeasurements. Each PageMeasurement may use
multiple metrics; each metric should be focussed on collect... |
a8601d8a17c9ba8e87b8336870e0d52f79e0ffa2 | indra/tests/test_omnipath.py | indra/tests/test_omnipath.py | from __future__ import unicode_literals
from builtins import dict, str
from indra.statements import Phosphorylation
from indra.databases import omnipath as op
def test_query_ptms():
stmts = op.get_ptms(['Q13873'])
assert len(stmts) == 1
assert isinstance(stmts[0], Phosphorylation)
assert stmts[0].enz.n... | import requests
from indra.sources.omnipath import OmniPathModificationProcessor,\
OmniPathLiganReceptorProcessor
from indra.sources.omnipath.api import op_url
from indra.statements import Agent, Phosphorylation
from indra.preassembler.grounding_mapper import GroundingMapper
BRAF_UPID = 'P15056'
JAK2_UPID = 'O6067... | Update imports, test general web api | Update imports, test general web api
| Python | bsd-2-clause | johnbachman/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra,johnbachman/belpy,sorgerlab/belpy,sorgerlab/indra,sorgerlab/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/indra,sorgerlab/belpy | - from __future__ import unicode_literals
- from builtins import dict, str
+ import requests
+ from indra.sources.omnipath import OmniPathModificationProcessor,\
+ OmniPathLiganReceptorProcessor
+ from indra.sources.omnipath.api import op_url
- from indra.statements import Phosphorylation
+ from indra.statements im... | Update imports, test general web api | ## Code Before:
from __future__ import unicode_literals
from builtins import dict, str
from indra.statements import Phosphorylation
from indra.databases import omnipath as op
def test_query_ptms():
stmts = op.get_ptms(['Q13873'])
assert len(stmts) == 1
assert isinstance(stmts[0], Phosphorylation)
asser... | - from __future__ import unicode_literals
- from builtins import dict, str
+ import requests
+ from indra.sources.omnipath import OmniPathModificationProcessor,\
+ OmniPathLiganReceptorProcessor
+ from indra.sources.omnipath.api import op_url
- from indra.statements import Phosphorylation
+ from indra.statements im... |
ba23f58f7359b943d8d8ae7f05e15419c6918c6f | test/blacklist.py | test/blacklist.py |
blacklist = {}
|
blacklist = {'BasicExprCommandsTestCase.test_evaluate_expression_python': 'Crashed while running the entire test suite with CC=clang'
# To reproduce the crash: CC=clang ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
# The clang version used is clang-126.
# Two radars filed for... | Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python, due to crashes while running the entire test suite with clang-126. | Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python,
due to crashes while running the entire test suite with clang-126.
To reproduce:
CC=clang ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
To skip this test case:
CC=clang ./dotest.py -b blacklist.py -v -w 2> ~/Developer/Log/lldb... | Python | apache-2.0 | llvm-mirror/lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,apple/swift-lldb,llvm-mirror/lldb,apple/swift-lldb,llvm-mirror/lldb,llvm-mirror/lldb,llvm-mirror/lldb |
- blacklist = {}
+ blacklist = {'BasicExprCommandsTestCase.test_evaluate_expression_python': 'Crashed while running the entire test suite with CC=clang'
+ # To reproduce the crash: CC=clang ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
+ # The clang version used is clang-126.
+ ... | Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python, due to crashes while running the entire test suite with clang-126. | ## Code Before:
blacklist = {}
## Instruction:
Add an entry for test case BasicExprCommandsTestCase.test_evaluate_expression_python, due to crashes while running the entire test suite with clang-126.
## Code After:
blacklist = {'BasicExprCommandsTestCase.test_evaluate_expression_python': 'Crashed while running the e... |
- blacklist = {}
+ blacklist = {'BasicExprCommandsTestCase.test_evaluate_expression_python': 'Crashed while running the entire test suite with CC=clang'
+ # To reproduce the crash: CC=clang ./dotest.py -v -w 2> ~/Developer/Log/lldbtest.log
+ # The clang version used is clang-126.
+ ... |
3d1521892ba17120ca4461335713b9d2254311fe | marble/tests/test_clustering.py | marble/tests/test_clustering.py | """ Tests for the clustering computation """
from nose.tools import *
import marble as mb
# Test c = 0 in the checkerboard case
# Test c = 1 in the fully clustered case
# Test an intermediate situation with known result
| """ Tests for the clustering computation """
from nose.tools import *
import itertools
from shapely.geometry import Polygon
import marble as mb
#
# Synthetic data for tests
#
def grid():
""" Areal units arranged in a grid """
au = [i*3+j for i,j in itertools.product(range(3), repeat=2)]
units = {a:Polygo... | Add tests for the clustering of cities | Add tests for the clustering of cities
| Python | bsd-3-clause | walkerke/marble,scities/marble | """ Tests for the clustering computation """
from nose.tools import *
+ import itertools
+ from shapely.geometry import Polygon
import marble as mb
- # Test c = 0 in the checkerboard case
- # Test c = 1 in the fully clustered case
- # Test an intermediate situation with known result
+ #
+ # Synthetic data f... | Add tests for the clustering of cities | ## Code Before:
""" Tests for the clustering computation """
from nose.tools import *
import marble as mb
# Test c = 0 in the checkerboard case
# Test c = 1 in the fully clustered case
# Test an intermediate situation with known result
## Instruction:
Add tests for the clustering of cities
## Code After:
""" Tests ... | """ Tests for the clustering computation """
from nose.tools import *
+ import itertools
+ from shapely.geometry import Polygon
import marble as mb
- # Test c = 0 in the checkerboard case
- # Test c = 1 in the fully clustered case
- # Test an intermediate situation with known result
+ #
+ # Synthetic data f... |
6dfed291a253174672d7003700ab770aabcacae4 | backend/breach/models/__init__.py | backend/breach/models/__init__.py | from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| __all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| Add __all__ to models init file | Add __all__ to models init file
| Python | mit | dimriou/rupture,esarafianou/rupture,dimriou/rupture,dimkarakostas/rupture,dionyziz/rupture,dimkarakostas/rupture,esarafianou/rupture,esarafianou/rupture,dimkarakostas/rupture,dimriou/rupture,dionyziz/rupture,esarafianou/rupture,dionyziz/rupture,dimkarakostas/rupture,dionyziz/rupture,dimriou/rupture,dimriou/rupture,dion... | + __all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
| Add __all__ to models init file | ## Code Before:
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet
## Instruction:
Add __all__ to models init file
## Code After:
__all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Ro... | + __all__ = ['victim', 'target', 'round', 'sampleset']
from .victim import Victim
from .target import Target
from .round import Round
from .sampleset import SampleSet |
895d51105cd51387e3ac5db595333ff794f3e2a7 | yotta/lib/ordered_json.py | yotta/lib/ordered_json.py | import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects so that we preserve the... | import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects so that we preserve the... | Add a newline at the end of json files when writing them. | Add a newline at the end of json files when writing them.
This fixes the really irritating ping-pong of newline/nonewline when editing
json files with an editor, and with `yotta version` commands.
| Python | apache-2.0 | BlackstoneEngineering/yotta,autopulated/yotta,ARMmbed/yotta,stevenewey/yotta,ARMmbed/yotta,autopulated/yotta,ntoll/yotta,BlackstoneEngineering/yotta,stevenewey/yotta,eyeye/yotta,ntoll/yotta,eyeye/yotta | import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects... | Add a newline at the end of json files when writing them. | ## Code Before:
import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects so that... | import json
import os
import stat
from collections import OrderedDict
# provide read & write methods for json files that maintain the order of
# dictionary keys, and indent consistently
# Internals
def load(path):
with open(path, 'r') as f:
# using an ordered dictionary for objects... |
f86c925604356b25a8c5c0c71644f0df6f1b48f8 | setup_directory.py | setup_directory.py |
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io/miniconda/Miniconda-lates... |
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io/miniconda/Miniconda-lates... | Add function to install miniconda | Add function to install miniconda
| Python | mit | NGTS/pipeline-output-analysis-setup-script |
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io... | Add function to install miniconda | ## Code Before:
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io/miniconda... |
from __future__ import division, print_function, absolute_import
import argparse
import os
import subprocess as sp
from contextlib import contextmanager
import tempfile
try:
import urllib.request as urllib2
except ImportError:
import urllib2
MINICONDA_URL = 'https://repo.continuum.io... |
ebd6d12ca16003e771a7015505be1b42d96483a3 | roles/gvl.commandline-utilities/templates/jupyterhub_config.py | roles/gvl.commandline-utilities/templates/jupyterhub_config.py | c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put t... | c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127.0.0.1'
# put t... | Set log level to 'WARN' | Set log level to 'WARN' | Python | mit | gvlproject/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,nuwang/gvl_commandline_utilities,claresloggett/gvl_commandline_utilities,gvlproject/gvl_commandline_utilities | c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub... | Set log level to 'WARN' | ## Code Before:
c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub_ip = '127... | c.JupyterHub.ip = '127.0.0.1'
# The ip for the proxy API handlers
c.JupyterHub.proxy_api_ip = '127.0.0.1'
# The public facing port of the proxy
c.JupyterHub.port = 9510
# The base URL of the entire application
c.JupyterHub.base_url = '/jupyterhub'
# The ip for this process
c.JupyterHub.hub... |
e7b853c667b5785355214380954c83b843c46f05 | tests/modules/contrib/test_publicip.py | tests/modules/contrib/test_publicip.py | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest... | Remove useless mock side effect | Remove useless mock side effect
| Python | mit | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widg... | Remove useless mock side effect | ## Code Before:
import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
cl... | import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widg... |
a1c87c491bf936d441ef7fd79b531384fa174138 | simpleubjson/version.py | simpleubjson/version.py |
__version_info__ = (0, 6, 0, 'dev', 0)
__version__ = '{version}{tag}{build}'.format(
version='.'.join(map(str, __version_info__[:3])),
tag='-' + __version_info__[3] if __version_info__[3] else '',
build='.' + str(__version_info__[4]) if __version_info__[4] else ''
)
|
__version_info__ = (0, 6, 0, 'dev', 0)
__version__ = '%(version)s%(tag)s%(build)s' % {
'version': '.'.join(map(str, __version_info__[:3])),
'tag': '-' + __version_info__[3] if __version_info__[3] else '',
'build': '.' + str(__version_info__[4]) if __version_info__[4] else ''
}
| Fix compatibility with Python 2.5 | Fix compatibility with Python 2.5
| Python | bsd-2-clause | kxepal/simpleubjson,brainwater/simpleubjson,samipshah/simpleubjson,498888197/simpleubjson |
__version_info__ = (0, 6, 0, 'dev', 0)
- __version__ = '{version}{tag}{build}'.format(
+ __version__ = '%(version)s%(tag)s%(build)s' % {
- version='.'.join(map(str, __version_info__[:3])),
+ 'version': '.'.join(map(str, __version_info__[:3])),
- tag='-' + __version_info__[3] if __version_info__[3] else... | Fix compatibility with Python 2.5 | ## Code Before:
__version_info__ = (0, 6, 0, 'dev', 0)
__version__ = '{version}{tag}{build}'.format(
version='.'.join(map(str, __version_info__[:3])),
tag='-' + __version_info__[3] if __version_info__[3] else '',
build='.' + str(__version_info__[4]) if __version_info__[4] else ''
)
## Instruction:
Fix com... |
__version_info__ = (0, 6, 0, 'dev', 0)
- __version__ = '{version}{tag}{build}'.format(
+ __version__ = '%(version)s%(tag)s%(build)s' % {
- version='.'.join(map(str, __version_info__[:3])),
? ^
+ 'version': '.'.join(map(str, __version_info__[:3])),
? + ^^^
- tag='-' + __version_in... |
5547e59360126baa20e1684a22e7f88fdacb530a | s2v2.py | s2v2.py | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of_records2(my_csv... | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
def number_of_records_ignore_header(data_sample, header=True):
if header:
return len(data_sample) - 1
else:
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties,... | Create new function for number of records and do a header check | Create new function for number of records and do a header check
| Python | mit | alexmilesyounger/ds_basics | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
+ def number_of_records_ignore_header(data_sample, header=True):
+ if header:
+ return len(data_sample) - 1
+ else:
+ return len(data_sample)
+
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
... | Create new function for number of records and do a header check | ## Code Before:
from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
# print(number_of_ties, "ties in our data sample")
def number_of_records2(data_sample):
return data_sample.size
number_of_ties_my_csv = number_of... | from s2v1 import *
def number_of_records(data_sample):
return len(data_sample)
+ def number_of_records_ignore_header(data_sample, header=True):
+ if header:
+ return len(data_sample) - 1
+ else:
+ return len(data_sample)
+
number_of_ties = number_of_records(data_from_csv) - 1 # minus header row
... |
9bb312c505c2749862372c0ff56ba47e087a9edc | searx/engines/semantic_scholar.py | searx/engines/semantic_scholar.py |
from json import dumps, loads
search_url = 'https://www.semanticscholar.org/api/1/search'
def request(query, params):
params['url'] = search_url
params['method'] = 'POST'
params['headers']['content-type'] = 'application/json'
params['data'] = dumps({
"queryString": query,
"page": pa... |
from json import dumps, loads
search_url = 'https://www.semanticscholar.org/api/1/search'
def request(query, params):
params['url'] = search_url
params['method'] = 'POST'
params['headers']['content-type'] = 'application/json'
params['data'] = dumps({
"queryString": query,
"page": pa... | Remove duplicated key from dict in Semantic Scholar | Remove duplicated key from dict in Semantic Scholar
| Python | agpl-3.0 | dalf/searx,dalf/searx,dalf/searx,dalf/searx |
from json import dumps, loads
search_url = 'https://www.semanticscholar.org/api/1/search'
def request(query, params):
params['url'] = search_url
params['method'] = 'POST'
params['headers']['content-type'] = 'application/json'
params['data'] = dumps({
"queryString":... | Remove duplicated key from dict in Semantic Scholar | ## Code Before:
from json import dumps, loads
search_url = 'https://www.semanticscholar.org/api/1/search'
def request(query, params):
params['url'] = search_url
params['method'] = 'POST'
params['headers']['content-type'] = 'application/json'
params['data'] = dumps({
"queryString": query,
... |
from json import dumps, loads
search_url = 'https://www.semanticscholar.org/api/1/search'
def request(query, params):
params['url'] = search_url
params['method'] = 'POST'
params['headers']['content-type'] = 'application/json'
params['data'] = dumps({
"queryString":... |
9da50045cc9d67df8d8d075a6e2a2dc7e9f137ee | tsa/data/sb5b/tweets.py | tsa/data/sb5b/tweets.py | import os
from tsa.lib import tabular, html
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at least 'Labels' and 'Tweet' fields.'''
for row in tabular.read_xlsx(xlsx_filepa... | import os
from tsa.lib import tabular, html
import logging
logger = logging.getLogger(__name__)
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at least 'Labels' and 'Tweet' f... | Add specific iterable-like pickling handler for sb5b tweet data | Add specific iterable-like pickling handler for sb5b tweet data
| Python | mit | chbrown/tsa,chbrown/tsa,chbrown/tsa | import os
from tsa.lib import tabular, html
+
+ import logging
+ logger = logging.getLogger(__name__)
+
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at le... | Add specific iterable-like pickling handler for sb5b tweet data | ## Code Before:
import os
from tsa.lib import tabular, html
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at least 'Labels' and 'Tweet' fields.'''
for row in tabular.read_... | import os
from tsa.lib import tabular, html
+
+ import logging
+ logger = logging.getLogger(__name__)
+
xlsx_filepath = '%s/ohio/sb5-b.xlsx' % os.getenv('CORPORA', '.')
label_keys = ['For', 'Against', 'Neutral', 'Broken Link', 'Not Applicable']
def read(limit=None):
'''Yields dicts with at le... |
8d56fe74b373efe2dd3bbaffbde9eddd6fae6da7 | piot/sensor/sumppump.py | piot/sensor/sumppump.py | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out... | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
trig=GPIO(23, 'out... | Return distance from sump pump sensor | Return distance from sump pump sensor
| Python | mit | tnewman/PIoT,tnewman/PIoT,tnewman/PIoT | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
... | Return distance from sump pump sensor | ## Code Before:
import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
tr... | import time
from periphery import GPIO
from piot.sensor.base import BaseAnalogSensor
class SumpPump(BaseAnalogSensor):
def __init__(self):
self.min_normal=30
self.max_normal=200
self.unit='cm'
self.error_sentinel=None
def read_analog_sensor(self):
... |
081b1cd60e363adf941ba511c7683c0ed2843a97 | gubernator/appengine_config.py | gubernator/appengine_config.py |
import os
from google.appengine.ext import vendor
# Add any libraries installed in the "third_party" folder.
vendor.add('third_party')
# Use remote GCS calls for local development.
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
os.environ['SERVER_SOFTWARE'] += ' remote_api'
|
import os
from google.appengine.ext import vendor
from google.appengine.api import urlfetch
# Add any libraries installed in the "third_party" folder.
vendor.add('third_party')
# Use remote GCS calls for local development.
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
os.environ['SERVER_SOF... | Increase Gubernator's url fetch deadline -- 5 seconds is too fast! | Increase Gubernator's url fetch deadline -- 5 seconds is too fast!
This should avoid a lot of refreshes because some directory listing or
download takes slightly too long.
| Python | apache-2.0 | mikedanese/test-infra,gmarek/test-infra,mindprince/test-infra,shashidharatd/test-infra,cblecker/test-infra,rmmh/kubernetes-test-infra,mikedanese/test-infra,jlowdermilk/test-infra,shyamjvs/test-infra,mikedanese/test-infra,girishkalele/test-infra,grodrigues3/test-infra,monopole/test-infra,foxish/test-infra,mikedanese/tes... |
import os
from google.appengine.ext import vendor
+ from google.appengine.api import urlfetch
# Add any libraries installed in the "third_party" folder.
vendor.add('third_party')
# Use remote GCS calls for local development.
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
... | Increase Gubernator's url fetch deadline -- 5 seconds is too fast! | ## Code Before:
import os
from google.appengine.ext import vendor
# Add any libraries installed in the "third_party" folder.
vendor.add('third_party')
# Use remote GCS calls for local development.
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
os.environ['SERVER_SOFTWARE'] += ' remote_api'
... |
import os
from google.appengine.ext import vendor
+ from google.appengine.api import urlfetch
# Add any libraries installed in the "third_party" folder.
vendor.add('third_party')
# Use remote GCS calls for local development.
if os.environ.get('SERVER_SOFTWARE','').startswith('Development'):
... |
00e84b51f22f78f0243cd7b7212e70447fd5b552 | store/tests/test_forms.py | store/tests/test_forms.py | from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
data={'name':'', 'text': '', '... | from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
data={'name':'', 'text': '', '... | Test that an empty name field doesn't raise errors | Test that an empty name field doesn't raise errors
| Python | bsd-3-clause | andela-kndungu/compshop,andela-kndungu/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop,andela-kndungu/compshop,kevgathuku/compshop,kevgathuku/compshop | from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
da... | Test that an empty name field doesn't raise errors | ## Code Before:
from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
data={'name':'... | from django.test import TestCase
from store.forms import ReviewForm
from store.models import Review
from .factories import *
class ReviewFormTest(TestCase):
def test_form_validation_for_blank_items(self):
p1 = ProductFactory.create()
form = ReviewForm(
da... |
9a52024ff5b8175ee8b8d4665d3c8c667003019b | glitter/blocks/redactor/tests.py | glitter/blocks/redactor/tests.py |
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
| from __future__ import unicode_literals
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import Co... | Add test for redactor block creation | Add test for redactor block creation
| Python | bsd-3-clause | developersociety/django-glitter,blancltd/django-glitter,developersociety/django-glitter,developersociety/django-glitter,blancltd/django-glitter,blancltd/django-glitter | + from __future__ import unicode_literals
+ """
+ This file demonstrates writing tests using the unittest module. These will pass
+ when you run "manage.py test".
+ Replace this with more appropriate tests for your application.
+ """
+
+ from django.contrib.auth import get_user_model
+ from django.contrib.contentty... | Add test for redactor block creation | ## Code Before:
from django.test import TestCase
class SimpleTest(TestCase):
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
"""
self.assertEqual(1 + 1, 2)
## Instruction:
Add test for redactor block creation
## Code After:
from __future__ import unicode_lite... | + from __future__ import unicode_literals
+ """
+ This file demonstrates writing tests using the unittest module. These will pass
+ when you run "manage.py test".
+ Replace this with more appropriate tests for your application.
+ """
+
+ from django.contrib.auth import get_user_model
+ from django.contrib.contentty... |
4fec805a0a6c04ac16fd4439298a4fa05709c7ea | armstrong/hatband/tests/hatband_support/admin.py | armstrong/hatband/tests/hatband_support/admin.py | from armstrong import hatband
from hatband_support import models
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(hatband.ModelAdmin):
formfield_overrides = {
models.TextField: {'widget': Te... | from armstrong import hatband
from . import models
from django.db.models import TextField
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(hatband.ModelAdmin):
formfield_overrides = {
TextFi... | Fix these class names and imports so it works | Fix these class names and imports so it works
| Python | apache-2.0 | armstrong/armstrong.hatband,texastribune/armstrong.hatband,texastribune/armstrong.hatband,armstrong/armstrong.hatband,armstrong/armstrong.hatband,texastribune/armstrong.hatband | from armstrong import hatband
- from hatband_support import models
+ from . import models
+ from django.db.models import TextField
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(h... | Fix these class names and imports so it works | ## Code Before:
from armstrong import hatband
from hatband_support import models
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(hatband.ModelAdmin):
formfield_overrides = {
models.TextFiel... | from armstrong import hatband
- from hatband_support import models
+ from . import models
+ from django.db.models import TextField
from django.forms.widgets import TextInput
class ArticleAdmin(hatband.ModelAdmin):
class Meta:
model = models.TestArticle
class ArticleOverrideAdmin(h... |
716f6d2f8ed4e2845746bcb803092806dd8f50b7 | tx_salaries/utils/transformers/mixins.py | tx_salaries/utils/transformers/mixins.py | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department.
"""
@property
def organization(self):
return {
'name': ... | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department and needs a ``department`` property.
"""
@property
def organization(self):
... | Tweak the wording just a bit | Tweak the wording just a bit
| Python | apache-2.0 | texastribune/tx_salaries,texastribune/tx_salaries | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
- department.
+ department and needs a ``department`` property.
"""
@pr... | Tweak the wording just a bit | ## Code Before:
class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
department.
"""
@property
def organization(self):
return {
... | class OrganizationMixin(object):
"""
Adds a generic ``organization`` property to the class
This requires that the class mixing it in adds an
``ORGANIZATION_NAME`` property of the main level agency or
- department.
+ department and needs a ``department`` property.
"""
@pr... |
b9b03c1f736b38d122baafdd57bbd96657de17af | valuenetwork/api/types/apps.py | valuenetwork/api/types/apps.py | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
#import pdb; pdb.set_trace()
from valuenetwork.api.types.EconomicResource import EconomicResource... | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
""" Source of this hack:
https://stackoverflow.com/questions/37862725/django-1-9-how-to-import-in-init-py
... | Add a comment about the source of the hack | Add a comment about the source of the hack
| Python | agpl-3.0 | FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork,FreedomCoop/valuenetwork | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
- #import pdb; pdb.set_trace()
+ """ Source of this hack:
+ https://stackoverflow.... | Add a comment about the source of the hack | ## Code Before:
from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
#import pdb; pdb.set_trace()
from valuenetwork.api.types.EconomicResource import ... | from django.apps import AppConfig
import valuenetwork.api.types as types
class ApiTypesAppConfig(AppConfig):
name = 'valuenetwork.api.types'
verbose_name = "ApiTypes"
def ready(self):
- #import pdb; pdb.set_trace()
+ """ Source of this hack:
+ https://stackoverflow.... |
109085a9f5f6eded6ea2afe1f6aabaf183980d7c | scripts/jenkins/cloud/ansible/roles/heat-generator/files/dns-update.py | scripts/jenkins/cloud/ansible/roles/heat-generator/files/dns-update.py |
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-servers",
metavar="NAME",... |
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-servers",
metavar="NAME",... | Add option for name and path of cloudConfig.yml file | Add option for name and path of cloudConfig.yml file
This change adds a command line option to the dns script to specify
the name and location of the `cloudConfig.yml` file.
Signed-off-by: Nicolas Bock <4ad6fd604400c7892c7a2cb53bf674987bcaa405@suse.com>
| Python | apache-2.0 | aspiers/automation,SUSE-Cloud/automation,gosipyan/automation,gosipyan/automation,gosipyan/automation,gosipyan/automation,SUSE-Cloud/automation,aspiers/automation,aspiers/automation,aspiers/automation,SUSE-Cloud/automation,SUSE-Cloud/automation |
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-s... | Add option for name and path of cloudConfig.yml file | ## Code Before:
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-servers",
... |
import argparse
import yaml
def parse_commandline():
parser = argparse.ArgumentParser()
parser.add_argument(
"--dns-servers",
metavar="NAME",
help="A list of nameservers",
nargs="+",
default=[])
parser.add_argument(
"--ntp-s... |
6448691ed77be2fd74761e056eeb5f16a881fd54 | test_settings.py | test_settings.py | from foundry.settings import *
# We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
# in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
... | from foundry.settings import *
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
'HOST': '',
'PORT': '',
}
}
# Need this last line until django-setuptest is improved.
| Adjust test settings to be in line with jmbo-skeleton | Adjust test settings to be in line with jmbo-skeleton
| Python | bsd-3-clause | praekelt/jmbo-competition,praekelt/jmbo-competition | from foundry.settings import *
- # We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
- # in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
... | Adjust test settings to be in line with jmbo-skeleton | ## Code Before:
from foundry.settings import *
# We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
# in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
... | from foundry.settings import *
- # We cannot use ssqlite or spatialite because it cannot handle the 'distinct'
- # in admin.py.
DATABASES = {
'default': {
'ENGINE': 'django.contrib.gis.db.backends.postgis',
'NAME': 'competition',
'USER': 'test',
'PASSWORD': '',
... |
504c50bd5cf229b5686f398304ab26e707d0cad8 | partner_firstname/exceptions.py | partner_firstname/exceptions.py |
from openerp import _, exceptions
class PartnerNameError(exceptions.ValidationError):
def __init__(self, record, value=None):
self.record = record
self._value = value
self.name = _("Error(s) with partner %d's name.") % record.id
@property
def value(self):
raise NotImpleme... |
from openerp import _, exceptions
class EmptyNames(exceptions.ValidationError):
def __init__(self, record, value=_("No name is set.")):
self.record = record
self._value = value
self.name = _("Error(s) with partner %d's name.") % record.id
| Remove subclassing of exception, since there is only one. | Remove subclassing of exception, since there is only one.
| Python | agpl-3.0 | microcom/partner-contact,brain-tec/partner-contact,brain-tec/partner-contact,microcom/partner-contact |
from openerp import _, exceptions
- class PartnerNameError(exceptions.ValidationError):
+ class EmptyNames(exceptions.ValidationError):
- def __init__(self, record, value=None):
+ def __init__(self, record, value=_("No name is set.")):
self.record = record
self._value = value
... | Remove subclassing of exception, since there is only one. | ## Code Before:
from openerp import _, exceptions
class PartnerNameError(exceptions.ValidationError):
def __init__(self, record, value=None):
self.record = record
self._value = value
self.name = _("Error(s) with partner %d's name.") % record.id
@property
def value(self):
... |
from openerp import _, exceptions
- class PartnerNameError(exceptions.ValidationError):
? ^^^ ^^^ ^^^^^
+ class EmptyNames(exceptions.ValidationError):
? ^^^ ^ ^
- def __init__(self, record, value=None):
+ def __init__(self, record, value=_("No name is set.")):
? ... |
85df3afc75f52a2183ef46560f57bb6993091238 | trex/urls.py | trex/urls.py |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^api/1/projects/(?P<pk>[0-9]+)/$",
proj... | Remove the admin url mapping | Remove the admin url mapping
| Python | mit | bjoernricks/trex,bjoernricks/trex |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
- url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="pr... | Remove the admin url mapping | ## Code Before:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="project-li... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views import project
urlpatterns = patterns(
'',
- url(r"^admin/", include(admin.site.urls)),
url(r"^api/1/projects/$",
project.ProjectListCreateAPIView.as_view(),
name="pr... |
040324578680a26f3816aef6f05a731be54a377d | pyroSAR/tests/test_dev_config.py | pyroSAR/tests/test_dev_config.py | import pytest
from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE
class TestStorage:
def test_insert(self):
storage = Storage(a=1, b=2)
assert storage.a == 1
assert storage.b == 2
class TestLookup:
def test_suffix(self):
assert LOOKUP.snap.suffix[0]['Apply-Orbit-Fil... | import pytest
from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE
class TestStorage:
def test_insert(self):
storage = Storage(a=1, b=2)
assert storage.a == 1
assert storage.b == 2
class TestLookup:
def test_suffix(self):
assert LOOKUP.snap.suffix['Apply-Orbit-File']... | Update due to changes in LOOKUP. | Update due to changes in LOOKUP.
| Python | mit | johntruckenbrodt/pyroSAR,johntruckenbrodt/pyroSAR | import pytest
from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE
class TestStorage:
def test_insert(self):
storage = Storage(a=1, b=2)
assert storage.a == 1
assert storage.b == 2
class TestLookup:
def test_suffix(self):
- assert LOOKUP.sna... | Update due to changes in LOOKUP. | ## Code Before:
import pytest
from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE
class TestStorage:
def test_insert(self):
storage = Storage(a=1, b=2)
assert storage.a == 1
assert storage.b == 2
class TestLookup:
def test_suffix(self):
assert LOOKUP.snap.suffix[0][... | import pytest
from pyroSAR._dev_config import Storage, LOOKUP, URL, STORAGE
class TestStorage:
def test_insert(self):
storage = Storage(a=1, b=2)
assert storage.a == 1
assert storage.b == 2
class TestLookup:
def test_suffix(self):
- assert LOOKUP.sna... |
486633791bea00c6a846b88124860efbc7532433 | fancypages/assets/fields.py | fancypages/assets/fields.py | from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_obj = getattr(ob... | from __future__ import unicode_literals, absolute_import
import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs... | Fix south introspection rule for custom AssetField | Fix south introspection rule for custom AssetField
| Python | bsd-3-clause | tangentlabs/django-fancypages,tangentlabs/django-fancypages,tangentlabs/django-fancypages | + from __future__ import unicode_literals, absolute_import
+ import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, ... | Fix south introspection rule for custom AssetField | ## Code Before:
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, self).formfield(**kwargs)
def value_from_object(self, obj):
asset_... | + from __future__ import unicode_literals, absolute_import
+ import django
from django.db.models.fields.related import ForeignKey
from .forms import AssetField
class AssetKey(ForeignKey):
def formfield(self, **kwargs):
kwargs['form_class'] = AssetField
return super(AssetKey, ... |
54cf69b4c105038f896ceaf8af10c82fd3772bf9 | pyethapp/tests/test_export.py | pyethapp/tests/test_export.py | from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
def test_export():
# requires a chain with at least 5 blocks
assert subprocess.call('pyethapp export', shell=True) != 0
assert subprocess.call... | from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
import pytest
@pytest.mark.xfail # can not work without mock-up chain
def test_export():
# requires a chain with at least 5 blocks
assert subproc... | Mark export test XFAIL since no chain mockup exists | Mark export test XFAIL since no chain mockup exists
| Python | mit | gsalgado/pyethapp,changwu-tw/pyethapp,RomanZacharia/pyethapp,ethereum/pyethapp,gsalgado/pyethapp,ethereum/pyethapp,changwu-tw/pyethapp,vaporry/pyethapp,RomanZacharia/pyethapp,d-das/pyethapp | from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
+ import pytest
+ @pytest.mark.xfail # can not work without mock-up chain
def test_export():
# requires a chain with at least 5 b... | Mark export test XFAIL since no chain mockup exists | ## Code Before:
from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
def test_export():
# requires a chain with at least 5 blocks
assert subprocess.call('pyethapp export', shell=True) != 0
assert... | from StringIO import StringIO
import subprocess
from pyethapp.app import app
from click.testing import CliRunner
from ethereum.blocks import BlockHeader
import rlp
+ import pytest
+ @pytest.mark.xfail # can not work without mock-up chain
def test_export():
# requires a chain with at least 5 b... |
d47d56525f85c5fa8b1f6b817a85479b9eb07582 | sqlalchemy_utils/functions/__init__.py | sqlalchemy_utils/functions/__init__.py | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assi... | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
is_auto_assi... | Add query_entities to functions module import | Add query_entities to functions module import
| Python | bsd-3-clause | joshfriend/sqlalchemy-utils,joshfriend/sqlalchemy-utils,cheungpat/sqlalchemy-utils,marrybird/sqlalchemy-utils,rmoorman/sqlalchemy-utils,spoqa/sqlalchemy-utils,tonyseek/sqlalchemy-utils,tonyseek/sqlalchemy-utils,JackWink/sqlalchemy-utils,konstantinoskostis/sqlalchemy-utils | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like... | Add query_entities to functions module import | ## Code Before:
from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like,
... | from .defer_except import defer_except
from .mock import create_mock_engine, mock_engine
from .render import render_expression, render_statement
from .sort_query import sort_query, QuerySorterException
from .database import (
database_exists,
create_database,
drop_database,
escape_like... |
306336d4445149cd2f0d6fa3a58b7244eafe3cd0 | conveyor/store.py | conveyor/store.py | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def... | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._data = {}
def... | Add a RedisStore to conveyor | Add a RedisStore to conveyor
| Python | bsd-2-clause | crateio/carrier | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
... | Add a RedisStore to conveyor | ## Code Before:
class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
self._da... | class BaseStore(object):
def set(self, key, value):
raise NotImplementedError
def get(self, key):
raise NotImplementedError
class InMemoryStore(BaseStore):
def __init__(self, *args, **kwargs):
super(InMemoryStore, self).__init__(*args, **kwargs)
... |
9c12e2d6890a32d93ea6b2a9ae6f000d46182377 | ga/image/store.py | ga/image/store.py |
import StringIO
import shortuuid
from boto.s3.connection import S3Connection
from ga import settings
conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET)
bucket = conn.get_bucket(settings.AWS_BUCKET)
def upload_image_from_pil_image(image):
output = StringIO.StringIO()
image.save(output, 'JPEG')
... |
import StringIO
import shortuuid
from boto.s3.connection import S3Connection
from ga import settings
def upload_image_from_pil_image(image):
output = StringIO.StringIO()
image.save(output, 'JPEG')
output.name = 'file'
return upload_image(output)
def upload_image(stream):
conn = S3Connection(s... | Move S3 bucket connection into `upload_image` | Move S3 bucket connection into `upload_image`
| Python | mit | alexmic/great-again,alexmic/great-again |
import StringIO
import shortuuid
from boto.s3.connection import S3Connection
from ga import settings
- conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET)
- bucket = conn.get_bucket(settings.AWS_BUCKET)
-
def upload_image_from_pil_image(image):
output = StringIO.StringIO()
i... | Move S3 bucket connection into `upload_image` | ## Code Before:
import StringIO
import shortuuid
from boto.s3.connection import S3Connection
from ga import settings
conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET)
bucket = conn.get_bucket(settings.AWS_BUCKET)
def upload_image_from_pil_image(image):
output = StringIO.StringIO()
image.save(outp... |
import StringIO
import shortuuid
from boto.s3.connection import S3Connection
from ga import settings
- conn = S3Connection(settings.AWS_KEY, settings.AWS_SECRET)
- bucket = conn.get_bucket(settings.AWS_BUCKET)
-
def upload_image_from_pil_image(image):
output = StringIO.StringIO()
i... |
354fb43cc95d68b06b85e8d1fa2426ca663ef8b9 | common/__init__.py | common/__init__.py | VERSION = (0, 0, 0)
__version__ = '.'.join(map(str, VERSION))
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development') | VERSION = (0, 1, 0)
__version__ = '.'.join(map(str, VERSION))
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
# Add db_name to options for use in model.Meta class
import django.db.models.options as options
options.DEFAULT_N... | Add db_name to options for use in model.Meta class | Add db_name to options for use in model.Meta class
| Python | bsd-3-clause | baskoopmans/djcommon,baskoopmans/djcommon,baskoopmans/djcommon | - VERSION = (0, 0, 0)
+ VERSION = (0, 1, 0)
__version__ = '.'.join(map(str, VERSION))
-
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
+
+ # Add db_name to options for use in model.Meta class
+ import django.db.... | Add db_name to options for use in model.Meta class | ## Code Before:
VERSION = (0, 0, 0)
__version__ = '.'.join(map(str, VERSION))
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
## Instruction:
Add db_name to options for use in model.Meta class
## Code After:
VERSION = (0, 1... | - VERSION = (0, 0, 0)
? ^
+ VERSION = (0, 1, 0)
? ^
__version__ = '.'.join(map(str, VERSION))
-
from django import template
template.add_to_builtins('common.templatetags.common')
template.add_to_builtins('common.templatetags.development')
+
+ # Add db_name to options for use i... |
f50589ec9b61efbd2bd56cca802ffc542f5b3336 | pyrene/constants.py | pyrene/constants.py | class REPO:
'''Repo attributes'''
TYPE = 'type'
DIRECTORY = 'directory'
VOLATILE = 'volatile'
SERVE_INTERFACE = 'serve_interface'
SERVE_PORT = 'serve_port'
SERVE_USERNAME = 'serve_username'
SERVE_PASSWORD = 'serve_password'
USERNAME = 'username'
PASSWORD = 'password'
DOWNLO... | class REPO:
'''Repo attributes'''
TYPE = 'type'
DIRECTORY = 'directory'
VOLATILE = 'volatile'
SERVE_INTERFACE = 'interface'
SERVE_PORT = 'port'
SERVE_USERNAME = 'username'
SERVE_PASSWORD = 'password'
USERNAME = 'username'
PASSWORD = 'password'
DOWNLOAD_URL = 'download_url'
... | Revert "make REPO.SERVE_* attributes distinct from other attributes (username, password)" | Revert "make REPO.SERVE_* attributes distinct from other attributes (username, password)"
This reverts commit 1553f4bae5f315666fac5ad9f6600ba8b076a84b.
| Python | mit | krisztianfekete/pyrene | class REPO:
'''Repo attributes'''
TYPE = 'type'
DIRECTORY = 'directory'
VOLATILE = 'volatile'
- SERVE_INTERFACE = 'serve_interface'
+ SERVE_INTERFACE = 'interface'
- SERVE_PORT = 'serve_port'
+ SERVE_PORT = 'port'
- SERVE_USERNAME = 'serve_username'
+ SERVE_USERNAME ... | Revert "make REPO.SERVE_* attributes distinct from other attributes (username, password)" | ## Code Before:
class REPO:
'''Repo attributes'''
TYPE = 'type'
DIRECTORY = 'directory'
VOLATILE = 'volatile'
SERVE_INTERFACE = 'serve_interface'
SERVE_PORT = 'serve_port'
SERVE_USERNAME = 'serve_username'
SERVE_PASSWORD = 'serve_password'
USERNAME = 'username'
PASSWORD = 'pass... | class REPO:
'''Repo attributes'''
TYPE = 'type'
DIRECTORY = 'directory'
VOLATILE = 'volatile'
- SERVE_INTERFACE = 'serve_interface'
? ------
+ SERVE_INTERFACE = 'interface'
- SERVE_PORT = 'serve_port'
? ------
+ SERVE_PORT = 'port'
... |
6785f6ef2287bc161085bcca7f1cb8653b88a433 | resolwe/flow/management/commands/cleantestdir.py | resolwe/flow/management/commands/cleantestdir.py | import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(BaseCommand):
"""Cleanup fi... | import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(BaseCommand):
"""Cleanup fi... | Clean only volumes of type host_path | Clean only volumes of type host_path
| Python | apache-2.0 | genialis/resolwe,genialis/resolwe | import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(Bas... | Clean only volumes of type host_path | ## Code Before:
import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(BaseCommand):
... | import re
import shutil
from itertools import chain
from pathlib import Path
from django.core.management.base import BaseCommand
from resolwe.storage import settings as storage_settings
from resolwe.storage.connectors import connectors
TEST_DIR_REGEX = r"^test_.*_\d+$"
class Command(Bas... |
66ba9aa2172fbed67b67a06acb331d449d32a33c | tests/services/shop/conftest.py | tests/services/shop/conftest.py |
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail
@pytest.fixture
d... |
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail
@pytest.fixture
d... | Remove unused fixture from orderer | Remove unused fixture from orderer
| Python | bsd-3-clause | homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps |
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail... | Remove unused fixture from orderer | ## Code Before:
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail
@... |
import pytest
from byceps.services.shop.cart.models import Cart
from byceps.services.shop.sequence import service as sequence_service
from byceps.services.shop.shop import service as shop_service
from testfixtures.shop_order import create_orderer
from tests.helpers import create_user_with_detail... |
5a885124432ccb33d180a8e73c753ceab54ffdf5 | src/Itemizers.py | src/Itemizers.py |
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
def iconForName(klass, name):
"""Return the NSImage instance representing a `name` item."""
imgpath = NSBundle.bundleForClass_(klass).pathForResource_ofType_(name, 'png')
img = NSImage.alloc().initWithContentsOfFile_(imgpath)
i... |
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
haskellBundleIdentifier = 'org.purl.net.mkhl.haskell'
def iconForName(name):
"""Return the NSImage instance representing a `name` item."""
bundle = NSBundle.bundleWithIdentifier_(haskellBundleIdentifier)
imgpath = bundle.pathFo... | Simplify the icon finder function. | Simplify the icon finder function.
We statically know our bundle identifier, so we don’t have too find the bundle by runtime class.
| Python | mit | mkhl/haskell.sugar |
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
+ haskellBundleIdentifier = 'org.purl.net.mkhl.haskell'
+
- def iconForName(klass, name):
+ def iconForName(name):
"""Return the NSImage instance representing a `name` item."""
+ bundle = NSBundle.bundleWithIdentifie... | Simplify the icon finder function. | ## Code Before:
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
def iconForName(klass, name):
"""Return the NSImage instance representing a `name` item."""
imgpath = NSBundle.bundleForClass_(klass).pathForResource_ofType_(name, 'png')
img = NSImage.alloc().initWithContentsOfF... |
from Foundation import objc
from Foundation import NSBundle
from AppKit import NSImage
+ haskellBundleIdentifier = 'org.purl.net.mkhl.haskell'
+
- def iconForName(klass, name):
? -------
+ def iconForName(name):
"""Return the NSImage instance representing a `name` item."""
+ bundle = N... |
17d9c84b01a6b9adc264164041d4c226355a6943 | loadimpact/utils.py | loadimpact/utils.py |
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
... |
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o in intersect:
... | Fix float diff comparison in dict differ function. | Fix float diff comparison in dict differ function.
| Python | apache-2.0 | loadimpact/loadimpact-sdk-python |
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
change... | Fix float diff comparison in dict differ function. | ## Code Before:
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
changed = []
for o... |
__all__ = ['UTC']
from datetime import timedelta, tzinfo
_ZERO = timedelta(0)
def is_dict_different(d1, d2, epsilon=0.00000000001):
s1 = set(d1.keys())
s2 = set(d2.keys())
intersect = s1.intersection(s2)
added = s1 - intersect
removed = s2 - intersect
change... |
81a35c396834667ba322456bac5abebe748e04f9 | tests/test_django_prometheus.py | tests/test_django_prometheus.py | import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
| import django_prometheus
from django_prometheus.utils import PowersOf, _INF
import unittest
class DjangoPrometheusTest(unittest.TestCase):
def testPowersOf(self):
"""Tests utils.PowersOf."""
self.assertEqual(
[0, 1, 2, 4, 8, _INF],
PowersOf(2, 4))
self.assertEqual(
... | Add a test for PowersOf. | Add a test for PowersOf.
| Python | apache-2.0 | obytes/django-prometheus,wangwanzhong/django-prometheus,wangwanzhong/django-prometheus,korfuri/django-prometheus,DingaGa/django-prometheus,DingaGa/django-prometheus,obytes/django-prometheus,korfuri/django-prometheus | import django_prometheus
+ from django_prometheus.utils import PowersOf, _INF
import unittest
- # TODO(korfuri): Add real tests. For now, this is just a placeholder
- # to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
- def testNothing(self):
+ def testPowersOf(self):
+ ... | Add a test for PowersOf. | ## Code Before:
import django_prometheus
import unittest
# TODO(korfuri): Add real tests. For now, this is just a placeholder
# to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
def testNothing(self):
self.assertTrue(True)
if __name__ == 'main':
unittest.main()
## Instructi... | import django_prometheus
+ from django_prometheus.utils import PowersOf, _INF
import unittest
- # TODO(korfuri): Add real tests. For now, this is just a placeholder
- # to set up a testing system.
class DjangoPrometheusTest(unittest.TestCase):
- def testNothing(self):
? ^ ^^^^^
+ def te... |
27065fd302c20937d44b840472d943ce8aa652e7 | plugins/candela/girder_plugin_candela/__init__.py | plugins/candela/girder_plugin_candela/__init__.py |
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
NPM_PACKAGE_NAME = '@girder/candela'
def load(self, info):
pass
|
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
DISPLAY_NAME = 'Candela Visualization'
NPM_PACKAGE_NAME = '@girder/candela'
def load(self, info):
pass
| Add a plugin displayName property | Add a plugin displayName property
This allows the web client to display an arbitrary plugin title rather
than to be restricted to valid python/javascript tokens.
| Python | apache-2.0 | Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela |
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
+ DISPLAY_NAME = 'Candela Visualization'
NPM_PACKAGE_NAME = '@girder/candela'
def load(self, info):
pass
| Add a plugin displayName property | ## Code Before:
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
NPM_PACKAGE_NAME = '@girder/candela'
def load(self, info):
pass
## Instruction:
Add a plugin displayName property
## Code After:
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
... |
from girder.plugin import GirderPlugin
class CandelaPlugin(GirderPlugin):
+ DISPLAY_NAME = 'Candela Visualization'
NPM_PACKAGE_NAME = '@girder/candela'
def load(self, info):
pass |
057510c78f80c3592c562006413049ab1292d0a3 | ipaqe_provision_hosts/backend/base.py | ipaqe_provision_hosts/backend/base.py |
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
class IDMBackendException(Exception):
pass
class VMsNotCreatedError(IDMBackendException):
pass
class IDMBackendMissingName(IDMBackendException):
pass
class IDMBackendBase(object):
"""IDMBackendBase class
This class re... |
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
from ipaqe_provision_hosts.errors import IPAQEProvisionerError
class VMsNotCreatedError(IPAQEProvisionerError):
pass
class IDMBackendBase(object):
"""IDMBackendBase class
This class represents a contract between the
idm-... | Replace the exceptions in backend classes | Replace the exceptions in backend classes
| Python | mit | apophys/ipaqe-provision-hosts |
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
+ from ipaqe_provision_hosts.errors import IPAQEProvisionerError
-
- class IDMBackendException(Exception):
- pass
+ class VMsNotCreatedError(IPAQEProvisionerError):
- class VMsNotCreatedError(IDMBackendException):
- pass
-
- ... | Replace the exceptions in backend classes | ## Code Before:
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
class IDMBackendException(Exception):
pass
class VMsNotCreatedError(IDMBackendException):
pass
class IDMBackendMissingName(IDMBackendException):
pass
class IDMBackendBase(object):
"""IDMBackendBase class
... |
NOT_IMPLEMENTED_MSG = "You need to override this method in a subclass"
+ from ipaqe_provision_hosts.errors import IPAQEProvisionerError
-
- class IDMBackendException(Exception):
- pass
+ class VMsNotCreatedError(IPAQEProvisionerError):
- class VMsNotCreatedError(IDMBackendException):
- pass
-
- ... |
1e10fa30998f63359ddd26d9804bd32a837c2cab | armstrong/esi/tests/_utils.py | armstrong/esi/tests/_utils.py | from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
| from django.conf import settings
from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
def with_fake_request(func):
def inner(self, *args, **kwargs):
request = fudge.Fake(HttpRequest)
fudge.clear_calls()
result = func(self, request, *args, **kw... | Add in a decorator for generating fake request objects for test cases | Add in a decorator for generating fake request objects for test cases
| Python | bsd-3-clause | armstrong/armstrong.esi | from django.conf import settings
+ from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
+
+ def with_fake_request(func):
+ def inner(self, *args, **kwargs):
+ request = fudge.Fake(HttpRequest)
+ fudge.clear_calls()
+
+ result = func(self... | Add in a decorator for generating fake request objects for test cases | ## Code Before:
from django.conf import settings
from django.test import TestCase as DjangoTestCase
import fudge
class TestCase(DjangoTestCase):
def setUp(self):
self._original_settings = settings
def tearDown(self):
settings = self._original_settings
## Instruction:
Add in a decorator for g... | from django.conf import settings
+ from django.http import HttpRequest
from django.test import TestCase as DjangoTestCase
import fudge
+
+ def with_fake_request(func):
+ def inner(self, *args, **kwargs):
+ request = fudge.Fake(HttpRequest)
+ fudge.clear_calls()
+
+ result = func(self... |
924bee7b0a8b11aa0f1506584966533924d29478 | django_hash_filter/templatetags/hash_filter.py | django_hash_filter/templatetags/hash_filter.py | from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, arg):
"""
Return... | from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, arg):
"""
Return... | Add helpful text to template error | Add helpful text to template error | Python | mit | andrewjsledge/django-hash-filter | from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, ar... | Add helpful text to template error | ## Code Before:
from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, arg):
... | from django import template
from django.template.defaultfilters import stringfilter
from django.template.base import TemplateSyntaxError
import hashlib
from django_hash_filter.templatetags import get_available_hashes
register = template.Library()
@register.filter
@stringfilter
def hash(value, ar... |
3d570864a39f10d6e502e4005e7931793fca3d01 | flask_app/models.py | flask_app/models.py | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')))
class Role(... | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id', ondelete='CASCADE')),
db.Column('role_i... | Add missing cascade deletes on user/roles | Add missing cascade deletes on user/roles
| Python | mit | getslash/mailboxer,vmalloc/mailboxer,Infinidat/lanister,vmalloc/mailboxer,getslash/mailboxer,Infinidat/lanister,vmalloc/mailboxer,getslash/mailboxer | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
- db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
+ db.Column('user_id', db.Integer(), d... | Add missing cascade deletes on user/roles | ## Code Before:
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id')... | from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.security import UserMixin, RoleMixin
db = SQLAlchemy()
### Add models here
roles_users = db.Table('roles_users',
- db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
+ db.Column('user_id', db.Integer(), d... |
cd996486b25ab35369994a4470f795ae31e06a9c | unit_tests/test_ccs.py | unit_tests/test_ccs.py |
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_nothing(self):
pass
if __name__ =... |
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_parse_line(self):
with open('data/... | Add first test for ccs | Add first test for ccs
| Python | mit | ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData,ewels/MultiQC_TestData |
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
- def test_nothing(self):
+... | Add first test for ccs | ## Code Before:
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
def test_nothing(self):
pas... |
import unittest
import sys
# This line allows the tests to run if you just naively run this script.
# But the preferred way is to use run_tests.sh
sys.path.insert(0,'../MultiQC')
from multiqc.modules.ccs.ccs import parse_ccs_log
class Test(unittest.TestCase):
- def test_nothing(self):
?... |
6e583085ac056b7df2b29a94cd6743493c151684 | subjectivity_clues/clues.py | subjectivity_clues/clues.py | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmethod
def read_a... | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
PRIORPOLARITY = {
'positive': 1,
'negative': -1,
'both': 0,
'neutral': 0
}
TYPE = {
'strongsubj': 2,
'weaksubj'... | Add calculation to the lexicon | Add calculation to the lexicon
| Python | apache-2.0 | chuajiesheng/twitter-sentiment-analysis | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
+
+ PRIORPOLARITY = {
+ 'positive': 1,
+ 'negative': -1,
+ 'both': 0,
+ 'neutral': 0
+ }
+
+ TYPE = {
+ 'st... | Add calculation to the lexicon | ## Code Before:
import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
def __init__(self, filename=DEFAULT_FILENAME):
lines = self.read_all(filename)
self.lexicons = self.parse_clues(lines)
@staticmetho... | import os
import shlex
class Clues:
DEFAULT_FILENAME = os.getcwd() + os.sep + 'subjectivity_clues' + os.sep + 'subjclueslen1-HLTEMNLP05.tff'
+
+ PRIORPOLARITY = {
+ 'positive': 1,
+ 'negative': -1,
+ 'both': 0,
+ 'neutral': 0
+ }
+
+ TYPE = {
+ 'st... |
bf961cf69386404b03d46ebc3ab34b7da804f016 | test/test_ttt.py | test/test_ttt.py |
import unittest
from ttt import ttt
class TestPat(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_000_something(self):
pass
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
|
class Test:
def setup(self):
pass
def teardown(self):
pass
def test_(self):
pass
| Use pytest instead of unittest | Use pytest instead of unittest
| Python | isc | yerejm/ttt,yerejm/ttt |
+ class Test:
- import unittest
-
- from ttt import ttt
-
-
- class TestPat(unittest.TestCase):
-
- def setUp(self):
+ def setup(self):
pass
- def tearDown(self):
+ def teardown(self):
pass
- def test_000_something(self):
+ def test_(self):
pass
-... | Use pytest instead of unittest | ## Code Before:
import unittest
from ttt import ttt
class TestPat(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_000_something(self):
pass
if __name__ == '__main__':
import sys
sys.exit(unittest.main())
## Instruction:
Use pytest instead... |
+ class Test:
- import unittest
-
- from ttt import ttt
-
-
- class TestPat(unittest.TestCase):
-
- def setUp(self):
? ^
+ def setup(self):
? ^
pass
- def tearDown(self):
? ^
+ def teardown(self):
? ^
pass
- def test_... |
ad6b7fe871be502220de5bcb6c2a65f4e7999294 | etcd3/client.py | etcd3/client.py | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc... | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.kvstub = etcdrpc... | Add compact and delete stubs | Add compact and delete stubs
| Python | apache-2.0 | kragniz/python-etcd3 | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
... | Add compact and delete stubs | ## Code Before:
import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
self.... | import grpc
from etcd3.etcdrpc import rpc_pb2 as etcdrpc
import etcd3.exceptions as exceptions
class Etcd3Client(object):
def __init__(self, host='localhost', port=2379):
self.channel = grpc.insecure_channel('{host}:{port}'.format(
host=host, port=port)
)
... |
4f4c3fabe1ccb91ca8f510a6ab81b6f2eb588c17 | openstack/tests/functional/telemetry/v2/test_statistics.py | openstack/tests/functional/telemetry/v2/test_statistics.py |
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
found_something = False
for met in self.conn... |
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
for met in self.conn.telemetry.meters():
... | Fix the telemetry statistics test | Fix the telemetry statistics test
This test worked fine on devstack, but failed on the test gate
because not all meters have statistics. Look for a meter with
statistics.
Partial-bug: #1665495
Change-Id: Ife0f1f11c70e926801b48000dd0b4e9d863a865f
| Python | apache-2.0 | briancurtin/python-openstacksdk,dtroyer/python-openstacksdk,dtroyer/python-openstacksdk,openstack/python-openstacksdk,openstack/python-openstacksdk,briancurtin/python-openstacksdk,stackforge/python-openstacksdk,stackforge/python-openstacksdk |
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
- found_something = False
... | Fix the telemetry statistics test | ## Code Before:
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
found_something = False
for ... |
import unittest
from openstack.tests.functional import base
@unittest.skipUnless(base.service_exists(service_type="metering"),
"Metering service does not exist")
class TestStatistics(base.BaseFunctionalTest):
def test_list(self):
- found_something = False
... |
073dd8529c95f44d7d250508dd10b8ffc8208926 | two_factor/migrations/0003_auto_20150817_1733.py | two_factor/migrations/0003_auto_20150817_1733.py | from __future__ import unicode_literals
from django.db import models, migrations
import two_factor.models
class Migration(migrations.Migration):
dependencies = [
('two_factor', '0002_auto_20150110_0810'),
]
operations = [
migrations.AlterField(
model_name='phonedevice',
... | from __future__ import unicode_literals
import logging
from django.db import models, migrations
import phonenumbers
import two_factor.models
logger = logging.getLogger(__name__)
def migrate_phone_numbers(apps, schema_editor):
PhoneDevice = apps.get_model("two_factor", "PhoneDevice")
for device in PhoneDevic... | Migrate phone numbers to E.164 format | Migrate phone numbers to E.164 format
| Python | mit | koleror/django-two-factor-auth,Bouke/django-two-factor-auth,koleror/django-two-factor-auth,Bouke/django-two-factor-auth | from __future__ import unicode_literals
+ import logging
from django.db import models, migrations
+ import phonenumbers
import two_factor.models
+
+ logger = logging.getLogger(__name__)
+
+
+ def migrate_phone_numbers(apps, schema_editor):
+ PhoneDevice = apps.get_model("two_factor", "PhoneDevice")
+ ... | Migrate phone numbers to E.164 format | ## Code Before:
from __future__ import unicode_literals
from django.db import models, migrations
import two_factor.models
class Migration(migrations.Migration):
dependencies = [
('two_factor', '0002_auto_20150110_0810'),
]
operations = [
migrations.AlterField(
model_name='ph... | from __future__ import unicode_literals
+ import logging
from django.db import models, migrations
+ import phonenumbers
import two_factor.models
+
+ logger = logging.getLogger(__name__)
+
+
+ def migrate_phone_numbers(apps, schema_editor):
+ PhoneDevice = apps.get_model("two_factor", "PhoneDevice")
+ ... |
25b84238204d3970c72d0ac133b0ff59ae4696bd | social/models.py | social/models.py | from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
password = models.TextField()
join_date = models.DateField('date joined')
def __str__(self):
return self.display_name... | from django.contrib.auth.models import AbstractBaseUser
from django.db import models
# Create your models here.
class User(AbstractBaseUser):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
join_date = models.DateField('date joined')
USERNAME_FIELD = 'usernam... | Implement User that extends Django's AbstractBaseUser. | Implement User that extends Django's AbstractBaseUser.
| Python | mit | eyohansa/temu,eyohansa/temu,eyohansa/temu | + from django.contrib.auth.models import AbstractBaseUser
from django.db import models
# Create your models here.
- class User(models.Model):
+ class User(AbstractBaseUser):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
- password = models.TextField(... | Implement User that extends Django's AbstractBaseUser. | ## Code Before:
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
password = models.TextField()
join_date = models.DateField('date joined')
def __str__(self):
return s... | + from django.contrib.auth.models import AbstractBaseUser
from django.db import models
# Create your models here.
- class User(models.Model):
+ class User(AbstractBaseUser):
username = models.CharField(max_length=20)
display_name = models.CharField(max_length=30)
- password = models.TextField(... |
fe34a904af1d691f96b19c87ee11129eecb09dc5 | byceps/blueprints/snippet_admin/service.py | byceps/blueprints/snippet_admin/service.py |
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_i... |
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_counts_by_party_i... | Handle values to be compared being `None`. | Handle values to be compared being `None`.
| Python | bsd-3-clause | m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps,m-ober/byceps |
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _g... | Handle values to be compared being `None`. | ## Code Before:
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _get_snippet_c... |
from difflib import HtmlDiff
from ...database import db
from ..party.models import Party
from ..snippet.models.snippet import Snippet
def get_parties_with_snippet_counts():
"""Yield (party, snippet count) pairs."""
parties = Party.query.all()
snippet_counts_by_party_id = _g... |
ab2d1296dd189016daa8012fc80d821d1b71486c | telephony/radio_station.py | telephony/radio_station.py | import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time.sleep(1)
return
... | import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time.sleep(1)
return
... | Fix no id property for RadioStation | Fix no id property for RadioStation
| Python | agpl-3.0 | rootio/rootio_web,rootio/rootio_web,rootio/rootio_web,rootio/rootio_web | import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time... | Fix no id property for RadioStation | ## Code Before:
import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time.sleep(1)
... | import time
from rootio.radio.models import Station
from call_handler import CallHandler
from program_handler import ProgramHandler
from community_menu import CommunityMenu
class RadioStation:
def run(self):
self.__program_handler.run()
while True:
time... |
3129d72151d81d8745a8e81ab4940dcd56a67b66 | scripts/get-translator-credits.py | scripts/get-translator-credits.py | import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract locale string f... | import subprocess
import re
from collections import defaultdict
from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
... | Sort languages by English name | Sort languages by English name
| Python | bsd-3-clause | zerolab/wagtail,thenewguy/wagtail,timorieber/wagtail,kaedroho/wagtail,kurtrwall/wagtail,nilnvoid/wagtail,nutztherookie/wagtail,kurtw/wagtail,nimasmi/wagtail,torchbox/wagtail,zerolab/wagtail,timorieber/wagtail,FlipperPA/wagtail,rsalmaso/wagtail,zerolab/wagtail,kaedroho/wagtail,mixxorz/wagtail,mikedingjan/wagtail,rsalmas... | import subprocess
import re
from collections import defaultdict
+
+ from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_l... | Sort languages by English name | ## Code Before:
import subprocess
import re
from collections import defaultdict
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_listing_line.strip()
# extract... | import subprocess
import re
from collections import defaultdict
+
+ from babel import Locale
authors_by_locale = defaultdict(set)
file_listing = subprocess.Popen('find ../wagtail -iname *.po', shell=True, stdout=subprocess.PIPE)
for file_listing_line in file_listing.stdout:
filename = file_l... |
2dc90659a7265740bb5821f0f153f00de1b2205a | pydle/features/__init__.py | pydle/features/__init__.py | from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3
from .rfc1459 import RFC1459Support
from .account import AccountSupport
from .ctcp import CTCPSupport
from .tls import TLSSupport
from .isupport import ISUPPORTSupport
from .whox import WHOXSupport
from .ircv3 import IRCv3Support, IRCv3_1Support, IRCv3_2... | from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3
from .rfc1459 import RFC1459Support
from .account import AccountSupport
from .ctcp import CTCPSupport
from .tls import TLSSupport
from .isupport import ISUPPORTSupport
from .whox import WHOXSupport
from .ircv3 import IRCv3Support, IRCv3_1Support, IRCv3_2... | Enable RplWhoisHostSupport implementation (as part of full featured client) | Enable RplWhoisHostSupport implementation (as part of full featured client)
| Python | bsd-3-clause | Shizmob/pydle | from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3
from .rfc1459 import RFC1459Support
from .account import AccountSupport
from .ctcp import CTCPSupport
from .tls import TLSSupport
from .isupport import ISUPPORTSupport
from .whox import WHOXSupport
from .ircv3 import IRCv3Support, IRCv3... | Enable RplWhoisHostSupport implementation (as part of full featured client) | ## Code Before:
from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3
from .rfc1459 import RFC1459Support
from .account import AccountSupport
from .ctcp import CTCPSupport
from .tls import TLSSupport
from .isupport import ISUPPORTSupport
from .whox import WHOXSupport
from .ircv3 import IRCv3Support, IRCv3_1... | from . import rfc1459, account, ctcp, tls, isupport, whox, ircv3
from .rfc1459 import RFC1459Support
from .account import AccountSupport
from .ctcp import CTCPSupport
from .tls import TLSSupport
from .isupport import ISUPPORTSupport
from .whox import WHOXSupport
from .ircv3 import IRCv3Support, IRCv3... |
786903e417c7dfd8773db10fcc7cd5fa1130272a | candidates/tests/test_caching.py | candidates/tests/test_caching.py | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def test_unauth_user_cache_heade... | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def test_unauth_user_cache_heade... | Make a test of multiple header values insensitve to their order | Make a test of multiple header values insensitve to their order
This test sometimes failed on Python 3 because the values in the header
were ordered differently - splitting them and comparing as a set should
fix that.
| Python | agpl-3.0 | DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def ... | Make a test of multiple header values insensitve to their order | ## Code Before:
from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def test_unauth_... | from __future__ import unicode_literals
from django_webtest import WebTest
from .auth import TestUserMixin
from .uk_examples import UK2015ExamplesMixin
class TestCaching(TestUserMixin, UK2015ExamplesMixin, WebTest):
def setUp(self):
super(TestCaching, self).setUp()
def ... |
ed09ed41e2b9486f55f801eee47f08e2a9679b6c | tests/sequence/test_alignment.py | tests/sequence/test_alignment.py | import unittest
from unittest import mock
from io import StringIO
from cref.sequence.alignment import Blast
class AlignmentTestCase(unittest.TestCase):
def test_blast_local(self):
blast = Blast('data/blastdb/pdbseqres')
results = blast.align('AASSF')
pdbs = {result.pdb_code for result in ... | import unittest
from unittest import mock
from io import StringIO
from cref.sequence.alignment import Blast
class AlignmentTestCase(unittest.TestCase):
def test_blast_local(self):
blast = Blast('data/blastdb/pdbseqres')
results = blast.align('AASSF')
pdbs = {result.pdb_code for result in ... | Fix broken test after blast web removal | Fix broken test after blast web removal
| Python | mit | mchelem/cref2,mchelem/cref2,mchelem/cref2 | import unittest
from unittest import mock
from io import StringIO
from cref.sequence.alignment import Blast
class AlignmentTestCase(unittest.TestCase):
def test_blast_local(self):
blast = Blast('data/blastdb/pdbseqres')
results = blast.align('AASSF')
pdbs = {result... | Fix broken test after blast web removal | ## Code Before:
import unittest
from unittest import mock
from io import StringIO
from cref.sequence.alignment import Blast
class AlignmentTestCase(unittest.TestCase):
def test_blast_local(self):
blast = Blast('data/blastdb/pdbseqres')
results = blast.align('AASSF')
pdbs = {result.pdb_cod... | import unittest
from unittest import mock
from io import StringIO
from cref.sequence.alignment import Blast
class AlignmentTestCase(unittest.TestCase):
def test_blast_local(self):
blast = Blast('data/blastdb/pdbseqres')
results = blast.align('AASSF')
pdbs = {result... |
9f3356d06067dbcc77a79afee6bccf80600dab28 | server/systeminfo.py | server/systeminfo.py | import subprocess
def get_uptime():
""" Return the uptime of the system as a str using the command: $ uptime
"""
proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True)
(output, error) = proc.communicate()
uptime = output.decode("utf-8").split(",")[0]
uptime = uptime[uptime.find... | import subprocess
from datetime import timedelta
def get_uptime():
""" Return the uptime of the system as a timedelta object.
"""
proc = subprocess.Popen(["cat /proc/uptime"],
stdout=subprocess.PIPE, shell=True)
(output, error) = proc.communicate()
uptime = int(output.de... | Add a method to get the idle time. Also data are directly readed in /proc/uptime. | Add a method to get the idle time. Also data are directly readed in /proc/uptime.
| Python | mit | juliendelplanque/raspirestmonitor | import subprocess
+ from datetime import timedelta
def get_uptime():
- """ Return the uptime of the system as a str using the command: $ uptime
+ """ Return the uptime of the system as a timedelta object.
"""
- proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True)
+ proc =... | Add a method to get the idle time. Also data are directly readed in /proc/uptime. | ## Code Before:
import subprocess
def get_uptime():
""" Return the uptime of the system as a str using the command: $ uptime
"""
proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True)
(output, error) = proc.communicate()
uptime = output.decode("utf-8").split(",")[0]
uptime = up... | import subprocess
+ from datetime import timedelta
def get_uptime():
- """ Return the uptime of the system as a str using the command: $ uptime
+ """ Return the uptime of the system as a timedelta object.
"""
- proc = subprocess.Popen(["uptime"], stdout=subprocess.PIPE, shell=True)
+ proc =... |
4858a17940ec4b4425f743813c0c1ecef391d967 | tests/test_file_handling.py | tests/test_file_handling.py | import os
from format_sql.file_handling import format_file, load_from_file, main
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
filename = g... | import os
import sys
from format_sql.file_handling import format_file, load_from_file, main
try:
from unittest.mock import patch
except ImportError:
from mock import patch
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(tes... | Add test for file iteration | Add test for file iteration
| Python | bsd-2-clause | paetzke/format-sql | import os
+ import sys
from format_sql.file_handling import format_file, load_from_file, main
+
+ try:
+ from unittest.mock import patch
+ except ImportError:
+ from mock import patch
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
... | Add test for file iteration | ## Code Before:
import os
from format_sql.file_handling import format_file, load_from_file, main
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
filename = os.path.join(test_data, 'tests/data', filename)
return filename
def test_format_empty_file():
... | import os
+ import sys
from format_sql.file_handling import format_file, load_from_file, main
+
+ try:
+ from unittest.mock import patch
+ except ImportError:
+ from mock import patch
def get_test_file(filename):
test_data = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
... |
ded0d2ced823deeabf860abd9ec5120165ed7fde | djoser/utils.py | djoser/utils.py | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(force_bytes(pk)).de... | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(force_bytes(pk)).de... | Add **kwargs to ActionViewmixin.post() handler | Add **kwargs to ActionViewmixin.post() handler
Details: #359
| Python | mit | sunscrapers/djoser,sunscrapers/djoser,sunscrapers/djoser | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(f... | Add **kwargs to ActionViewmixin.post() handler | ## Code Before:
from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(for... | from django.contrib.auth import user_logged_in, user_logged_out, login, logout
from django.utils.encoding import force_bytes, force_text
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
from djoser.conf import settings
def encode_uid(pk):
return urlsafe_base64_encode(f... |
98190f0e96b2e2880e81b4801ebd5b04c1e9f1d8 | geomdl/__init__.py | geomdl/__init__.py |
__version__ = "3.0.0"
|
__version__ = "3.0.0"
# Fixes "from geomdl import *" but this is not considered as a good practice
# @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package
__all__ = ["BSpline.Curve",
"BSpline.Curve2D",
"BSpline.Surface",
"NURBS.Curve",
"NURBS.Curve2... | Fix importing * (star) from package | Fix importing * (star) from package
| Python | mit | orbingol/NURBS-Python,orbingol/NURBS-Python |
__version__ = "3.0.0"
+ # Fixes "from geomdl import *" but this is not considered as a good practice
+ # @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package
+ __all__ = ["BSpline.Curve",
+ "BSpline.Curve2D",
+ "BSpline.Surface",
+ "NURBS.Curve",
+ ... | Fix importing * (star) from package | ## Code Before:
__version__ = "3.0.0"
## Instruction:
Fix importing * (star) from package
## Code After:
__version__ = "3.0.0"
# Fixes "from geomdl import *" but this is not considered as a good practice
# @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package
__all__ = ["BSpline.Curve",
... |
__version__ = "3.0.0"
+
+ # Fixes "from geomdl import *" but this is not considered as a good practice
+ # @see: https://docs.python.org/3/tutorial/modules.html#importing-from-a-package
+ __all__ = ["BSpline.Curve",
+ "BSpline.Curve2D",
+ "BSpline.Surface",
+ "NURBS.Curve",
+ ... |
8ebec493b086525d23bbe4110c9d277c9b9b8301 | src/sentry/tsdb/dummy.py | src/sentry/tsdb/dummy.py | from __future__ import absolute_import
from sentry.tsdb.base import BaseTSDB
class DummyTSDB(BaseTSDB):
"""
A no-op time-series storage.
"""
def incr(self, model, key, timestamp=None, count=1):
pass
def get_range(self, model, keys, start, end, rollup=None):
return dict((k, []) fo... | from __future__ import absolute_import
from sentry.tsdb.base import BaseTSDB
class DummyTSDB(BaseTSDB):
"""
A no-op time-series storage.
"""
def incr(self, model, key, timestamp=None, count=1):
pass
def get_range(self, model, keys, start, end, rollup=None):
return dict((k, []) fo... | Add support for DummyTSDB backend. | Add support for DummyTSDB backend.
| Python | bsd-3-clause | daevaorn/sentry,gencer/sentry,mvaled/sentry,BuildingLink/sentry,daevaorn/sentry,beeftornado/sentry,jean/sentry,JackDanger/sentry,JamesMura/sentry,zenefits/sentry,jean/sentry,jean/sentry,ifduyue/sentry,mvaled/sentry,gencer/sentry,BayanGroup/sentry,imankulov/sentry,nicholasserra/sentry,JamesMura/sentry,beeftornado/sentry... | from __future__ import absolute_import
from sentry.tsdb.base import BaseTSDB
class DummyTSDB(BaseTSDB):
"""
A no-op time-series storage.
"""
def incr(self, model, key, timestamp=None, count=1):
pass
def get_range(self, model, keys, start, end, rollup=None):
... | Add support for DummyTSDB backend. | ## Code Before:
from __future__ import absolute_import
from sentry.tsdb.base import BaseTSDB
class DummyTSDB(BaseTSDB):
"""
A no-op time-series storage.
"""
def incr(self, model, key, timestamp=None, count=1):
pass
def get_range(self, model, keys, start, end, rollup=None):
return... | from __future__ import absolute_import
from sentry.tsdb.base import BaseTSDB
class DummyTSDB(BaseTSDB):
"""
A no-op time-series storage.
"""
def incr(self, model, key, timestamp=None, count=1):
pass
def get_range(self, model, keys, start, end, rollup=None):
... |
7ad0aa082114811a1638916060c6b18f93d09824 | books/services.py | books/services.py | from datetime import date
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = date(today.year, today.month, 1)
qs = Transaction.objects.filter(created__gte=first_day_of_a_month)... | from datetime import datetime
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = datetime(today.year, today.month, 1,
tzinfo=today.tzinfo)
q... | Add service functions to get transactions by time | Add service functions to get transactions by time
| Python | mit | trimailov/finance,trimailov/finance,trimailov/finance | - from datetime import date
+ from datetime import datetime
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
- first_day_of_a_month = date(today.year, today.month, 1)
+ first_day_... | Add service functions to get transactions by time | ## Code Before:
from datetime import date
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
first_day_of_a_month = date(today.year, today.month, 1)
qs = Transaction.objects.filter(created__gte=first... | - from datetime import date
+ from datetime import datetime
? ++++
from datetime import timedelta
from django.utils import timezone
from books.models import Transaction
def get_months_transactions():
today = timezone.now()
- first_day_of_a_month = date(today.year,... |
6c6e8d17bce3976a2ef766139f3692a78df2d0c4 | tests/unit/cloud/clouds/test_saltify.py | tests/unit/cloud/clouds/test_saltify.py | '''
:codeauthor: :email:`Alexander Schwartz <alexander.schwartz@gmx.net>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase
from tests.support.mock import MagicMock
# Import Salt Libs
from salt.cloud.clouds import saltify
# Globals... | '''
:codeauthor: :email:`Alexander Schwartz <alexander.schwartz@gmx.net>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase
from tests.support.mock import (
MagicMock,
patch
)
# Import Salt Libs
from salt.cloud.clouds import... | Update unit test for Saltify with credential verification | Update unit test for Saltify with credential verification
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | '''
:codeauthor: :email:`Alexander Schwartz <alexander.schwartz@gmx.net>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase
- from tests.support.mock import MagicMock
+ from tests.support.mock import (
+ MagicMo... | Update unit test for Saltify with credential verification | ## Code Before:
'''
:codeauthor: :email:`Alexander Schwartz <alexander.schwartz@gmx.net>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase
from tests.support.mock import MagicMock
# Import Salt Libs
from salt.cloud.clouds import sa... | '''
:codeauthor: :email:`Alexander Schwartz <alexander.schwartz@gmx.net>`
'''
# Import Python libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.unit import TestCase
- from tests.support.mock import MagicMock
? ^^^^^^^^^
+ fr... |
8ad4627973db344e228a9170aef030ab58efdeb9 | src/ggrc/converters/__init__.py | src/ggrc/converters/__init__.py |
from ggrc.converters.sections import SectionsConverter
all_converters = [('sections', SectionsConverter)]
HANDLERS = {}
def get_converter(name):
return all_converters(name)
|
from ggrc.converters.sections import SectionsConverter
from ggrc.models import (
Audit, Control, ControlAssessment, DataAsset, Directive, Contract,
Policy, Regulation, Standard, Facility, Market, Objective, Option,
OrgGroup, Vendor, Person, Product, Program, Project, Request, Response,
Section, Clause,... | Add column order and importable objects lists | Add column order and importable objects lists
| Python | apache-2.0 | edofic/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,NejcZupec/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,jmakov/ggrc-core,VinnieJohns/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,hyperNURb/ggrc-... |
from ggrc.converters.sections import SectionsConverter
+ from ggrc.models import (
+ Audit, Control, ControlAssessment, DataAsset, Directive, Contract,
+ Policy, Regulation, Standard, Facility, Market, Objective, Option,
+ OrgGroup, Vendor, Person, Product, Program, Project, Request, Response,
+ Se... | Add column order and importable objects lists | ## Code Before:
from ggrc.converters.sections import SectionsConverter
all_converters = [('sections', SectionsConverter)]
HANDLERS = {}
def get_converter(name):
return all_converters(name)
## Instruction:
Add column order and importable objects lists
## Code After:
from ggrc.converters.sections import SectionsC... |
from ggrc.converters.sections import SectionsConverter
+ from ggrc.models import (
+ Audit, Control, ControlAssessment, DataAsset, Directive, Contract,
+ Policy, Regulation, Standard, Facility, Market, Objective, Option,
+ OrgGroup, Vendor, Person, Product, Program, Project, Request, Response,
+ Se... |
c4f0f13892f1a1af73a94e6cbea95d30e676203c | xorgauth/accounts/views.py | xorgauth/accounts/views.py | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_conse... | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_required
def list_conse... | Fix access restriction to /accounts/profile/ | Fix access restriction to /accounts/profile/
LoginRequiredMixin needs to come first for it to be applied. Otherwise,
/accounts/profile/ is accessible even when the user is not
authenticated.
| Python | agpl-3.0 | Polytechnique-org/xorgauth,Polytechnique-org/xorgauth | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_req... | Fix access restriction to /accounts/profile/ | ## Code Before:
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_require... | from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import render
from django.views.generic import TemplateView
from oidc_provider.models import UserConsent, Client
@login_req... |
101784851bf8c7add95bba7dbb4277114b7a3098 | refugeedata/mailings/tasks.py | refugeedata/mailings/tasks.py | from django_rq import job
from .. import utils
@job
def send_sms(to, body):
utils.send_sms(to=to, body=body)
| from django_rq import job
from .. import utils
@job
def send_sms(to, body):
for number in to:
send_single_sms.delay([to], body)
@job
def send_single_sms(to, body):
utils.send_sms(to=to, body=body)
| Split SMS sending into multiple jobs (to get around Heroku timeout) | Split SMS sending into multiple jobs (to get around Heroku timeout)
| Python | mit | ukch/refugeedata,ukch/refugeedata,ukch/refugeedata,ukch/refugeedata | from django_rq import job
from .. import utils
@job
def send_sms(to, body):
+ for number in to:
+ send_single_sms.delay([to], body)
+
+
+ @job
+ def send_single_sms(to, body):
utils.send_sms(to=to, body=body)
| Split SMS sending into multiple jobs (to get around Heroku timeout) | ## Code Before:
from django_rq import job
from .. import utils
@job
def send_sms(to, body):
utils.send_sms(to=to, body=body)
## Instruction:
Split SMS sending into multiple jobs (to get around Heroku timeout)
## Code After:
from django_rq import job
from .. import utils
@job
def send_sms(to, body):
for n... | from django_rq import job
from .. import utils
@job
def send_sms(to, body):
+ for number in to:
+ send_single_sms.delay([to], body)
+
+
+ @job
+ def send_single_sms(to, body):
utils.send_sms(to=to, body=body) |
0a907442eee18d0b30ca4ad2c6a5ef1fabb90684 | pelicanconf.py | pelicanconf.py | from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed generation is usually not desired ... | from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed generation is usually not desired ... | Support static files via new Pelican API | Support static files via new Pelican API
| Python | mit | lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io,lextoumbourou/lextoumbourou.github.io | from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed genera... | Support static files via new Pelican API | ## Code Before:
from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed generation is usua... | from __future__ import unicode_literals
AUTHOR = u'Lex Toumbourou'
SITENAME = u'LexToumbourou.com'
SITEURL = 'http://lextoumbourou.com'
TIMEZONE = 'Australia/Melbourne'
DEFAULT_LANG = u'en'
ARTICLE_URL = 'blog/posts/{slug}/'
ARTICLE_SAVE_AS = 'blog/posts/{slug}/index.html'
# Feed genera... |
3373521f43b0d605bba6cc36b190c064d5a0303e | kytos/core/link.py | kytos/core/link.py |
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b = endpoint_b
... |
import json
from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.en... | Define Link ID as UUID | Define Link ID as UUID
| Python | mit | kytos/kyco,kytos/kytos,renanrodrigo/kytos,macartur/kytos |
import json
+
+ from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a ... | Define Link ID as UUID | ## Code Before:
import json
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a = endpoint_a
self.endpoint_b... |
import json
+
+ from uuid import uuid4
from kytos.core.common import GenericEntity
class Link(GenericEntity):
"""Define a link between two Endpoints."""
def __init__(self, endpoint_a, endpoint_b):
"""Create a Link instance and set its attributes."""
self.endpoint_a ... |
e82ed9fcaa6745f849dfb65968ed44da30f6065b | src/plugins/spikeProbability.py | src/plugins/spikeProbability.py |
SpikeDB.plotClear()
files = SpikeDB.getFiles(True)
for f in files:
means = []
err = []
x = []
raw = []
for t in f['trials']:
count = []
x.append(t['xvalue'])
for p in t['passes']:
if len(p) > 0:
count.append(1)
else:
count.append(0)
means.append(SpikeDB.mean(count))
err.append(SpikeDB.std... |
SpikeDB.plotClear()
files = SpikeDB.getFiles(True)
for f in files:
means = []
err = []
x = []
raw = []
for t in f['trials']:
count = []
x.append(t['xvalue'])
for p in t['passes']:
if len(p) > 0:
count.append(1)
else:
count.append(0)
means.append(SpikeDB.mean(count))
err.append(SpikeDB.std... | Add line to spike prob | Add line to spike prob
| Python | bsd-3-clause | baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB,baubie/SpikeDB |
SpikeDB.plotClear()
files = SpikeDB.getFiles(True)
for f in files:
means = []
err = []
x = []
raw = []
for t in f['trials']:
count = []
x.append(t['xvalue'])
for p in t['passes']:
if len(p) > 0:
count.append(1)
else:
count.append(0)
means.append(SpikeDB.mea... | Add line to spike prob | ## Code Before:
SpikeDB.plotClear()
files = SpikeDB.getFiles(True)
for f in files:
means = []
err = []
x = []
raw = []
for t in f['trials']:
count = []
x.append(t['xvalue'])
for p in t['passes']:
if len(p) > 0:
count.append(1)
else:
count.append(0)
means.append(SpikeDB.mean(count))
err.ap... |
SpikeDB.plotClear()
files = SpikeDB.getFiles(True)
for f in files:
means = []
err = []
x = []
raw = []
for t in f['trials']:
count = []
x.append(t['xvalue'])
for p in t['passes']:
if len(p) > 0:
count.append(1)
else:
count.append(0)
means.append(SpikeDB.mea... |
e2c9d39dd30a60c5c54521d7d11773430cae1bd1 | tests/test_image_access.py | tests/test_image_access.py | import pytest
import imghdr
from io import BytesIO
from PIL import Image
from pikepdf import _qpdf as qpdf
def test_jpeg(resources, outdir):
pdf = qpdf.Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pdf.pag... | import pytest
import imghdr
from io import BytesIO
from PIL import Image
import zlib
from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
pdf = Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pdfimage = pd... | Add manual experiment that replaces a RGB image with grayscale | Add manual experiment that replaces a RGB image with grayscale
| Python | mpl-2.0 | pikepdf/pikepdf,pikepdf/pikepdf,pikepdf/pikepdf | import pytest
import imghdr
from io import BytesIO
from PIL import Image
+ import zlib
- from pikepdf import _qpdf as qpdf
+ from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
- pdf = qpdf.Pdf.open(resources / 'congress.pdf')
+ pdf = Pdf.open(resources / 'congress.pdf')
#... | Add manual experiment that replaces a RGB image with grayscale | ## Code Before:
import pytest
import imghdr
from io import BytesIO
from PIL import Image
from pikepdf import _qpdf as qpdf
def test_jpeg(resources, outdir):
pdf = qpdf.Pdf.open(resources / 'congress.pdf')
# If you are looking at this as example code, Im0 is not necessarily the
# name of any image.
pd... | import pytest
import imghdr
from io import BytesIO
from PIL import Image
+ import zlib
- from pikepdf import _qpdf as qpdf
+ from pikepdf import Pdf, Object
def test_jpeg(resources, outdir):
- pdf = qpdf.Pdf.open(resources / 'congress.pdf')
? -----
+ pdf = Pdf.open(resources / 'congre... |
cdcb503d3dbc4679a2bda9dd204df18ab334d70c | pyclub/content/forms.py | pyclub/content/forms.py |
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = (
'title',
'body',
'status',
)
|
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = (
'title',
'body',
)
| Remove campo com default do form | Remove campo com default do form
| Python | mit | dvl/pyclub,dvl/pyclub,dvl/pyclub |
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = (
'title',
'body',
- 'status',
)
| Remove campo com default do form | ## Code Before:
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = (
'title',
'body',
'status',
)
## Instruction:
Remove campo com default do form
## Code After:
from django import... |
from django import forms
from . import models
class PostForm(forms.ModelForm):
class Meta:
model = models.Post
fields = (
'title',
'body',
- 'status',
) |
8780d2eb3d7782e7f1e6c23e2e428a72e6bd3dad | server/kcaa/manipulator_util_test.py | server/kcaa/manipulator_util_test.py |
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.ManipulatorManager.in_s... |
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.ManipulatorManager.in_s... | Add a test for one schedule fragment. | Add a test for one schedule fragment.
| Python | apache-2.0 | kcaa/kcaa,kcaa/kcaa,kcaa/kcaa,kcaa/kcaa |
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_... | Add a test for one schedule fragment. | ## Code Before:
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_util.Manipul... |
import pytest
import manipulator_util
class TestManipulatorManager(object):
def pytest_funcarg__manager(self, request):
return manipulator_util.ManipulatorManager(None, {}, 0)
def test_in_schedule_fragment(self):
in_schedule_fragment = (
manipulator_... |
2f44eb65e22672a894cced9c9de8d64f72d0fc39 | pyosmo/algorithm/weighted.py | pyosmo/algorithm/weighted.py | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep:
... | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep:
... | Fix py3.9 check that total weight need to be more than zero | Fix py3.9 check that total weight need to be more than zero
| Python | mit | OPpuolitaival/pyosmo,OPpuolitaival/pyosmo | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestSt... | Fix py3.9 check that total weight need to be more than zero | ## Code Before:
from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestStep]) -... | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestSt... |
671ca30892e3ebeb0a9140f95690853b4b92dc02 | post/views.py | post/views.py | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *... | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra_context(self, *... | Fix reverse since we deprecated post_object_list | Fix reverse since we deprecated post_object_list
| Python | bsd-3-clause | praekelt/jmbo-post,praekelt/jmbo-post | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_e... | Fix reverse since we deprecated post_object_list | ## Code Before:
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_extra... | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from post.models import Post
from jmbo.generic.views import GenericObjectDetail, GenericObjectList
from jmbo.view_modifiers import DefaultViewModifier
class ObjectList(GenericObjectList):
def get_e... |
08167d79efb97a0728564caf96a96b08763ddf60 | bibliopixel/util/importer.py | bibliopixel/util/importer.py | import importlib
def import_symbol(typename):
"""Import a module or typename within a module from its name."""
try:
return importlib.import_module(typename)
except ImportError as e:
parts = typename.split('.')
if len(parts) > 1:
typename = parts.pop()
# Ca... | import importlib
def import_symbol(typename, package=None):
"""Import a module or typename within a module from its name."""
try:
return importlib.import_module(typename, package=package)
except ImportError as e:
parts = typename.split('.')
if len(parts) > 1:
typename ... | Add a package argument to import_symbol. | Add a package argument to import_symbol.
| Python | mit | ManiacalLabs/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel | import importlib
- def import_symbol(typename):
+ def import_symbol(typename, package=None):
"""Import a module or typename within a module from its name."""
try:
- return importlib.import_module(typename)
+ return importlib.import_module(typename, package=package)
except Im... | Add a package argument to import_symbol. | ## Code Before:
import importlib
def import_symbol(typename):
"""Import a module or typename within a module from its name."""
try:
return importlib.import_module(typename)
except ImportError as e:
parts = typename.split('.')
if len(parts) > 1:
typename = parts.pop()
... | import importlib
- def import_symbol(typename):
+ def import_symbol(typename, package=None):
? ++++++++++++++
"""Import a module or typename within a module from its name."""
try:
- return importlib.import_module(typename)
+ return importlib.import_module(t... |
60b039aabb94c1e5a50bb19bb7267a0fd3ceaa86 | mollie/api/objects/list.py | mollie/api/objects/list.py | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __len__(self):
"""Return the count field."""
return int(self['count'])
def get_object_name(self):
r... | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __len__(self):
"""Return the count field."""
return int(self['count'])
def get_object_name(self):
r... | Drop obsoleted support for offset. | Drop obsoleted support for offset.
| Python | bsd-2-clause | mollie/mollie-api-python | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __len__(self):
"""Return the count field."""
return int(self['count'])
def ge... | Drop obsoleted support for offset. | ## Code Before:
from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __len__(self):
"""Return the count field."""
return int(self['count'])
def get_object_name(... | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def __len__(self):
"""Return the count field."""
return int(self['count'])
def ge... |
8c55bdc78b3ae2c52826740ab049a2bab5ca1fdd | src/nodeconductor_saltstack/exchange/extension.py | src/nodeconductor_saltstack/exchange/extension.py | from nodeconductor.core import NodeConductorExtension
class ExchangeExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.exchange'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
| from nodeconductor.core import NodeConductorExtension
class ExchangeExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.exchange'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
@staticmethod
... | Add sync quota task to celerybeat | Add sync quota task to celerybeat
- nc-1009
| Python | mit | opennode/nodeconductor-saltstack | from nodeconductor.core import NodeConductorExtension
class ExchangeExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.exchange'
@staticmethod
def rest_urls():
from .urls import register_in
return regis... | Add sync quota task to celerybeat | ## Code Before:
from nodeconductor.core import NodeConductorExtension
class ExchangeExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.exchange'
@staticmethod
def rest_urls():
from .urls import register_in
return register_in
##... | from nodeconductor.core import NodeConductorExtension
class ExchangeExtension(NodeConductorExtension):
@staticmethod
def django_app():
return 'nodeconductor_saltstack.exchange'
@staticmethod
def rest_urls():
from .urls import register_in
return regis... |
cb4973909ea662abdf718e5a831806dcb0ecc821 | 14B-088/HI/HI_correct_mask_model.py | 14B-088/HI/HI_correct_mask_model.py |
'''
Swap the spatial axes. Swap the spectral and stokes axes.
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
hdu[0].data = hdu[0].data[:, :, :, ::-1]
hdu[0].data = hdu[0].data[:, :, ::-1, :]
hdu.flush()
execfile("~/Dropbox/code_dev... |
'''
\Swap the spectral and stokes axes. Needed due to issue in regridding function
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
execfile("/home/eric/Dropbox/code_development/ewky_scripts/header_swap_axis.py")
hdu[0].header = heade... | Update what's needed to correct mask and model | Update what's needed to correct mask and model
| Python | mit | e-koch/VLA_Lband,e-koch/VLA_Lband |
'''
- Swap the spatial axes. Swap the spectral and stokes axes.
+ \Swap the spectral and stokes axes. Needed due to issue in regridding function
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
- hdu[0].data = h... | Update what's needed to correct mask and model | ## Code Before:
'''
Swap the spatial axes. Swap the spectral and stokes axes.
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
hdu[0].data = hdu[0].data[:, :, :, ::-1]
hdu[0].data = hdu[0].data[:, :, ::-1, :]
hdu.flush()
execfile("~/... |
'''
- Swap the spatial axes. Swap the spectral and stokes axes.
+ \Swap the spectral and stokes axes. Needed due to issue in regridding function
'''
import sys
from astropy.io import fits
hdu = fits.open(sys.argv[1], mode='update')
hdu[0].data = hdu[0].data.swapaxes(0, 1)
- hdu[0].data = h... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.