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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
02363de7bdd7a069243da09248816f3caf38b2e6 | scripts/get-month.py | scripts/get-month.py | import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date... | import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strptime(updated_date... | Update "Active Records" PDF URL | Update "Active Records" PDF URL
| Python | mit | BuzzFeedNews/nics-firearm-background-checks | import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.dateti... | Update "Active Records" PDF URL | ## Code Before:
import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.datetime.strpt... | import pandas as pd
import pdfplumber
import requests
import datetime
import re
from io import BytesIO
def parse_date(pdf):
text = pdf.pages[0].extract_text(x_tolerance=5)
date_pat = r"UPDATED:\s+As of (.+)\n"
updated_date = re.search(date_pat, text).group(1)
d = datetime.dateti... |
f31f17da75557ce45977589d7da0e1b1fd6612dd | niftianon/cli.py | niftianon/cli.py | from __future__ import absolute_import
import click
import niftianon.anonymiser
@click.command()
@click.argument('identifiable_image', type=click.Path(exists=True))
@click.argument('anonymised_image', type=click.Path(exists=False))
def anonymise(identifiable_image, anonymised_image):
niftianon.anonymiser.anonymis... | from __future__ import absolute_import
import click
import niftianon.anonymiser
@click.command()
@click.argument('identifiable_image', type=click.Path(exists=True))
@click.argument('anonymised_image', type=click.Path(exists=False))
def anonymise(identifiable_image, anonymised_image):
"""Anonymise IDENTIFIABLE_IMA... | Add docstring to command line entrypoint function | Add docstring to command line entrypoint function
| Python | mit | jstutters/niftianon | from __future__ import absolute_import
import click
import niftianon.anonymiser
@click.command()
@click.argument('identifiable_image', type=click.Path(exists=True))
@click.argument('anonymised_image', type=click.Path(exists=False))
def anonymise(identifiable_image, anonymised_image):
+ """Anonym... | Add docstring to command line entrypoint function | ## Code Before:
from __future__ import absolute_import
import click
import niftianon.anonymiser
@click.command()
@click.argument('identifiable_image', type=click.Path(exists=True))
@click.argument('anonymised_image', type=click.Path(exists=False))
def anonymise(identifiable_image, anonymised_image):
niftianon.ano... | from __future__ import absolute_import
import click
import niftianon.anonymiser
@click.command()
@click.argument('identifiable_image', type=click.Path(exists=True))
@click.argument('anonymised_image', type=click.Path(exists=False))
def anonymise(identifiable_image, anonymised_image):
+ """Anonym... |
6a717adf087f847ae4a58375170d01adf5ef17de | polyaxon/factories/pipelines.py | polyaxon/factories/pipelines.py | import factory
from factories.factory_projects import ProjectFactory
from factories.factory_users import UserFactory
from pipelines.models import Pipeline, Operation
class PipelineFactory(factory.DjangoModelFactory):
user = factory.SubFactory(UserFactory)
project = factory.SubFactory(ProjectFactory)
cla... | import factory
from factories.factory_projects import ProjectFactory
from factories.factory_users import UserFactory
from pipelines.models import Pipeline, Operation, PipelineRun, OperationRun
class PipelineFactory(factory.DjangoModelFactory):
user = factory.SubFactory(UserFactory)
project = factory.SubFacto... | Add pipeline run and operation run factories | Add pipeline run and operation run factories
| Python | apache-2.0 | polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon | import factory
from factories.factory_projects import ProjectFactory
from factories.factory_users import UserFactory
- from pipelines.models import Pipeline, Operation
+ from pipelines.models import Pipeline, Operation, PipelineRun, OperationRun
class PipelineFactory(factory.DjangoModelFactory):
... | Add pipeline run and operation run factories | ## Code Before:
import factory
from factories.factory_projects import ProjectFactory
from factories.factory_users import UserFactory
from pipelines.models import Pipeline, Operation
class PipelineFactory(factory.DjangoModelFactory):
user = factory.SubFactory(UserFactory)
project = factory.SubFactory(ProjectF... | import factory
from factories.factory_projects import ProjectFactory
from factories.factory_users import UserFactory
- from pipelines.models import Pipeline, Operation
+ from pipelines.models import Pipeline, Operation, PipelineRun, OperationRun
? +++++++++++++++... |
b8bd5fc044d3dd3b273cba4443c771e60036b6c0 | corehq/apps/importer/base.py | corehq/apps/importer/base.py | from corehq.apps.data_interfaces.interfaces import DataInterface
from django.utils.translation import ugettext as _
class ImportCases(DataInterface):
name = _("Import Cases from Excel")
slug = "import_cases"
description = _("Import case data from an external Excel file")
report_template_path = "importe... | from corehq.apps.data_interfaces.interfaces import DataInterface
from django.utils.translation import ugettext_lazy
class ImportCases(DataInterface):
name = ugettext_lazy("Import Cases from Excel")
slug = "import_cases"
description = ugettext_lazy("Import case data from an external Excel file")
report_... | Use lazy translation for importer strings | Use lazy translation for importer strings
| Python | bsd-3-clause | SEL-Columbia/commcare-hq,dimagi/commcare-hq,SEL-Columbia/commcare-hq,gmimano/commcaretest,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,SEL-Columbia/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,gmimano/commcaretest,qedsoftware/commcare-hq,puttarajubr/... | from corehq.apps.data_interfaces.interfaces import DataInterface
- from django.utils.translation import ugettext as _
+ from django.utils.translation import ugettext_lazy
class ImportCases(DataInterface):
- name = _("Import Cases from Excel")
+ name = ugettext_lazy("Import Cases from Excel")
slug =... | Use lazy translation for importer strings | ## Code Before:
from corehq.apps.data_interfaces.interfaces import DataInterface
from django.utils.translation import ugettext as _
class ImportCases(DataInterface):
name = _("Import Cases from Excel")
slug = "import_cases"
description = _("Import case data from an external Excel file")
report_template... | from corehq.apps.data_interfaces.interfaces import DataInterface
- from django.utils.translation import ugettext as _
? ^ ^^^
+ from django.utils.translation import ugettext_lazy
? ^^ ^^
class ImportCases(DataInterface):
... |
8fc6ba648347a48065ab2fb26f940dc92919feeb | bands/__init__.py | bands/__init__.py | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['module_root'], 'static'))
te... | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['module_root'], 'static'))
te... | Implement new python-based menu format | Implement new python-based menu format
| Python | agpl-3.0 | magfest/bands,magfest/bands | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['mo... | Implement new python-based menu format | ## Code Before:
import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['module_root'... | import shutil
from cherrypy.lib.static import serve_file
from uber.common import *
from panels import *
from bands._version import __version__
from bands.config import *
from bands.models import *
import bands.model_checks
import bands.automated_emails
static_overrides(join(bands_config['mo... |
d446a634cf2d903b8f7a7964210017065ffb9b9a | tests/test_xorshift_rand.py | tests/test_xorshift_rand.py |
from __future__ import absolute_import, division
import collections
import unittest
from eval7 import xorshift_rand
class XorshiftRandTestCase(unittest.TestCase):
SAMPLE_COUNT = 1000000
BINS = 1000
DELTA = 125
def check_uniform(self, counter):
expected_count = self.SAMPLE_COUNT / self.BINS... |
from __future__ import absolute_import, division
import collections
import unittest
from eval7 import xorshift_rand
class XorshiftRandTestCase(unittest.TestCase):
SAMPLE_COUNT = 1000000
BINS = 1000
DELTA = 150 # This should give < 1% chance of failure per test
def check_uniform(self, counter):
... | Increase delta to reduce chance of random failure | Increase delta to reduce chance of random failure
Exact chance of failure is more trouble to calculate than I care to go
to, but the the old chance of failure was likely somewhere in the 1-10%
range. The purpose of the test is to detect meaningful non-uniformity,
so false positives should be kept rare.
| Python | mit | JulianAndrews/pyeval7,JulianAndrews/pyeval7 |
from __future__ import absolute_import, division
import collections
import unittest
from eval7 import xorshift_rand
class XorshiftRandTestCase(unittest.TestCase):
SAMPLE_COUNT = 1000000
BINS = 1000
- DELTA = 125
+ DELTA = 150 # This should give < 1% chance of failure per te... | Increase delta to reduce chance of random failure | ## Code Before:
from __future__ import absolute_import, division
import collections
import unittest
from eval7 import xorshift_rand
class XorshiftRandTestCase(unittest.TestCase):
SAMPLE_COUNT = 1000000
BINS = 1000
DELTA = 125
def check_uniform(self, counter):
expected_count = self.SAMPLE_C... |
from __future__ import absolute_import, division
import collections
import unittest
from eval7 import xorshift_rand
class XorshiftRandTestCase(unittest.TestCase):
SAMPLE_COUNT = 1000000
BINS = 1000
- DELTA = 125
+ DELTA = 150 # This should give < 1% chance of failure per te... |
613c01517288ef7d3170dd7ab4dc2d3541a77168 | chainerrl/misc/is_return_code_zero.py | chainerrl/misc/is_return_code_zero.py | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import subprocess
def is_return_code_zero(args):
"""Return true iff the given comma... | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import subprocess
def is_return_code_zero(args):
"""Return true iff the given comma... | Fix ResourceWarning: unclosed file of devnull | Fix ResourceWarning: unclosed file of devnull
| Python | mit | toslunar/chainerrl,toslunar/chainerrl | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import subprocess
def is_return_code_zero(args):
"""Retur... | Fix ResourceWarning: unclosed file of devnull | ## Code Before:
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import subprocess
def is_return_code_zero(args):
"""Return true iff... | from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from future import standard_library
standard_library.install_aliases()
import os
import subprocess
def is_return_code_zero(args):
"""Retur... |
5d762fba65575b11ccbc15a23852d6b2d18b3f05 | examples/qidle/qidle/utils.py | examples/qidle/qidle/utils.py | from glob import glob
import os
import platform
def get_interpreters():
if platform.system().lower() == 'linux':
executables = [os.path.join('/usr/bin/', exe)
for exe in ['python2', 'python3']
if os.path.exists(os.path.join('/usr/bin/', exe))]
else:
... | from glob import glob
import os
import platform
def get_interpreters():
if platform.system().lower() == 'linux':
executables = [os.path.join('/usr/bin/', exe)
for exe in ['python2', 'python3']
if os.path.exists(os.path.join('/usr/bin/', exe))]
else:
... | Fix interpreter detection on windows | Fix interpreter detection on windows
| Python | mit | mmolero/pyqode.python,zwadar/pyqode.python,pyQode/pyqode.python,pyQode/pyqode.python | from glob import glob
import os
import platform
def get_interpreters():
if platform.system().lower() == 'linux':
executables = [os.path.join('/usr/bin/', exe)
for exe in ['python2', 'python3']
if os.path.exists(os.path.join('/usr/bin/', exe... | Fix interpreter detection on windows | ## Code Before:
from glob import glob
import os
import platform
def get_interpreters():
if platform.system().lower() == 'linux':
executables = [os.path.join('/usr/bin/', exe)
for exe in ['python2', 'python3']
if os.path.exists(os.path.join('/usr/bin/', exe))]
... | from glob import glob
import os
import platform
def get_interpreters():
if platform.system().lower() == 'linux':
executables = [os.path.join('/usr/bin/', exe)
for exe in ['python2', 'python3']
if os.path.exists(os.path.join('/usr/bin/', exe... |
550befeed6ff3b2c64454c05f9e05b586d16ff64 | googlevoice/__init__.py | googlevoice/__init__.py | __author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
from .util import P... | __author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
try:
__version__ = (
__import__('pkg_resources').get_distribu... | Load the version from the package metadata. | Load the version from the package metadata.
| Python | bsd-3-clause | pettazz/pygooglevoice | __author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
+
+ try:
- __version__ = '0.5'
+ __version__ = (
+ ... | Load the version from the package metadata. | ## Code Before:
__author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
__version__ = '0.5'
from .voice import Voice
fro... | __author__ = 'Justin Quick and Joe McCall'
__email__ = 'justquick@gmail.com, joe@mcc4ll.us',
__copyright__ = 'Copyright 2009, Justin Quick and Joe McCall'
__credits__ = ['Justin Quick', 'Joe McCall', 'Jacob Feisley', 'John Nagle']
__license__ = 'New BSD'
+
+ try:
- __version__ = '0.5'
? ^^^^^
... |
342512a12868bc7dadbaf3c85b5aedd86bb990e7 | gunicorn/workers/__init__.py | gunicorn/workers/__init__.py |
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gun... |
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"gevent_pywsgi": "gun... | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary
Fixes #1011.
| Python | mit | GitHublong/gunicorn,elelianghh/gunicorn,ephes/gunicorn,malept/gunicorn,malept/gunicorn,tempbottle/gunicorn,malept/gunicorn,ccl0326/gunicorn,keakon/gunicorn,mvaled/gunicorn,tejasmanohar/gunicorn,mvaled/gunicorn,WSDC-NITWarangal/gunicorn,gtrdotmcs/gunicorn,mvaled/gunicorn,z-fork/gunicorn,prezi/gunicorn,zhoucen/gunicorn,p... |
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"... | Add the 'gthread' worker to the gunicorn.workers.SUPPORTED_WORKERS dictionary | ## Code Before:
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"geve... |
import sys
# supported gunicorn workers.
SUPPORTED_WORKERS = {
"sync": "gunicorn.workers.sync.SyncWorker",
"eventlet": "gunicorn.workers.geventlet.EventletWorker",
"gevent": "gunicorn.workers.ggevent.GeventWorker",
"gevent_wsgi": "gunicorn.workers.ggevent.GeventPyWSGIWorker",
"... |
03dc4f221aa9909c8a3074cbef9fd1816e0cc86c | stagecraft/libs/mass_update/data_set_mass_update.py | stagecraft/libs/mass_update/data_set_mass_update.py | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate():
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
model_filter = DataSet.objects
if 'data_type' in query:
data_type = cls._get_model_instance_b... | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate(object):
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
cls(query).update(bearer_token=new_token)
def __init__(self, query_dict):
self.model_filter =... | Refactor query out into instance with delegates the update | Refactor query out into instance with delegates the update
| Python | mit | alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft,alphagov/stagecraft | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
- class DataSetMassUpdate():
+ class DataSetMassUpdate(object):
+
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
+ cls(query).update(bearer_token=new_token)
- model_fil... | Refactor query out into instance with delegates the update | ## Code Before:
from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
class DataSetMassUpdate():
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
model_filter = DataSet.objects
if 'data_type' in query:
data_type = cls._get_... | from stagecraft.apps.datasets.models import DataGroup, DataSet, DataType
- class DataSetMassUpdate():
+ class DataSetMassUpdate(object):
? ++++++
+
@classmethod
def update_bearer_token_for_data_type_or_group_name(cls, query, new_token):
+ cls(query).update(bearer_to... |
1de828cf54ec0e87bdf1db4d7d4abf1b822eab68 | pytips/models.py | pytips/models.py | """Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
... | """Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQuery(BaseQuery):
... | Add `publication_date` property to `Tip` model. | Add `publication_date` property to `Tip` model.
BEFORE: We had a column in the DB, but no property on the model object.
AFTER: We have that property in the model.
| Python | isc | gthank/pytips,gthank/pytips,gthank/pytips,gthank/pytips | """Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
... | Add `publication_date` property to `Tip` model. | ## Code Before:
"""Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
class TipQue... | """Defines the model 'layer' for PyTips."""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from sqlalchemy import func
from flask.ext.sqlalchemy import BaseQuery
from pytips import db
... |
b1b0919f47f43d27bc409528617af8dbd4eea41c | tests/test_imports.py | tests/test_imports.py | import unittest
class TestImport(unittest.TestCase):
# Basic import tests for packages without any.
def test_basic(self):
import bq_helper
import cleverhans
from rl.agents.dqn import DQNAgent
| import unittest
class TestImport(unittest.TestCase):
# Basic import tests for packages without any.
def test_basic(self):
import bq_helper
import cleverhans
| Remove import test for keras-rl | Remove import test for keras-rl
This package was removed in #747 | Python | apache-2.0 | Kaggle/docker-python,Kaggle/docker-python | import unittest
class TestImport(unittest.TestCase):
# Basic import tests for packages without any.
def test_basic(self):
import bq_helper
import cleverhans
- from rl.agents.dqn import DQNAgent
| Remove import test for keras-rl | ## Code Before:
import unittest
class TestImport(unittest.TestCase):
# Basic import tests for packages without any.
def test_basic(self):
import bq_helper
import cleverhans
from rl.agents.dqn import DQNAgent
## Instruction:
Remove import test for keras-rl
## Code After:
import unittest... | import unittest
class TestImport(unittest.TestCase):
# Basic import tests for packages without any.
def test_basic(self):
import bq_helper
import cleverhans
- from rl.agents.dqn import DQNAgent |
3e403ed0962b62b19247dd1021f672507d003f07 | labware/microplates.py | labware/microplates.py | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
class Microplate(GridContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = 7.15
depth ... | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
class Microplate(GridContainer, LiquidContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = ... | Refactor of LiquidContainer vs. GridContainer to support grids which don't contain liquids. | Refactor of LiquidContainer vs. GridContainer to support grids which don't contain liquids.
| Python | apache-2.0 | OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons_sdk,OpenTrons/opentrons-api,OpenTrons/opentrons-api,OpenTrons/opentrons-api,Opentrons/labware | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
- class Microplate(GridContainer):
+ class Microplate(GridContainer, LiquidContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
... | Refactor of LiquidContainer vs. GridContainer to support grids which don't contain liquids. | ## Code Before:
from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
class Microplate(GridContainer):
rows = 8
cols = 12
volume = 100
min_vol = 50
max_vol = 90
height = 14.45
length = 127.76
width = 85.47
diameter = ... | from .grid import GridContainer, GridItem
from .liquids import LiquidContainer, LiquidWell
- class Microplate(GridContainer):
+ class Microplate(GridContainer, LiquidContainer):
? +++++++++++++++++
rows = 8
cols = 12
volume = 100
min_vol = ... |
46ebeba28f8fbb9d43457aa3fa539b29048a581b | netbox/users/api/views.py | netbox/users/api/views.py | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(Model... | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class UserViewSet(Model... | Set default ordering for user and group API endpoints | Set default ordering for user and group API endpoints
| Python | apache-2.0 | digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
... | Set default ordering for user and group API endpoints | ## Code Before:
from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
#
class U... | from django.contrib.auth.models import Group, User
from django.db.models import Count
from users import filters
from users.models import ObjectPermission
from utilities.api import ModelViewSet
from utilities.querysets import RestrictedQuerySet
from . import serializers
#
# Users and groups
... |
96d12496e425806a635ba345a534c0ca2790754d | satchmo/apps/payment/modules/giftcertificate/processor.py | satchmo/apps/payment/modules/giftcertificate/processor.py | from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__i... | from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProcessor, self).__i... | Fix the gift certificate module so that an invalid code won't throw an exception. | Fix the gift certificate module so that an invalid code won't throw an exception.
| Python | bsd-3-clause | twidi/satchmo,ringemup/satchmo,ringemup/satchmo,dokterbob/satchmo,twidi/satchmo,dokterbob/satchmo,Ryati/satchmo,Ryati/satchmo | from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentPr... | Fix the gift certificate module so that an invalid code won't throw an exception. | ## Code Before:
from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentProc... | from django.utils.translation import ugettext as _
from l10n.utils import moneyfmt
from models import GiftCertificate
from payment.modules.base import BasePaymentProcessor, ProcessorResult, NOTSET
class PaymentProcessor(BasePaymentProcessor):
def __init__(self, settings):
super(PaymentPr... |
6515d159ab3d09f4ac6157b0f825157c4ed1f5c9 | botbot/checks.py | botbot/checks.py | """Functions for checking files"""
import os
import stat
from .checker import is_link
def file_exists(path):
try:
with open(path, mode='r') as test:
pass
except FileNotFoundError:
if is_link(path):
return 'PROB_BROKEN_LINK'
except OSError:
return 'PROB_UNKNO... | """Functions for checking files"""
import os
import stat
from .checker import is_link
def is_fastq(path):
"""Check whether a given file is a fastq file."""
if os.path.splitext(path)[1] == ".fastq":
if not is_link(path):
return 'PROB_FILE_IS_FASTQ'
def sam_should_compress(path):
"""Che... | Clean up some loose ends | Clean up some loose ends
| Python | mit | jackstanek/BotBot,jackstanek/BotBot | """Functions for checking files"""
import os
import stat
from .checker import is_link
-
- def file_exists(path):
- try:
- with open(path, mode='r') as test:
- pass
- except FileNotFoundError:
- if is_link(path):
- return 'PROB_BROKEN_LINK'
- except OSError... | Clean up some loose ends | ## Code Before:
"""Functions for checking files"""
import os
import stat
from .checker import is_link
def file_exists(path):
try:
with open(path, mode='r') as test:
pass
except FileNotFoundError:
if is_link(path):
return 'PROB_BROKEN_LINK'
except OSError:
re... | """Functions for checking files"""
import os
import stat
from .checker import is_link
-
- def file_exists(path):
- try:
- with open(path, mode='r') as test:
- pass
- except FileNotFoundError:
- if is_link(path):
- return 'PROB_BROKEN_LINK'
- except OSError... |
c429abe7bee0461c8d2874ecb75093246565e58c | code/python/Gaussian.py | code/python/Gaussian.py | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
self.cos_theta, self.sin_theta = np.cos(self.theta... | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
def evaluate(self, x, y):
"""
Evaluate the den... | Make an image of a gaussian | Make an image of a gaussian
| Python | mit | eggplantbren/MogTrack | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
- self.cos_theta, self.sin... | Make an image of a gaussian | ## Code Before:
import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
self.cos_theta, self.sin_theta = n... | import numpy as np
class Gaussian:
"""
An object of this class is a 2D elliptical gaussian
"""
def __init__(self):
"""
Constructor sets up a standard gaussian
"""
self.xc, self.yc, self.mass, self.width, self.q, self.theta =\
0., 0., 1., 1., 1., 0.
- self.cos_theta, self.sin... |
4947ebf9460c2cf2ba8338de92601804dec2148a | src/svg_icons/templatetags/svg_icons.py | src/svg_icons/templatetags/svg_icons.py | import json
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
register = Library()
@register.inclusion_tag('svg_icons/icon.html')
def icon(name, **kwargs):
"""Render a SVG icon defined in a json file to our template.
..:json exampl... | import json
from importlib import import_module
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader')
try:
module, cls = reader_class.rspli... | Use the new reader classes in the template tag | Use the new reader classes in the template tag
| Python | apache-2.0 | mikedingjan/django-svg-icons,mikedingjan/django-svg-icons | import json
+ from importlib import import_module
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
+ reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader')
+
+ try:
+ module, cl... | Use the new reader classes in the template tag | ## Code Before:
import json
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
register = Library()
@register.inclusion_tag('svg_icons/icon.html')
def icon(name, **kwargs):
"""Render a SVG icon defined in a json file to our template.
... | import json
+ from importlib import import_module
from django.core.cache import cache
from django.conf import settings
from django.template import Library, TemplateSyntaxError
+ reader_class = getattr(settings, 'SVG_ICONS_READER_CLASS', 'svg_icons.readers.icomoon.IcomoonReader')
+
+ try:
+ module, cl... |
387ca6153d0f584f3caf27add6cf01d1da081fc3 | plasmapy/physics/__init__.py | plasmapy/physics/__init__.py |
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency
from .quantum import deBroglie_wavelength, ther... |
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency
from .quantum import deBroglie_wavelength, ther... | Add classical_transport to init file | Add classical_transport to init file
| Python | bsd-3-clause | StanczakDominik/PlasmaPy |
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency
from .quantum import deBroglie_wavelength... | Add classical_transport to init file | ## Code Before:
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency
from .quantum import deBroglie_... |
from .parameters import Alfven_speed, ion_sound_speed, thermal_speed, kappa_thermal_speed, gyrofrequency, gyroradius, plasma_frequency, Debye_length, Debye_number, inertial_length, magnetic_pressure, magnetic_energy_density, upper_hybrid_frequency, lower_hybrid_frequency
from .quantum import deBroglie_wavelength... |
6f540821e891f49e0f2059757b58d2aa0efdf267 | src/panda_test.py | src/panda_test.py | from direct.showbase.ShowBase import ShowBase
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
app = MyApp()
app.run()
| from math import pi, sin, cos
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from direct.actor.Actor import Actor
from direct.interval.IntervalGlobal import Sequence
from panda3d.core import Point3
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
s... | Add the rest of Panda3D test program. | Add the rest of Panda3D test program.
| Python | mit | CheeseLord/warts,CheeseLord/warts | + from math import pi, sin, cos
+
from direct.showbase.ShowBase import ShowBase
+ from direct.task import Task
+ from direct.actor.Actor import Actor
+ from direct.interval.IntervalGlobal import Sequence
+ from panda3d.core import Point3
class MyApp(ShowBase):
def __init__(self):
ShowBase._... | Add the rest of Panda3D test program. | ## Code Before:
from direct.showbase.ShowBase import ShowBase
class MyApp(ShowBase):
def __init__(self):
ShowBase.__init__(self)
app = MyApp()
app.run()
## Instruction:
Add the rest of Panda3D test program.
## Code After:
from math import pi, sin, cos
from direct.showbase.ShowBase import ShowBase
fr... | + from math import pi, sin, cos
+
from direct.showbase.ShowBase import ShowBase
+ from direct.task import Task
+ from direct.actor.Actor import Actor
+ from direct.interval.IntervalGlobal import Sequence
+ from panda3d.core import Point3
class MyApp(ShowBase):
def __init__(self):
ShowBase._... |
d5b231fbc5dd32ded78e4499a49872487533cda4 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.git') is True
... | from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecut... | Implement a test specifically for abbreviations | Implement a test specifically for abbreviations
| Python | bsd-3-clause | willingc/cookiecutter,michaeljoseph/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,pjbull/cookiecutter,ramiroluz/cookiecutter,luzfcb/cookiecutter,stevepiercy/cookiecutter,michaeljoseph/cookiecutter,pjbull/cookiecutter,cguardia/cookiecutter,terryjbates/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutt... | - from cookiecutter.main import is_repo_url
+ from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
... | Implement a test specifically for abbreviations | ## Code Before:
from cookiecutter.main import is_repo_url
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecutter.gi... | - from cookiecutter.main import is_repo_url
+ from cookiecutter.main import is_repo_url, expand_abbreviations
? ++++++++++++++++++++++
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
asser... |
aaa74513f8b947cf542b59408816be9ed1867644 | atc/atcd/setup.py | atc/atcd/setup.py | import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
setup... | import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['bin/atcd']
s... | Make atcd depends on atc_thrift package implicitely | Make atcd depends on atc_thrift package implicitely
| Python | bsd-3-clause | jamesblunt/augmented-traffic-control,linearregression/augmented-traffic-control,biddyweb/augmented-traffic-control,beni55/augmented-traffic-control,linearregression/augmented-traffic-control,duydb2/ZTC,shinyvince/augmented-traffic-control,Endika/augmented-traffic-control,drptbl/augmented-traffic-control,shinyvince/augm... | import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
- 'thrift'
+ 'atc_thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
te... | Make atcd depends on atc_thrift package implicitely | ## Code Before:
import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
'thrift'
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3.3':
tests_require.append('mock')
scripts = ['b... | import sys
from distutils.core import setup
readme = open("README.md", "r")
install_requires = [
'pyroute2==0.3.3',
'pyotp==1.4.1',
'sparts==0.7.1',
- 'thrift'
+ 'atc_thrift'
? ++++
]
tests_require = install_requires + [
'pytest'
]
if sys.version < '3... |
1eb6f65e40fccb3cea4b35374e7ddc25dd574dfa | examples/test/test_scratchnet.py | examples/test/test_scratchnet.py |
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( se... |
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
index = p.expect( se... | Increase scratchnet timeout to see if it's just slow. | Increase scratchnet timeout to see if it's just slow.
| Python | bsd-3-clause | mininet/mininet,mininet/mininet,mininet/mininet |
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
- ... | Increase scratchnet timeout to see if it's just slow. | ## Code Before:
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
inde... |
import unittest
import pexpect
class testScratchNet( unittest.TestCase ):
opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ]
def pingTest( self, name ):
"Verify that no ping packets were dropped"
p = pexpect.spawn( 'python -m %s' % name )
- ... |
7cef87a81278c227db0cb07329d1b659dbd175b3 | mail_factory/models.py | mail_factory/models.py |
import django
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
def autodiscover():
"""Auto-discover INSTALLED_APPS mails.py modules."""
for app in settings.INSTALLED_APPS:
module = '%s.mails' % app # Attem... |
import django
from django.conf import settings
from django.utils.module_loading import module_has_submodule
try:
from importlib import import_module
except ImportError:
# Compatibility for python-2.6
from django.utils.importlib import import_module
def autodiscover():
"""Auto-discover INSTALLED_APPS... | Use standard library instead of django.utils.importlib | Use standard library instead of django.utils.importlib
> django.utils.importlib is a compatibility library for when Python 2.6 was
> still supported. It has been obsolete since Django 1.7, which dropped support
> for Python 2.6, and is removed in 1.9 per the deprecation cycle.
> Use Python's import_module function ins... | Python | bsd-3-clause | novafloss/django-mail-factory,novafloss/django-mail-factory |
import django
from django.conf import settings
- from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
+
+ try:
+ from importlib import import_module
+ except ImportError:
+ # Compatibility for python-2.6
+ from django.utils.importlib import ... | Use standard library instead of django.utils.importlib | ## Code Before:
import django
from django.conf import settings
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
def autodiscover():
"""Auto-discover INSTALLED_APPS mails.py modules."""
for app in settings.INSTALLED_APPS:
module = '%s.mails... |
import django
from django.conf import settings
- from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
+
+ try:
+ from importlib import import_module
+ except ImportError:
+ # Compatibility for python-2.6
+ from django.utils.importlib import ... |
4c71ba23720001d06d519a7828f2866814f1c46a | tests/conftest.py | tests/conftest.py |
import pytest
from UM.Application import Application
class FixtureApplication(Application):
def __init__(self):
Application._instance = None
super().__init__("test", "1.0")
def functionEvent(self, event):
pass
def parseCommandLine(self):
pass
@pytest.fixture()
def appli... |
import pytest
from UM.Application import Application
from UM.Signal import Signal
class FixtureApplication(Application):
def __init__(self):
Application._instance = None
super().__init__("test", "1.0")
Signal._app = self
def functionEvent(self, event):
event.call()
def p... | Make sure to set the test application instance as app for Signals | Make sure to set the test application instance as app for Signals
This makes singals be properly emitted in tests
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium |
import pytest
from UM.Application import Application
+ from UM.Signal import Signal
class FixtureApplication(Application):
def __init__(self):
Application._instance = None
super().__init__("test", "1.0")
+ Signal._app = self
def functionEvent(self, event):
- ... | Make sure to set the test application instance as app for Signals | ## Code Before:
import pytest
from UM.Application import Application
class FixtureApplication(Application):
def __init__(self):
Application._instance = None
super().__init__("test", "1.0")
def functionEvent(self, event):
pass
def parseCommandLine(self):
pass
@pytest.fix... |
import pytest
from UM.Application import Application
+ from UM.Signal import Signal
class FixtureApplication(Application):
def __init__(self):
Application._instance = None
super().__init__("test", "1.0")
+ Signal._app = self
def functionEvent(self, event):
- ... |
fd909f383ab8a930c8a858144e0566075821f019 | tests/test_search.py | tests/test_search.py | from sharepa.search import ShareSearch
from sharepa.search import basic_search
import elasticsearch_dsl
import types
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
my_search = my_se... | from sharepa.search import ShareSearch
from sharepa.search import basic_search
import vcr
import types
import elasticsearch_dsl
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
my_sea... | Add vcr to scan test | Add vcr to scan test
| Python | mit | fabianvf/sharepa,erinspace/sharepa,samanehsan/sharepa,CenterForOpenScience/sharepa | from sharepa.search import ShareSearch
from sharepa.search import basic_search
+ import vcr
+ import types
import elasticsearch_dsl
- import types
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search... | Add vcr to scan test | ## Code Before:
from sharepa.search import ShareSearch
from sharepa.search import basic_search
import elasticsearch_dsl
import types
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search():
my_search = ShareSearch()
m... | from sharepa.search import ShareSearch
from sharepa.search import basic_search
+ import vcr
+ import types
import elasticsearch_dsl
- import types
def test_basic_search():
results = basic_search.execute()
assert results.hits
assert results.aggregations
def test_no_title_search... |
f5b13d16045e7e734a66bc13873ab5f4e8045f5a | skylines/views/about.py | skylines/views/about.py | import os.path
from flask import Blueprint, render_template
from flask.ext.babel import _
from skylines import app
from skylines.lib.helpers import markdown
about_blueprint = Blueprint('about', 'skylines')
@about_blueprint.route('/')
def about():
return render_template('about.jinja')
@about_blueprint.route('... | import os.path
from flask import Blueprint, render_template, current_app
from flask.ext.babel import _
from skylines.lib.helpers import markdown
about_blueprint = Blueprint('about', 'skylines')
@about_blueprint.route('/')
def about():
return render_template('about.jinja')
@about_blueprint.route('/imprint')
d... | Use current_app in Blueprint module | flask/views: Use current_app in Blueprint module
| Python | agpl-3.0 | RBE-Avionik/skylines,RBE-Avionik/skylines,Harry-R/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,TobiasLohner/SkyLines,kerel-fs/skylines,Harry-R/skylines,skylines-project/skylines,shadowoneau/skylines,Turbo87/skylines,snip/skylines,shadowoneau/skylines,RBE-Avion... | import os.path
- from flask import Blueprint, render_template
+ from flask import Blueprint, render_template, current_app
from flask.ext.babel import _
- from skylines import app
from skylines.lib.helpers import markdown
about_blueprint = Blueprint('about', 'skylines')
@about_blueprint.route('/... | Use current_app in Blueprint module | ## Code Before:
import os.path
from flask import Blueprint, render_template
from flask.ext.babel import _
from skylines import app
from skylines.lib.helpers import markdown
about_blueprint = Blueprint('about', 'skylines')
@about_blueprint.route('/')
def about():
return render_template('about.jinja')
@about_b... | import os.path
- from flask import Blueprint, render_template
+ from flask import Blueprint, render_template, current_app
? +++++++++++++
from flask.ext.babel import _
- from skylines import app
from skylines.lib.helpers import markdown
about_blueprint = Blu... |
72d0ca4e2f4be7969498b226af4243315f2dff0c | tests/test_colors.py | tests/test_colors.py | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
self.assertEqual(result[... | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
self.assertEqual(len(res... | Check color length instead of value since the tests will fail on other versions of imageamgick | tests: Check color length instead of value since the tests will fail on other versions of imageamgick
| Python | mit | dylanaraps/pywal,dylanaraps/pywal,dylanaraps/pywal | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
- ... | Check color length instead of value since the tests will fail on other versions of imageamgick | ## Code Before:
"""Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
self.ass... | """Test imagemagick functions."""
import unittest
from pywal import colors
class TestGenColors(unittest.TestCase):
"""Test the gen_colors functions."""
def test_gen_colors(self):
"""> Generate a colorscheme."""
result = colors.get("tests/test_files/test.jpg")
- ... |
fb65fedbf60481d37e097ea9db290f53b84cae26 | giveaminute/migrations/versions/001_Initial_models.py | giveaminute/migrations/versions/001_Initial_models.py | from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
import os
with open(os.path.join(os.path.dirname(__file__), '000_Initial_models.sql')) as initial_file:
sql = initi... | from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
import os
# Uncomment the following lines if you do not yet have a database to set up.
# If you run this migration, it will... | Comment out the initial migration step by default (so that we're not inadvertently blowing peoples databases away | Comment out the initial migration step by default (so that we're not inadvertently blowing peoples databases away
| Python | agpl-3.0 | codeforamerica/Change-By-Us,localprojects/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,codeforeurope/Change-By-Us,codeforeurope/Change-By-Us,codeforamerica/Change-By-Us,watchcat/cbu-rotterdam,watchcat/cbu-rotterdam,localprojects/Change-By-Us,localprojects/Change-By-Us,watchcat/c... | from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
-
+
import os
+ # Uncomment the following lines if you do not yet have a database to set up.
+ # If you ... | Comment out the initial migration step by default (so that we're not inadvertently blowing peoples databases away | ## Code Before:
from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
import os
with open(os.path.join(os.path.dirname(__file__), '000_Initial_models.sql')) as initial_file:
... | from sqlalchemy import *
from migrate import *
def upgrade(migrate_engine):
# Upgrade operations go here. Don't create your own engine; bind migrate_engine
# to your metadata
-
+
import os
+ # Uncomment the following lines if you do not yet have a database to set up.
+ # If you ... |
11853bead5a47d0b15877eb5e5968b91708bb223 | API/chat/models.py | API/chat/models.py | from django.db import models
class Channel(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20, unique=True)
class Message(models.Model):
def __str__(self):
return self.text
def to_dict(self):
return {
'text': self.text,
... | from django.db import models
class Channel(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20, unique=True)
class Message(models.Model):
def __str__(self):
return self.text
def to_dict(self):
serializable_fields = ('text', 'datetime_sta... | Refactor to_dict method on the Message model | Refactor to_dict method on the Message model
| Python | mit | odyvarv/ting-1,VitSalis/ting,odyvarv/ting-1,VitSalis/ting,mbalamat/ting,dionyziz/ting,gtklocker/ting,sirodoht/ting,mbalamat/ting,dionyziz/ting,VitSalis/ting,odyvarv/ting-1,mbalamat/ting,mbalamat/ting,VitSalis/ting,gtklocker/ting,odyvarv/ting-1,dionyziz/ting,sirodoht/ting,gtklocker/ting,gtklocker/ting,sirodoht/ting,siro... | from django.db import models
class Channel(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20, unique=True)
class Message(models.Model):
def __str__(self):
return self.text
def to_dict(self):
+ serializable... | Refactor to_dict method on the Message model | ## Code Before:
from django.db import models
class Channel(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20, unique=True)
class Message(models.Model):
def __str__(self):
return self.text
def to_dict(self):
return {
'text':... | from django.db import models
class Channel(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=20, unique=True)
class Message(models.Model):
def __str__(self):
return self.text
def to_dict(self):
+ serializable... |
eca2199c90fa169acef8672458df0df3e6d65fad | tests/test_device.py | tests/test_device.py | def test_test():
assert True
| import pytest
from xbee_helper import device, exceptions, ZigBee
def test_raise_if_error_no_status():
"""
Should return None without raising if there's no "status" key in frame.
"""
assert device.raise_if_error({}) is None
def test_raise_if_error_zero():
"""
Should return None without raisi... | Add tests for raise_if_error function | Add tests for raise_if_error function
| Python | mit | flyte/xbee-helper | + import pytest
- def test_test():
- assert True
+ from xbee_helper import device, exceptions, ZigBee
+
+
+ def test_raise_if_error_no_status():
+ """
+ Should return None without raising if there's no "status" key in frame.
+ """
+ assert device.raise_if_error({}) is None
+
+
+ def test_rais... | Add tests for raise_if_error function | ## Code Before:
def test_test():
assert True
## Instruction:
Add tests for raise_if_error function
## Code After:
import pytest
from xbee_helper import device, exceptions, ZigBee
def test_raise_if_error_no_status():
"""
Should return None without raising if there's no "status" key in frame.
"""
... | - def test_test():
- assert True
+ import pytest
+
+ from xbee_helper import device, exceptions, ZigBee
+
+
+ def test_raise_if_error_no_status():
+ """
+ Should return None without raising if there's no "status" key in frame.
+ """
+ assert device.raise_if_error({}) is None
+
+
+ def test_rais... |
06d210cdc811f0051a489f335cc94a604e99a35d | werobot/session/mongodbstorage.py | werobot/session/mongodbstorage.py |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
... |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import MongoDBStorage
... | Use new pymongo API in MongoDBStorage | Use new pymongo API in MongoDBStorage
| Python | mit | whtsky/WeRoBot,whtsky/WeRoBot,adam139/WeRobot,adam139/WeRobot,whtsky/WeRoBot,weberwang/WeRoBot,weberwang/WeRoBot |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... | Use new pymongo API in MongoDBStorage | ## Code Before:
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage import M... |
from werobot.session import SessionStorage
from werobot.utils import json_loads, json_dumps
class MongoDBStorage(SessionStorage):
"""
MongoDBStorage 会把你的 Session 数据储存在一个 MongoDB Collection 中 ::
import pymongo
import werobot
from werobot.session.mongodbstorage ... |
5fc72fab36b3c29ccadc64aac3ffcb8d6bf56c48 | osf/models/subject.py | osf/models/subject.py | from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text... | from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query = None
text... | Add Subject.hierarchy to djangosf model | Add Subject.hierarchy to djangosf model
| Python | apache-2.0 | Johnetordoff/osf.io,mluo613/osf.io,acshi/osf.io,hmoco/osf.io,alexschiller/osf.io,adlius/osf.io,leb2dg/osf.io,adlius/osf.io,mfraezz/osf.io,monikagrabowska/osf.io,cwisecarver/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,Johnetordoff/osf.io,caneruguz/osf.io,baylee-d/osf.io,saradbowman/osf.io,aaxelb/osf.io,brianjgeiger/osf.... | from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_... | Add Subject.hierarchy to djangosf model | ## Code Before:
from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_query ... | from django.db import models
from website.util import api_v2_url
from osf.models.base import BaseModel, ObjectIDMixin
class Subject(ObjectIDMixin, BaseModel):
"""A subject discipline that may be attached to a preprint."""
modm_model_path = 'website.project.taxonomies.Subject'
modm_... |
ccdb5001a450859ae9eb85f1c2c90a9a80fa0ce1 | eforge/wiki/urls.py | eforge/wiki/urls.py |
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
url(r'^$', 'wiki_page', name='wiki-home'),
) |
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'),
url(r'^$', 'wiki_page', name='wiki-home'),
) | Update wiki to be a little more flexible with naming | Update wiki to be a little more flexible with naming
| Python | isc | oshepherd/eforge,oshepherd/eforge,oshepherd/eforge |
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
- url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
+ url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'),
- url(r'^$', 'wiki_page', name='wiki-home'),
+ url(r'^$', ... | Update wiki to be a little more flexible with naming | ## Code Before:
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
url(r'^$', 'wiki_page', name='wiki-home'),
)
## Instruction:
Update wiki to be a little more flexible with naming
## Code Afte... |
from django.conf.urls.defaults import *
patterns = patterns('eforge.wiki.views',
- url(r'^(?P<name>[a-zA-Z_/ ]+)$', 'wiki_page', name='wiki-page'),
? ^^^^^^^^^
+ url(r'^(?P<name>[\w]+)$', 'wiki_page', name='wiki-page'),
? ^^ +
- url(r'^$', ... |
313a81093527c88631713f6b4ad8c652554edb50 | l10n_br_base/migrations/12.0.1.0.0/post-migration.py | l10n_br_base/migrations/12.0.1.0.0/post-migration.py |
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
cr.execute(
'''INSERT INTO res_city(id, name, country_id, state_id, ibge_code)
SELECT nextval('res_city_id_seq'), name, (SELECT id FROM res_country
WHERE code='BR'), state_id, ibge_co... |
from openupgradelib import openupgrade
_model_renames = [
('l10n_br_base.city', 'res.city'),
]
_table_renames = [
('l10n_br_base_city', 'res_city'),
]
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
openupgrade.rename_models(cr, _model_renames)
openupgrade.rename_tables(cr, _table... | Rename table _model_renames and _table_renames | [ADD] Rename table _model_renames and _table_renames
Signed-off-by: Luis Felipe Mileo <c9a5b4d335634d99740001a1172b3e56e4fc5aa8@kmee.com.br>
| Python | agpl-3.0 | akretion/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,OCA/l10n-brazil,akretion/l10n-brazil,akretion/l10n-brazil |
from openupgradelib import openupgrade
+
+ _model_renames = [
+ ('l10n_br_base.city', 'res.city'),
+ ]
+
+ _table_renames = [
+ ('l10n_br_base_city', 'res_city'),
+ ]
+
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
+ openupgrade.rename_models(cr, _model_renames)
+ op... | Rename table _model_renames and _table_renames | ## Code Before:
from openupgradelib import openupgrade
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
cr.execute(
'''INSERT INTO res_city(id, name, country_id, state_id, ibge_code)
SELECT nextval('res_city_id_seq'), name, (SELECT id FROM res_country
WHERE code='BR'), s... |
from openupgradelib import openupgrade
+
+ _model_renames = [
+ ('l10n_br_base.city', 'res.city'),
+ ]
+
+ _table_renames = [
+ ('l10n_br_base_city', 'res_city'),
+ ]
+
@openupgrade.migrate()
def migrate(env, version):
cr = env.cr
+ openupgrade.rename_models(cr, _model_renames)
+ op... |
315b581b9b0438389c7f4eb651d2893b805a2369 | translit.py | translit.py | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
reverse=True,
... | Handle case when char is mapped to empty (removed) and table is inverted | Handle case when char is mapped to empty (removed) and table is inverted
| Python | mit | malexer/SublimeTranslit | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
... | Handle case when char is mapped to empty (removed) and table is inverted | ## Code Before:
class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
... | class Transliterator(object):
def __init__(self, mapping, invert=False):
self.mapping = [
(v, k) if invert else (k, v)
for k, v in mapping.items()
]
self._rules = sorted(
self.mapping,
key=lambda item: len(item[0]),
... |
0ad6cb338bbf10c48049d5649b5cd41eab0ed8d1 | prawcore/sessions.py | prawcore/sessions.py | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self):
"""Preprare the connection to reddit's API."""
self._session = requests.Session()
def __enter__(s... | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self, authorizer=None):
"""Preprare the connection to reddit's API.
:param authorizer: An instance of :class... | Add optional authorizer parameter to session class and function. | Add optional authorizer parameter to session class and function.
| Python | bsd-2-clause | praw-dev/prawcore | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
- def __init__(self):
+ def __init__(self, authorizer=None):
- """Preprare the connection to reddit's API."""
... | Add optional authorizer parameter to session class and function. | ## Code Before:
"""prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
def __init__(self):
"""Preprare the connection to reddit's API."""
self._session = requests.Session()
... | """prawcore.sessions: Provides prawcore.Session and prawcore.session."""
import requests
class Session(object):
"""The low-level connection interface to reddit's API."""
- def __init__(self):
+ def __init__(self, authorizer=None):
- """Preprare the connection to reddit's API."""
... |
c8c0f6ec8abbcc845df38bfbba36b5ae916f77cd | vinotes/apps/api/urls.py | vinotes/apps/api/urls.py | from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^notes/$', views.NoteList.as_view()),
url(r'^notes/(?P<pk>[0-9]+)/$', views.NoteDetail.as_view()),
url(r'^traits/$', views.TraitList.as_view()),
url(r'^traits/(?P<pk... | from django.conf.urls import include, url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^notes/$', views.NoteList.as_view()),
url(r'^notes/(?P<pk>[0-9]+)/$', views.Note... | Add login to browsable API. | Add login to browsable API.
| Python | unlicense | rcutmore/vinotes-api,rcutmore/vinotes-api | - from django.conf.urls import url
+ from django.conf.urls import include, url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^notes/$', views.NoteList.as_view... | Add login to browsable API. | ## Code Before:
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
url(r'^notes/$', views.NoteList.as_view()),
url(r'^notes/(?P<pk>[0-9]+)/$', views.NoteDetail.as_view()),
url(r'^traits/$', views.TraitList.as_view()),
url(... | - from django.conf.urls import url
+ from django.conf.urls import include, url
? +++++++++
from rest_framework.urlpatterns import format_suffix_patterns
from . import views
urlpatterns = [
+ url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
... |
4418a08553572ca18187472cc32e5044229333f2 | django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py | django/applications/catmaid/management/commands/catmaid_set_user_profiles_to_default.py | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
def handle_noargs(self, **options):
for u in User.objects.... | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
from optparse import make_option
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
option_list = NoArgsCommand.opti... | Add explicit anonymous user update parameter to user profile command | Add explicit anonymous user update parameter to user profile command
The set_user_profiles_to_default management command should only update
the anonymous user if explicitely stated. This commit adds the
'--update-anon-user' switch to do let the user state that also the
anonymous user's profile should be updated with t... | Python | agpl-3.0 | fzadow/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,htem/CATMAID | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
+ from optparse import make_option
+
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
+ option_list ... | Add explicit anonymous user update parameter to user profile command | ## Code Before:
from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
def handle_noargs(self, **options):
for u ... | from django.conf import settings
from django.contrib.auth.models import User
from django.core.management.base import NoArgsCommand, CommandError
+ from optparse import make_option
+
class Command(NoArgsCommand):
help = "Set the user profile settings of every user to the defaults"
+ option_list ... |
ea54f0a306c6defa4edc58c50794da0083ed345d | setup_app.py | setup_app.py |
import os
from flask_app.database import init_db
# Generate new secret key
secret_key = os.urandom(24).encode('hex').strip()
with open('flask_app/secret_key.py', 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".decode("hex")')
# Initialize database
init_db()
|
import os
from flask_app.database import init_db
# Generate new secret key
key_file_path = 'flask_app/secret_key.py'
if not os.path.isfile(key_file_path):
secret_key = os.urandom(24).encode('hex').strip()
with open(key_file_path, 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".... | Check if keyfile exists before generating new key | Check if keyfile exists before generating new key
| Python | mit | szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft,szeestraten/kidsakoder-minecraft |
import os
from flask_app.database import init_db
# Generate new secret key
+ key_file_path = 'flask_app/secret_key.py'
+ if not os.path.isfile(key_file_path):
- secret_key = os.urandom(24).encode('hex').strip()
+ secret_key = os.urandom(24).encode('hex').strip()
- with open('flask_app/secret_key.py', 'w... | Check if keyfile exists before generating new key | ## Code Before:
import os
from flask_app.database import init_db
# Generate new secret key
secret_key = os.urandom(24).encode('hex').strip()
with open('flask_app/secret_key.py', 'w') as key_file:
key_file.write('secret_key = """' + secret_key + '""".decode("hex")')
# Initialize database
init_db()
## Instruction... |
import os
from flask_app.database import init_db
# Generate new secret key
+ key_file_path = 'flask_app/secret_key.py'
+ if not os.path.isfile(key_file_path):
- secret_key = os.urandom(24).encode('hex').strip()
+ secret_key = os.urandom(24).encode('hex').strip()
? ++++
- with open('flask_app/secret_key... |
8c159ee5fa6aa1d10cef2268a373b90f6cb72896 | px/px_loginhistory.py | px/px_loginhistory.py | def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
which addresses at a given timestamp.
Optional argument last_output is the output of "last". Will be filled in by
actually executing "last" if not provided.
Opt... | import sys
import re
USERNAME_PART = "([^ ]+)"
DEVICE_PART = "([^ ]+)"
ADDRESS_PART = "([^ ]+)?"
FROM_PART = "(.*)"
DASH_PART = " . "
TO_PART = "(.*)"
DURATION_PART = "([0-9+:]+)"
LAST_RE = re.compile(
USERNAME_PART +
" +" +
DEVICE_PART +
" +" +
ADDRESS_PART +
" +" +
FROM_PART +
DASH_PART +
TO_PART ... | Create regexp to match at least some last lines | Create regexp to match at least some last lines
| Python | mit | walles/px,walles/px | + import sys
+
+ import re
+
+ USERNAME_PART = "([^ ]+)"
+ DEVICE_PART = "([^ ]+)"
+ ADDRESS_PART = "([^ ]+)?"
+ FROM_PART = "(.*)"
+ DASH_PART = " . "
+ TO_PART = "(.*)"
+ DURATION_PART = "([0-9+:]+)"
+ LAST_RE = re.compile(
+ USERNAME_PART +
+ " +" +
+ DEVICE_PART +
+ " +" +
+ ADDRESS_PART +
+ " +" +
+ ... | Create regexp to match at least some last lines | ## Code Before:
def get_users_at(timestamp, last_output=None, now=None):
"""
Return a set of strings corresponding to which users were logged in from
which addresses at a given timestamp.
Optional argument last_output is the output of "last". Will be filled in by
actually executing "last" if not pr... | + import sys
+
+ import re
+
+ USERNAME_PART = "([^ ]+)"
+ DEVICE_PART = "([^ ]+)"
+ ADDRESS_PART = "([^ ]+)?"
+ FROM_PART = "(.*)"
+ DASH_PART = " . "
+ TO_PART = "(.*)"
+ DURATION_PART = "([0-9+:]+)"
+ LAST_RE = re.compile(
+ USERNAME_PART +
+ " +" +
+ DEVICE_PART +
+ " +" +
+ ADDRESS_PART +
+ " +" +
+ ... |
5125bbfcf96ff0d3f2690198b43ed96059eb6745 | common/parsableText.py | common/parsableText.py | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
... | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are supported"""
... | Fix unicode in parsable text | Fix unicode in parsable text
| Python | agpl-3.0 | GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious,layus/INGInious,layus/INGInious,GuillaumeDerval/INGInious,GuillaumeDerval/INGInious,layus/INGInious | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are suppo... | Fix unicode in parsable text | ## Code Before:
from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are suppo... | from docutils import core
class ParsableText:
"""Allow to parse a string with different parsers"""
def __init__(self,content,mode="rst"):
"""Init the object. Content is the string to be parsed. Mode is the parser to be used. Currently, only rst(reStructuredText) and HTML are suppo... |
c9abba3a9ca6ccf1a9bed5fad5cda12557b3266c | tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py | tests/chainer_tests/training_tests/extensions_tests/test_plot_report.py | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
... | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available = False
... | Use plot_report._available instead of available() | Use plot_report._available instead of available()
| Python | mit | hvy/chainer,jnishi/chainer,niboshi/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,chainer/chainer,jnishi/chainer,niboshi/chainer,okuta/chainer,keisuke-umezawa/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,okuta/chainer,chainer/chainer,hvy/chainer,ktnyt/chainer,ktnyt/chainer,wkentaro/chainer,jnishi/ch... | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
... | Use plot_report._available instead of available() | ## Code Before:
import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
available... | import unittest
import warnings
from chainer import testing
from chainer.training import extensions
class TestPlotReport(unittest.TestCase):
def test_available(self):
try:
import matplotlib # NOQA
available = True
except ImportError:
... |
7bab32ef89d760a8cf4aeb2700725ea88e3fc31c | tests/basics/builtin_hash.py | tests/basics/builtin_hash.py |
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
print(hash(A())... |
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
print(hash(A())... | Add further tests for class defining __hash__. | tests: Add further tests for class defining __hash__.
| Python | mit | martinribelotta/micropython,puuu/micropython,ganshun666/micropython,suda/micropython,EcmaXp/micropython,ChuckM/micropython,mgyenik/micropython,pramasoul/micropython,infinnovation/micropython,bvernoux/micropython,xyb/micropython,lbattraw/micropython,adafruit/circuitpython,blazewicz/micropython,tobbad/micropython,kostyll... |
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
re... | Add further tests for class defining __hash__. | ## Code Before:
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
return "a instance"
... |
print(hash(False))
print(hash(True))
print({():1}) # hash tuple
print({1 << 66:1}) # hash big int
print(hash in {hash:1}) # hash function
try:
hash([])
except TypeError:
print("TypeError")
class A:
def __hash__(self):
return 123
def __repr__(self):
re... |
26c1daab6095c6110995104b94ad5b6260557c70 | aiortp/sdp.py | aiortp/sdp.py | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = f'IN IP4 {self.local_addr[0]}'
self.payload = '\r\n'.join([
'v=0',
f'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
... | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = 'IN IP4 {}'.format(self.local_addr[0])
self.payload = '\r\n'.join([
'v=0',
'o=user1 53655765 2353687637 {local_addr_desc}',
's=-',
... | Remove python 3.6 only format strings | Remove python 3.6 only format strings
| Python | apache-2.0 | vodik/aiortp | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
- local_addr_desc = f'IN IP4 {self.local_addr[0]}'
+ local_addr_desc = 'IN IP4 {}'.format(self.local_addr[0])
self.payload = '\r\n'.join([
'v=0',
- ... | Remove python 3.6 only format strings | ## Code Before:
class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
local_addr_desc = f'IN IP4 {self.local_addr[0]}'
self.payload = '\r\n'.join([
'v=0',
f'o=user1 53655765 2353687637 {local_addr_desc}',
... | class SDP:
def __init__(self, local_addr, ptime):
self.local_addr = local_addr
self.ptime = ptime
- local_addr_desc = f'IN IP4 {self.local_addr[0]}'
? - ^^
+ local_addr_desc = 'IN IP4 {}'.format(self.local_addr[0])
? ... |
260beeaae9daeadb3319b895edc5328504e779b2 | cansen.py | cansen.py |
print('Test')
| import cantera as ct
gas = ct.Solution('mech.cti')
gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
reac = ct.Reactor(gas)
netw = ct.ReactorNet([reac])
tend = 10
time = 0
while time < tend:
time = netw.step(tend)
print(time,reac.T,reac.thermo.P)
if reac.T > 1400:
break
| Create working constant volume reactor test | Create working constant volume reactor test
| Python | mit | kyleniemeyer/CanSen,bryanwweber/CanSen | + import cantera as ct
+ gas = ct.Solution('mech.cti')
+ gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
+ reac = ct.Reactor(gas)
+ netw = ct.ReactorNet([reac])
+ tend = 10
+ time = 0
+ while time < tend:
+ time = netw.step(tend)
+ print(time,reac.T,reac.thermo.P)
+ if reac.T > 1400:
+ break
- print('T... | Create working constant volume reactor test | ## Code Before:
print('Test')
## Instruction:
Create working constant volume reactor test
## Code After:
import cantera as ct
gas = ct.Solution('mech.cti')
gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
reac = ct.Reactor(gas)
netw = ct.ReactorNet([reac])
tend = 10
time = 0
while time < tend:
time = netw.step(tend)
... | -
- print('Test')
+ import cantera as ct
+ gas = ct.Solution('mech.cti')
+ gas.TPX = 1000,101325,'H2:2,O2:1,N2:3.76'
+ reac = ct.Reactor(gas)
+ netw = ct.ReactorNet([reac])
+ tend = 10
+ time = 0
+ while time < tend:
+ time = netw.step(tend)
+ print(time,reac.T,reac.thermo.P)
+ if reac.T > 1400:
+ ... |
36e00778befd9e6763236b771a77184d31c3c885 | babbage_fiscal/tasks.py | babbage_fiscal/tasks.py | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connection_string is not None:... | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connection_string is not None:... | Add more info to the callback | Add more info to the callback
| Python | mit | openspending/babbage.fiscal-data-package | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connec... | Add more info to the callback | ## Code Before:
from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connection_str... | from celery import Celery
import requests
from .config import get_engine, _set_connection_string
from .loader import FDPLoader
app = Celery('fdp_loader')
app.config_from_object('babbage_fiscal.celeryconfig')
@app.task
def load_fdp_task(package, callback, connection_string=None):
if connec... |
4636fc514b0ebf7b16e82cc3eb7de6b69431cd43 | site_analytics.py | site_analytics.py |
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S*)?" (?P<code>[^ ]*) (?P... |
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S*)?" (?P<code>... | Fix tab spacing from 2 to 4 spaces | Fix tab spacing from 2 to 4 spaces
| Python | mit | mouhtasi/basic_site_analytics |
import re
def get_log_lines(path):
- """Return a list of regex matched log lines from the passed nginx access log path"""
+ """Return a list of regex matched log lines from the passed nginx access log path"""
- lines = []
+ lines = []
- with open(path) as f:
+ with open(path) as f:
- ... | Fix tab spacing from 2 to 4 spaces | ## Code Before:
import re
def get_log_lines(path):
"""Return a list of regex matched log lines from the passed nginx access log path"""
lines = []
with open(path) as f:
r = re.compile("""(?P<remote>[^ ]*) (?P<host>[^ ]*) (?P<user>[^ ]*) \[(?P<time>[^\]]*)\] "(?P<method>\S+)(?: +(?P<path>[^\"]*) +\S*)?" (?P... |
import re
def get_log_lines(path):
- """Return a list of regex matched log lines from the passed nginx access log path"""
+ """Return a list of regex matched log lines from the passed nginx access log path"""
? ++
- lines = []
+ lines = []
? ++
- with open(path) as f:
+ with open(path) ... |
8fa89c8642721896b7b97ff928bc66e65470691a | pinax/stripe/tests/test_utils.py | pinax/stripe/tests/test_utils.py | import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import convert_tstamp, plan_from_stripe_id
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(
sta... | import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import convert_tstamp
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(
stamp,
datet... | Remove test for function that no longer exists | Remove test for function that no longer exists
| Python | mit | pinax/django-stripe-payments | import datetime
from django.test import TestCase
from django.utils import timezone
- from ..utils import convert_tstamp, plan_from_stripe_id
+ from ..utils import convert_tstamp
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_... | Remove test for function that no longer exists | ## Code Before:
import datetime
from django.test import TestCase
from django.utils import timezone
from ..utils import convert_tstamp, plan_from_stripe_id
class TestTimestampConversion(TestCase):
def test_conversion_without_field_name(self):
stamp = convert_tstamp(1365567407)
self.assertEquals(... | import datetime
from django.test import TestCase
from django.utils import timezone
- from ..utils import convert_tstamp, plan_from_stripe_id
? ---------------------
+ from ..utils import convert_tstamp
class TestTimestampConversion(TestCase):
def test_conv... |
246971d8dd7d6c5fdc480c55e4e79ffd7a840b9b | Cura/View/View.py | Cura/View/View.py | class View(object):
def __init__(self):
self._renderer = None | class View(object):
def __init__(self):
self._renderer = None
def render(self, glcontext):
pass
| Add a render method to view that should be reimplemented | Add a render method to view that should be reimplemented
| Python | agpl-3.0 | onitake/Uranium,onitake/Uranium | class View(object):
def __init__(self):
self._renderer = None
+
+ def render(self, glcontext):
+ pass
+ | Add a render method to view that should be reimplemented | ## Code Before:
class View(object):
def __init__(self):
self._renderer = None
## Instruction:
Add a render method to view that should be reimplemented
## Code After:
class View(object):
def __init__(self):
self._renderer = None
def render(self, glcontext):
pass
| class View(object):
def __init__(self):
self._renderer = None
+
+ def render(self, glcontext):
+ pass |
bb5d6d94d555a91b2f9da1258aee90146ccd9998 | openstack/common/messaging/_executors/impl_eventlet.py | openstack/common/messaging/_executors/impl_eventlet.py |
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
def start(self):
if s... |
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
def start(self):
if s... | Add forgotten piece of eventlet executor | Add forgotten piece of eventlet executor
| Python | apache-2.0 | hkumarmk/oslo.messaging,dims/oslo.messaging,dukhlov/oslo.messaging,hkumarmk/oslo.messaging,ozamiatin/oslo.messaging,redhat-openstack/oslo.messaging,dukhlov/oslo.messaging,zhurongze/oslo.messaging,isyippee/oslo.messaging,viggates/oslo.messaging,markmc/oslo.messaging,apporc/oslo.messaging,apporc/oslo.messaging,stevei101/... |
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
d... | Add forgotten piece of eventlet executor | ## Code Before:
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
def start(sel... |
import eventlet
import greenlet
from openstack.common.messaging._executors import base
class EventletExecutor(base.ExecutorBase):
def __init__(self, conf, listener, callback):
super(EventletExecutor, self).__init__(conf, listener, callback)
self._thread = None
d... |
8e72ef3fa525c961786e9b60c039c847bc2c710f | caSandbox.py | caSandbox.py | import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WH... | import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2, curses.COLOR_WH... | Make program close on any keypress | Make program close on any keypress
| Python | mit | cferwin/CA-Sandbox | import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.... | Make program close on any keypress | ## Code Before:
import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.init_pair(2,... | import map
import curses
# Set up Curses screen
screen = curses.initscr()
curses.noecho()
screen.keypad(True)
curses.cbreak()
curses.halfdelay(5) # Wait for half a second for input before continuing
curses.start_color()
curses.init_pair(1, curses.COLOR_RED, curses.COLOR_BLACK)
curses.... |
2c26434b7dcd71530d453989372b8d67d90ad3c7 | rwt/scripts.py | rwt/scripts.py | import sys
import tokenize
def run(cmdline):
"""
Execute the script as if it had been invoked naturally.
"""
namespace = dict()
filename = cmdline[0]
namespace['__file__'] = filename
namespace['__name__'] = '__main__'
sys.argv[:] = cmdline
open_ = getattr(tokenize, 'open', open)
script = open_(filename).re... | import sys
import ast
import tokenize
def read_deps(script, var_name='__requires__'):
"""
Given a script path, read the dependencies from the
indicated variable (default __requires__). Does not
execute the script, so expects the var_name to be
assigned a static list of strings.
"""
with open(script) as stream:... | Add routine for loading deps from a script. | Add routine for loading deps from a script.
| Python | mit | jaraco/rwt | import sys
+ import ast
import tokenize
+
+
+ def read_deps(script, var_name='__requires__'):
+ """
+ Given a script path, read the dependencies from the
+ indicated variable (default __requires__). Does not
+ execute the script, so expects the var_name to be
+ assigned a static list of strings.
+ """
+ wi... | Add routine for loading deps from a script. | ## Code Before:
import sys
import tokenize
def run(cmdline):
"""
Execute the script as if it had been invoked naturally.
"""
namespace = dict()
filename = cmdline[0]
namespace['__file__'] = filename
namespace['__name__'] = '__main__'
sys.argv[:] = cmdline
open_ = getattr(tokenize, 'open', open)
script = op... | import sys
+ import ast
import tokenize
+
+
+ def read_deps(script, var_name='__requires__'):
+ """
+ Given a script path, read the dependencies from the
+ indicated variable (default __requires__). Does not
+ execute the script, so expects the var_name to be
+ assigned a static list of strings.
+ """
+ wi... |
cbb0ed5ed66571feba22413472a5fe1a20824dbd | shared_export.py | shared_export.py | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
if name not in sequences:
... | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
what = what.lower()
if... | Make sequence marker types (:type) case insensitive | Make sequence marker types (:type) case insensitive
| Python | mit | qoh/io_scene_dts,portify/io_scene_dts | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
+ what = ... | Make sequence marker types (:type) case insensitive | ## Code Before:
import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
if name not in... | import bpy
def find_seqs(scene, select_marker):
sequences = {}
sequence_flags = {}
for marker in scene.timeline_markers:
if ":" not in marker.name or (select_marker and not marker.select):
continue
name, what = marker.name.rsplit(":", 1)
+ what = ... |
319bdba73d0ccecb229454272bb9bb12c226335a | cineapp/fields.py | cineapp/fields.py |
from wtforms import fields, widgets
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDITOR.replace( '%s... |
from wtforms import fields, widgets
from flask import Markup
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>... | Fix unwanted escape for CKEditor display | Fix unwanted escape for CKEditor display
Fixes: #117
| Python | mit | ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp |
from wtforms import fields, widgets
+ from flask import Markup
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_st... | Fix unwanted escape for CKEditor display | ## Code Before:
from wtforms import fields, widgets
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_string += ("""<script>
CKEDI... |
from wtforms import fields, widgets
+ from flask import Markup
# Define wtforms widget and field
class CKTextAreaWidget(widgets.TextArea):
def __call__(self, field, **kwargs):
kwargs.setdefault('class_', 'ckeditor')
html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs)
html_st... |
1db1dfe35a97080286577b78f4708cc9afd82232 | rx/checkedobserver.py | rx/checkedobserver.py | from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check_access()
... | from six import add_metaclass
from rx import Observer
from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 -... | Use extension method for Observer.checked | Use extension method for Observer.checked
| Python | mit | dbrattli/RxPY,ReactiveX/RxPY,ReactiveX/RxPY | + from six import add_metaclass
+
from rx import Observer
+ from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 -... | Use extension method for Observer.checked | ## Code Before:
from rx import Observer
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 - idle, 1 - busy, 2 - done
def on_next(self, value):
self.check... | + from six import add_metaclass
+
from rx import Observer
+ from rx.internal import ExtensionMethod
from rx.internal.exceptions import ReEntracyException, CompletedException
class CheckedObserver(Observer):
def __init__(self, observer):
self._observer = observer
self._state = 0 # 0 -... |
13d1895a979cfb210e097e4d471238bf36c88c65 | website/db_create.py | website/db_create.py | from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.')
print('Recreating ... | from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.')
print('Recreating ... | Use store true in db creation script | Use store true in db creation script
| Python | lgpl-2.1 | reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visua... | from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.... | Use store true in db creation script | ## Code Before:
from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.')
pr... | from database import db
from database import bdb
from database import bdb_refseq
from import_data import import_data
import argparse
def restet_relational_db():
print('Removing relational database...')
db.reflect()
db.drop_all()
print('Removing relational database completed.... |
7a5b86bcb8c0a2e8c699c7602cef50bed2acef1b | src/keybar/tests/factories/user.py | src/keybar/tests/factories/user.py | import factory
from django.contrib.auth.hashers import make_password
from keybar.models.user import User
class UserFactory(factory.DjangoModelFactory):
email = factory.Sequence(lambda i: '{0}@none.none'.format(i))
is_active = True
class Meta:
model = User
@classmethod
def _prepare(cls, ... | import factory
from django.contrib.auth.hashers import make_password
from keybar.models.user import User
class UserFactory(factory.DjangoModelFactory):
email = factory.Sequence(lambda i: '{0}@none.none'.format(i))
is_active = True
class Meta:
model = User
@classmethod
def _prepare(cls, ... | Use pdbkdf_sha256 hasher for testing too. | Use pdbkdf_sha256 hasher for testing too.
| Python | bsd-3-clause | keybar/keybar | import factory
from django.contrib.auth.hashers import make_password
from keybar.models.user import User
class UserFactory(factory.DjangoModelFactory):
email = factory.Sequence(lambda i: '{0}@none.none'.format(i))
is_active = True
class Meta:
model = User
@classm... | Use pdbkdf_sha256 hasher for testing too. | ## Code Before:
import factory
from django.contrib.auth.hashers import make_password
from keybar.models.user import User
class UserFactory(factory.DjangoModelFactory):
email = factory.Sequence(lambda i: '{0}@none.none'.format(i))
is_active = True
class Meta:
model = User
@classmethod
de... | import factory
from django.contrib.auth.hashers import make_password
from keybar.models.user import User
class UserFactory(factory.DjangoModelFactory):
email = factory.Sequence(lambda i: '{0}@none.none'.format(i))
is_active = True
class Meta:
model = User
@classm... |
8eed621a15dafc8b0965c59b8da2296f8193d0ca | karabo_data/tests/test_agipd_geometry.py | karabo_data/tests/test_agipd_geometry.py | import numpy as np
from karabo_data.geometry2 import AGIPD_1MGeometry
def test_snap_assemble_data():
geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[
(-525, 625),
(-550, -10),
(520, -160),
(542.5, 475),
])
snap_geom = geom.snap()
stacked_data = np.zeros((16, 512,... | import numpy as np
from karabo_data.geometry2 import AGIPD_1MGeometry
def test_snap_assemble_data():
geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[
(-525, 625),
(-550, -10),
(520, -160),
(542.5, 475),
])
snap_geom = geom.snap()
stacked_data = np.zeros((16, 512,... | Add test of reading & writing CrystFEL geometry | Add test of reading & writing CrystFEL geometry
| Python | bsd-3-clause | European-XFEL/h5tools-py | import numpy as np
from karabo_data.geometry2 import AGIPD_1MGeometry
def test_snap_assemble_data():
geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[
(-525, 625),
(-550, -10),
(520, -160),
(542.5, 475),
])
snap_geom = geom.snap()
stack... | Add test of reading & writing CrystFEL geometry | ## Code Before:
import numpy as np
from karabo_data.geometry2 import AGIPD_1MGeometry
def test_snap_assemble_data():
geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[
(-525, 625),
(-550, -10),
(520, -160),
(542.5, 475),
])
snap_geom = geom.snap()
stacked_data = np... | import numpy as np
from karabo_data.geometry2 import AGIPD_1MGeometry
def test_snap_assemble_data():
geom = AGIPD_1MGeometry.from_quad_positions(quad_pos=[
(-525, 625),
(-550, -10),
(520, -160),
(542.5, 475),
])
snap_geom = geom.snap()
stack... |
8f1fd73d6a88436d24f936adec997f88ad7f1413 | neutron/tests/unit/objects/test_l3agent.py | neutron/tests/unit/objects/test_l3agent.py |
from neutron.objects import l3agent
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase):
_test_class = l3agent.RouterL3AgentBinding
class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObje... |
from neutron.objects import l3agent
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase):
_test_class = l3agent.RouterL3AgentBinding
class RouterL3AgentBindingDbObjTestCase(test_base.BaseDbObje... | Use unique binding_index for RouterL3AgentBinding | Use unique binding_index for RouterL3AgentBinding
This is because (router_id, binding_index) tuple is expected to be
unique, as per db model.
Closes-Bug: #1674434
Change-Id: I64fcee88f2ac942e6fa173644fbfb7655ea6041b
| Python | apache-2.0 | openstack/neutron,mahak/neutron,noironetworks/neutron,huntxu/neutron,eayunstack/neutron,openstack/neutron,huntxu/neutron,eayunstack/neutron,mahak/neutron,mahak/neutron,openstack/neutron,noironetworks/neutron |
from neutron.objects import l3agent
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase):
_test_class = l3agent.RouterL3AgentBinding
class RouterL3AgentBindingDbObjTestC... | Use unique binding_index for RouterL3AgentBinding | ## Code Before:
from neutron.objects import l3agent
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase):
_test_class = l3agent.RouterL3AgentBinding
class RouterL3AgentBindingDbObjTestCase(test... |
from neutron.objects import l3agent
from neutron.tests.unit.objects import test_base
from neutron.tests.unit import testlib_api
class RouterL3AgentBindingIfaceObjTestCase(test_base.BaseObjectIfaceTestCase):
_test_class = l3agent.RouterL3AgentBinding
class RouterL3AgentBindingDbObjTestC... |
c8ffd1fc4c4e06cd71e86d1d48749a3fe527a54e | biosys/apps/main/tests/api/test_serializers.py | biosys/apps/main/tests/api/test_serializers.py | from django.test import TestCase
from main.api.serializers import DatasetSerializer
from main.tests.api import helpers
class TestDatsetSerializer(helpers.BaseUserTestCase):
def test_name_uniqueness(self):
"""
Test that the serializer report an error if the dataset name is not unique within a pro... | from django.test import TestCase
from main.api.serializers import DatasetSerializer
from main.tests.api import helpers
class TestDatsetSerializer(helpers.BaseUserTestCase):
def test_name_uniqueness(self):
"""
Test that the serializer report an error if the dataset name is not unique within a pro... | Fix test to accommodate change of error message. | Fix test to accommodate change of error message.
| Python | apache-2.0 | gaiaresources/biosys,parksandwildlife/biosys,gaiaresources/biosys,serge-gaia/biosys,ropable/biosys,parksandwildlife/biosys,serge-gaia/biosys,ropable/biosys,gaiaresources/biosys,ropable/biosys,serge-gaia/biosys,parksandwildlife/biosys | from django.test import TestCase
from main.api.serializers import DatasetSerializer
from main.tests.api import helpers
class TestDatsetSerializer(helpers.BaseUserTestCase):
def test_name_uniqueness(self):
"""
Test that the serializer report an error if the dataset name is n... | Fix test to accommodate change of error message. | ## Code Before:
from django.test import TestCase
from main.api.serializers import DatasetSerializer
from main.tests.api import helpers
class TestDatsetSerializer(helpers.BaseUserTestCase):
def test_name_uniqueness(self):
"""
Test that the serializer report an error if the dataset name is not uni... | from django.test import TestCase
from main.api.serializers import DatasetSerializer
from main.tests.api import helpers
class TestDatsetSerializer(helpers.BaseUserTestCase):
def test_name_uniqueness(self):
"""
Test that the serializer report an error if the dataset name is n... |
ac209811feb25dfe9b5eac8b1488b42a8b5d73ba | kitsune/kbadge/migrations/0002_auto_20181023_1319.py | kitsune/kbadge/migrations/0002_auto_20181023_1319.py | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kbadge', '0001_initial'),
]
operations = [
migrations.RunSQL(
"UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'u... | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kbadge', '0001_initial'),
]
operations = [
migrations.RunSQL(
"UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE image NOT LIKE 'u... | Update SQL data migration to exclude NULL and blank image values. | Update SQL data migration to exclude NULL and blank image values.
| Python | bsd-3-clause | mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune,mozilla/kitsune,anushbmx/kitsune,anushbmx/kitsune,mozilla/kitsune | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kbadge', '0001_initial'),
]
operations = [
migrations.RunSQL(
- "UPDATE badger_badge SET image = CONCAT('uploads/', im... | Update SQL data migration to exclude NULL and blank image values. | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kbadge', '0001_initial'),
]
operations = [
migrations.RunSQL(
"UPDATE badger_badge SET image = CONCAT('uploads/', image) WHERE i... | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('kbadge', '0001_initial'),
]
operations = [
migrations.RunSQL(
- "UPDATE badger_badge SET image = CONCAT('uploads/', im... |
1ea6a0b43e4b05bdb743b0e2be86174062581d03 | errors.py | errors.py | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = 9
REPOSITORY_NOT_I... | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = 9
REPOSITORY_NOT_I... | Add a new error code | Add a new error code
| Python | lgpl-2.1 | mhl/gib,mhl/gib | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = ... | Add a new error code | ## Code Before:
class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = 9
... | class Errors:
'''enum-like values to use as exit codes'''
USAGE_ERROR = 1
DEPENDENCY_NOT_FOUND = 2
VERSION_ERROR = 3
GIT_CONFIG_ERROR = 4
STRANGE_ENVIRONMENT = 5
EATING_WITH_STAGED_CHANGES = 6
BAD_GIT_DIRECTORY = 7
BRANCH_EXISTS_ON_INIT = 8
NO_SUCH_BRANCH = ... |
c502ead77b9f82205eebdbf9863649160302a681 | scripts/generate_token.py | scripts/generate_token.py |
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write... |
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
sys.stderr.write... | Change to positional argument for generate-token | Change to positional argument for generate-token
| Python | mit | Proj-P/project-p-api,Proj-P/project-p-api |
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollbac... | Change to positional argument for generate-token | ## Code Before:
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollback()
... |
import argparse
import sys
from api import db
from api.tokens.models import Token
from sqlalchemy.exc import IntegrityError
def generate_token(name):
token = Token(name)
db.session.add(token)
try:
db.session.commit()
except IntegrityError:
db.session.rollbac... |
92d0a09cfb232270d04f82eccc451ee63bd7901a | dev/TOPSECRET/SirBot/lib/sirbot/shutdown.py | dev/TOPSECRET/SirBot/lib/sirbot/shutdown.py |
from json import dumps
def shutdown(config,interinput=None,interoutput=None):
#check for lingering runtime errors
#finishing writing log queues to file
#if none: write clean.start file in config directory
if(config['Interface']['remember position'] == 0):
config['Interface']['map'] = '620x540+... |
def shutdown(config,interinput,interoutput):
#check for lingering runtime errors
#finishing writing log queues to file
#if none: write clean.start file in config directory
pass
#perhaps add garbage collector control here?
| Revert "changes to config during runtime are now saved" | Revert "changes to config during runtime are now saved"
This reverts commit e09a780da17bb2f97d20aafc2c007fe3fc3051bb.
| Python | mit | SirRujak/SirBot |
- from json import dumps
-
- def shutdown(config,interinput=None,interoutput=None):
+ def shutdown(config,interinput,interoutput):
#check for lingering runtime errors
#finishing writing log queues to file
#if none: write clean.start file in config directory
+ pass
- if(config['Interface'][... | Revert "changes to config during runtime are now saved" | ## Code Before:
from json import dumps
def shutdown(config,interinput=None,interoutput=None):
#check for lingering runtime errors
#finishing writing log queues to file
#if none: write clean.start file in config directory
if(config['Interface']['remember position'] == 0):
config['Interface']['m... |
- from json import dumps
-
- def shutdown(config,interinput=None,interoutput=None):
? ----- -----
+ def shutdown(config,interinput,interoutput):
#check for lingering runtime errors
#finishing writing log queues to file
#if none: write clean.start file in c... |
2c5a1bebf805c9bf5208fc75c32d8998b865eb32 | designate/objects/zone_transfer_request.py | designate/objects/zone_transfer_request.py | from designate.objects import base
class ZoneTransferRequest(base.DictObjectMixin, base.DesignateObject,
base.PersistentObjectMixin):
FIELDS = {
'domain_id': {},
'key': {},
'description': {},
'tenant_id': {},
'target_tenant_id': {},
'status... | from designate.objects import base
class ZoneTransferRequest(base.DictObjectMixin, base.PersistentObjectMixin,
base.DesignateObject,):
FIELDS = {
'domain_id': {},
'key': {},
'description': {},
'tenant_id': {},
'target_tenant_id': {},
'statu... | Remove duplicate fields from ZoneTransferRequest object | Remove duplicate fields from ZoneTransferRequest object
The fields id, version, created_at, updated_at are defined in the
PersistentObjectMixin which ZoneTransferRequest extends, so this
patch removes them from ZoneTransferRequest.
Change-Id: Iff20a31b4a208bff0bc879677a9901fedc43226b
Closes-Bug: #1403274
| Python | apache-2.0 | kiall/designate-py3,muraliselva10/designate,openstack/designate,kiall/designate-py3,ramsateesh/designate,kiall/designate-py3,openstack/designate,muraliselva10/designate,cneill/designate,tonyli71/designate,cneill/designate,cneill/designate-testing,cneill/designate-testing,cneill/designate,tonyli71/designate,muraliselva1... | from designate.objects import base
- class ZoneTransferRequest(base.DictObjectMixin, base.DesignateObject,
+ class ZoneTransferRequest(base.DictObjectMixin, base.PersistentObjectMixin,
- base.PersistentObjectMixin):
+ base.DesignateObject,):
FIELDS = {
... | Remove duplicate fields from ZoneTransferRequest object | ## Code Before:
from designate.objects import base
class ZoneTransferRequest(base.DictObjectMixin, base.DesignateObject,
base.PersistentObjectMixin):
FIELDS = {
'domain_id': {},
'key': {},
'description': {},
'tenant_id': {},
'target_tenant_id': {},... | from designate.objects import base
- class ZoneTransferRequest(base.DictObjectMixin, base.DesignateObject,
? ^ ^^^
+ class ZoneTransferRequest(base.DictObjectMixin, base.PersistentObjectMixin,
? ^ + ^ ... |
3c4565dcf6222af0e3b7cabf5c52f9ab18488be2 | tests/test_main.py | tests/test_main.py | from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/audreyr/cookiecut... |
import pytest
from cookiecutter.main import is_repo_url, expand_abbreviations
@pytest.fixture(params=[
'gitolite@server:team/repo',
'git@github.com:audreyr/cookiecutter.git',
'https://github.com/audreyr/cookiecutter.git',
'https://bitbucket.org/pokoli/cookiecutter.hg',
])
def remote_repo_url(request... | Refactor tests for is_repo_url to be parametrized | Refactor tests for is_repo_url to be parametrized
| Python | bsd-3-clause | luzfcb/cookiecutter,terryjbates/cookiecutter,michaeljoseph/cookiecutter,willingc/cookiecutter,pjbull/cookiecutter,stevepiercy/cookiecutter,hackebrot/cookiecutter,dajose/cookiecutter,Springerle/cookiecutter,dajose/cookiecutter,stevepiercy/cookiecutter,terryjbates/cookiecutter,audreyr/cookiecutter,pjbull/cookiecutter,aud... | +
+ import pytest
+
from cookiecutter.main import is_repo_url, expand_abbreviations
- def test_is_repo_url():
+ @pytest.fixture(params=[
+ 'gitolite@server:team/repo',
+ 'git@github.com:audreyr/cookiecutter.git',
+ 'https://github.com/audreyr/cookiecutter.git',
+ 'https://bitbucket.org/pokoli/... | Refactor tests for is_repo_url to be parametrized | ## Code Before:
from cookiecutter.main import is_repo_url, expand_abbreviations
def test_is_repo_url():
"""Verify is_repo_url works."""
assert is_repo_url('gitolite@server:team/repo') is True
assert is_repo_url('git@github.com:audreyr/cookiecutter.git') is True
assert is_repo_url('https://github.com/a... | +
+ import pytest
+
from cookiecutter.main import is_repo_url, expand_abbreviations
- def test_is_repo_url():
+ @pytest.fixture(params=[
+ 'gitolite@server:team/repo',
+ 'git@github.com:audreyr/cookiecutter.git',
+ 'https://github.com/audreyr/cookiecutter.git',
+ 'https://bitbucket.org/pokoli/... |
9912974a283912acd31fa4ee85de2fb44c2cf862 | nn/model.py | nn/model.py | import abc
import tensorflow as tf
class Model(metaclass=abc.ABCMeta):
@abc.astractmethod
def __init__(self, **hyperparameters_and_initial_parameters):
return NotImplemented
@abc.astractmethod
def train(self, *input_tensors) -> tf.Tensor: # scalar loss
return NotImplemented
@abc.astractmethod
d... | import abc
import tensorflow as tf
class Model(metaclass=abc.ABCMeta):
@abc.astractmethod
def __init__(self, **hyperparameters_and_initial_parameters):
return NotImplemented
@abc.astractmethod
def train(self, *input_tensors) -> tf.Operation: # training operation
return NotImplemented
@abc.astract... | Fix type annotation for Model.train() | Fix type annotation for Model.train()
| Python | unlicense | raviqqe/tensorflow-extenteten,raviqqe/tensorflow-extenteten | import abc
import tensorflow as tf
class Model(metaclass=abc.ABCMeta):
@abc.astractmethod
def __init__(self, **hyperparameters_and_initial_parameters):
return NotImplemented
@abc.astractmethod
- def train(self, *input_tensors) -> tf.Tensor: # scalar loss
+ def train(self, *input_... | Fix type annotation for Model.train() | ## Code Before:
import abc
import tensorflow as tf
class Model(metaclass=abc.ABCMeta):
@abc.astractmethod
def __init__(self, **hyperparameters_and_initial_parameters):
return NotImplemented
@abc.astractmethod
def train(self, *input_tensors) -> tf.Tensor: # scalar loss
return NotImplemented
@abc.a... | import abc
import tensorflow as tf
class Model(metaclass=abc.ABCMeta):
@abc.astractmethod
def __init__(self, **hyperparameters_and_initial_parameters):
return NotImplemented
@abc.astractmethod
- def train(self, *input_tensors) -> tf.Tensor: # scalar loss
+ def train(self, *input_... |
7531fbb5cea5ef71f75e344c6a9e84e05377573a | jarn/mkrelease/process.py | jarn/mkrelease/process.py | import os
import tee
class Process(object):
"""Process related functions using the tee module (mostly)."""
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
if self.quiet:
echo = echo2 = False
... | import os
import tee
class Process(object):
"""Process related functions using the tee module (mostly)."""
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
if self.quiet:
echo = echo2 = False
... | Remove NotEmpty filter from Process.system. | Remove NotEmpty filter from Process.system.
| Python | bsd-2-clause | Jarn/jarn.mkrelease | import os
import tee
class Process(object):
"""Process related functions using the tee module (mostly)."""
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
if self.quiet:
... | Remove NotEmpty filter from Process.system. | ## Code Before:
import os
import tee
class Process(object):
"""Process related functions using the tee module (mostly)."""
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
if self.quiet:
echo = e... | import os
import tee
class Process(object):
"""Process related functions using the tee module (mostly)."""
def __init__(self, quiet=False, env=None):
self.quiet = quiet
self.env = env
def popen(self, cmd, echo=True, echo2=True):
if self.quiet:
... |
12352c1f7c9751727b8bd98ece576f9d690b520e | corehq/apps/export/migrations/0008_auto_20190906_2008.py | corehq/apps/export/migrations/0008_auto_20190906_2008.py | from __future__ import unicode_literals
from django.db import migrations
from corehq.apps.es.aggregations import (
AggregationTerm,
NestedTermAggregationsHelper,
)
from corehq.apps.es.ledgers import LedgerES
from corehq.apps.export.models.new import LedgerSectionEntry
from corehq.util.django_migrations import... | from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
"""
This migration used to contain some initialization for LedgerSectionEntry.
At the time it was run, this model was only used by exports and only on Supply projects
"""
dependencies... | Remove data migration from migration file | Remove data migration from migration file
| Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from __future__ import unicode_literals
from django.db import migrations
- from corehq.apps.es.aggregations import (
- AggregationTerm,
- NestedTermAggregationsHelper,
- )
- from corehq.apps.es.ledgers import LedgerES
- from corehq.apps.export.models.new import LedgerSectionEntry
- from corehq.util.dj... | Remove data migration from migration file | ## Code Before:
from __future__ import unicode_literals
from django.db import migrations
from corehq.apps.es.aggregations import (
AggregationTerm,
NestedTermAggregationsHelper,
)
from corehq.apps.es.ledgers import LedgerES
from corehq.apps.export.models.new import LedgerSectionEntry
from corehq.util.django_m... | from __future__ import unicode_literals
from django.db import migrations
- from corehq.apps.es.aggregations import (
- AggregationTerm,
- NestedTermAggregationsHelper,
- )
- from corehq.apps.es.ledgers import LedgerES
- from corehq.apps.export.models.new import LedgerSectionEntry
- from corehq.util.dj... |
eec24c2cff1b588b957215a867a85a148f4e71e9 | tuneme/views.py | tuneme/views.py | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from molo.core.models import ArticlePage
from molo.commenting.models import MoloComment
from wagtail.wagtailsearch.models import Query
def search(request, results_per_page=10):
search_query = request.GET.... | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from django.utils.translation import get_language_from_request
from molo.core.utils import get_locale_code
from molo.core.models import ArticlePage
from molo.commenting.models import MoloComment
from wagtail.wa... | Add multi-languages support for search | Add multi-languages support for search
| Python | bsd-2-clause | praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
+ from django.utils.translation import get_language_from_request
+ from molo.core.utils import get_locale_code
from molo.core.models import ArticlePage
from molo.commenting.models import MoloComment
... | Add multi-languages support for search | ## Code Before:
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
from molo.core.models import ArticlePage
from molo.commenting.models import MoloComment
from wagtail.wagtailsearch.models import Query
def search(request, results_per_page=10):
search_quer... | from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render
+ from django.utils.translation import get_language_from_request
+ from molo.core.utils import get_locale_code
from molo.core.models import ArticlePage
from molo.commenting.models import MoloComment
... |
37b8cf1af7818fe78b31ed25622f3f91805ade01 | test_bert_trainer.py | test_bert_trainer.py | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(str(int(time.time())))
... | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(str(int(time.time())))
... | Fix merge conflict in bert_trainer_example.py | Fix merge conflict in bert_trainer_example.py
| Python | apache-2.0 | googleinterns/smart-news-query-embeddings,googleinterns/smart-news-query-embeddings | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(... | Fix merge conflict in bert_trainer_example.py | ## Code Before:
import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(str(int(... | import unittest
import time
import shutil
import pandas as pd
from bert_trainer import BERTTrainer
from utils import *
class TestBERT(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(TestBERT, self).__init__(*args, **kwargs)
self.output_dir = 'test_{}'.format(... |
1223726c081000ef42a580881c9f8d2002d91c0b | src/hireme/tasks/__init__.py | src/hireme/tasks/__init__.py |
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_data
pa... |
from flask import render_template
from flask import request
def render_task(func):
"""Decorator for task solving functions. Provides raw form data from the
request and expects a string formatted return value."""
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if... | Add docstring, fix template param name | Add docstring, fix template param name
| Python | bsd-2-clause | cutoffthetop/hireme |
from flask import render_template
from flask import request
def render_task(func):
+ """Decorator for task solving functions. Provides raw form data from the
+ request and expects a string formatted return value."""
+
def rendered():
params = dict(title=func.__module__.split('.')... | Add docstring, fix template param name | ## Code Before:
from flask import render_template
from flask import request
def render_task(func):
def rendered():
params = dict(title=func.__module__.split('.')[-1] or '')
if request.method == 'POST':
input_data = request.form.get('input')
params['input_data'] = input_dat... |
from flask import render_template
from flask import request
def render_task(func):
+ """Decorator for task solving functions. Provides raw form data from the
+ request and expects a string formatted return value."""
+
def rendered():
params = dict(title=func.__module__.split('.')... |
d1a2a4c2ee7fda2bfde369bb6311719e72c75a3d | corehq/blobs/tasks.py | corehq/blobs/tasks.py | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic_task(run_every=crontab(... | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic_task(run_every=crontab(... | Delete expired blobs in batches | Delete expired blobs in batches | Python | bsd-3-clause | dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic... | Delete expired blobs in batches | ## Code Before:
from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic_task(ru... | from __future__ import absolute_import
from datetime import datetime
from celery.task import periodic_task
from celery.schedules import crontab
from corehq.util.datadog.gauges import datadog_counter
from corehq.blobs.models import BlobExpiration
from corehq.blobs import get_blob_db
@periodic... |
0947643977b989ca924bcf932a5153472e362108 | plata/utils.py | plata/utils.py | from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
setattr(obj, cache... | from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_... | Use DjangoJSONEncoder, it knows how to handle dates and decimals | JSONFieldDescriptor: Use DjangoJSONEncoder, it knows how to handle dates and decimals
| Python | bsd-3-clause | armicron/plata,stefanklug/plata,allink/plata,armicron/plata,armicron/plata | + from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if n... | Use DjangoJSONEncoder, it knows how to handle dates and decimals | ## Code Before:
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if not hasattr(obj, cache_field):
try:
se... | + from django.core.serializers.json import DjangoJSONEncoder
from django.utils import simplejson
class JSONFieldDescriptor(object):
def __init__(self, field):
self.field = field
def __get__(self, obj, objtype):
cache_field = '_cached_jsonfield_%s' % self.field
if n... |
ee4c8b806ecf0ada51916fe63f9da9e81c03850d | django_react_templatetags/tests/demosite/urls.py | django_react_templatetags/tests/demosite/urls.py | from django.urls import path
from django_react_templatetags.tests.demosite import views
urlpatterns = [
path(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
| from django.conf.urls import url
from django_react_templatetags.tests.demosite import views
urlpatterns = [
url(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
| Use url instead of path (to keep django 1 compat) | Use url instead of path (to keep django 1 compat)
| Python | mit | Frojd/django-react-templatetags,Frojd/django-react-templatetags,Frojd/django-react-templatetags | - from django.urls import path
+ from django.conf.urls import url
+
from django_react_templatetags.tests.demosite import views
urlpatterns = [
- path(
+ url(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
| Use url instead of path (to keep django 1 compat) | ## Code Before:
from django.urls import path
from django_react_templatetags.tests.demosite import views
urlpatterns = [
path(
'static-react-view',
views.StaticReactView.as_view(),
name='static_react_view',
),
]
## Instruction:
Use url instead of path (to keep django 1 compat)
## Code... | - from django.urls import path
? ^^^^
+ from django.conf.urls import url
? +++++ ^^^
+
from django_react_templatetags.tests.demosite import views
urlpatterns = [
- path(
+ url(
'static-react-view',
views.StaticReactView.as_view()... |
fcde79c7743b621be31acc4bd4e5826b121d573d | nalaf/download_corpora.py | nalaf/download_corpora.py | if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus) | if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
download(corpus)
| Fix a build for travis-CI | Fix a build for travis-CI
| Python | apache-2.0 | Rostlab/nalaf | if __name__ == '__main__':
- import nltk
+ from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
- nltk.download(corpus)
+ download(corpus)
+ | Fix a build for travis-CI | ## Code Before:
if __name__ == '__main__':
import nltk
CORPORA = ['punkt']
for corpus in CORPORA:
nltk.download(corpus)
## Instruction:
Fix a build for travis-CI
## Code After:
if __name__ == '__main__':
from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
dow... | if __name__ == '__main__':
- import nltk
+ from nltk import download
CORPORA = ['punkt']
for corpus in CORPORA:
- nltk.download(corpus)
? -----
+ download(corpus) |
6ec7465b5ec96b44e82cae9db58d6529e60ff920 | tests/linters/test_lint_nwod.py | tests/linters/test_lint_nwod.py | import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwod.lint_vice_virtue(char_file.read())
assert 'Missing virtue' not in problem... | """Tests the helpers for linting generic nwod characters"""
import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwod.lint_vice_virtue(cha... | Add doc comment to nwod lint tests | Add doc comment to nwod lint tests
| Python | mit | aurule/npc,aurule/npc | + """Tests the helpers for linting generic nwod characters"""
+
import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwo... | Add doc comment to nwod lint tests | ## Code Before:
import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwod.lint_vice_virtue(char_file.read())
assert 'Missing virtue... | + """Tests the helpers for linting generic nwod characters"""
+
import npc
import pytest
import os
from tests.util import fixture_dir
def test_has_virtue():
char_file = fixture_dir('linter', 'nwod', 'Has Virtue.nwod')
with open(char_file, 'r') as char_file:
problems = npc.linters.nwo... |
3ddddbd24bb37c30df80233ec4c70c38b6c29e82 | emstrack/forms.py | emstrack/forms.py | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdnjs.cloudflare.com/ajax/libs/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css',
... | Update leaflet request to be over https | Update leaflet request to be over https
| Python | bsd-3-clause | EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient,EMSTrack/WebServerAndClient | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
- 'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
+ 'all': ('https://cdnjs.cloudflare.com... | Update leaflet request to be over https | ## Code Before:
from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
'leaflet/css/location_form.css'... | from django.contrib.gis.forms import widgets
class LeafletPointWidget(widgets.BaseGeometryWidget):
template_name = 'leaflet/leaflet.html'
class Media:
css = {
- 'all': ('https://cdn.leafletjs.com/leaflet/v0.7.7/leaflet.css',
? --------
+ ... |
78a03f0b0cbc948a6c9fb215e9051d099c528a82 | src/app.py | src/app.py | from flask import Flask
from flask import render_template, url_for
import parse_data
app = Flask(__name__)
@app.route("/dashboard")
def dashboard():
data = parse_data.load_and_format_data()
title = 'Grand Bargain Monitoring'
return render_template('dashboard.html', data=data, heading=title, page_title... | from flask import Flask
from flask import render_template, url_for
import parse_data
app = Flask(__name__)
@app.route("/dashboard")
def dashboard():
data = parse_data.load_and_format_data()
title = 'Grand Bargain Transparency Dashboard'
return render_template('dashboard.html', data=data, heading=title... | Change page title and heading | Change page title and heading
| Python | mit | devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring,devinit/grand-bargain-monitoring | from flask import Flask
from flask import render_template, url_for
import parse_data
app = Flask(__name__)
@app.route("/dashboard")
def dashboard():
data = parse_data.load_and_format_data()
- title = 'Grand Bargain Monitoring'
+ title = 'Grand Bargain Transparency Dashboard'
... | Change page title and heading | ## Code Before:
from flask import Flask
from flask import render_template, url_for
import parse_data
app = Flask(__name__)
@app.route("/dashboard")
def dashboard():
data = parse_data.load_and_format_data()
title = 'Grand Bargain Monitoring'
return render_template('dashboard.html', data=data, heading=t... | from flask import Flask
from flask import render_template, url_for
import parse_data
app = Flask(__name__)
@app.route("/dashboard")
def dashboard():
data = parse_data.load_and_format_data()
- title = 'Grand Bargain Monitoring'
+ title = 'Grand Bargain Transparency Dashboard'
... |
08b998d63808b99cf96635bd50b7d33238cda633 | Recorders.py | Recorders.py | from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'file')
self.form... | import os
from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'file')
... | Create folder if not exist | Create folder if not exist
| Python | mit | hectortosa/py-temperature-recorder | + import os
from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__ini... | Create folder if not exist | ## Code Before:
from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__init__(self, 'file')
... | + import os
from Measurement import Measurement
class Recorder(object):
def __init__(self, recorderType):
self.recorderType = recorderType
def record(self, measure: Measurement):
None
class PrintRecorder(Recorder):
def __init__(self, config):
Recorder.__ini... |
5d57c43ba7a01dc0f94ab41e4014484d1b78c1cb | django_polymorphic_auth/admin.py | django_polymorphic_auth/admin.py | from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
PolymorphicParentModelAdmi... | from django.conf import settings
from django.contrib import admin
from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from poly... | Integrate `UserChangeForm` so we get nice password fields. | Integrate `UserChangeForm` so we get nice password fields.
| Python | mit | whembed197923/django-polymorphic-auth,ixc/django-polymorphic-auth | from django.conf import settings
from django.contrib import admin
+ from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUs... | Integrate `UserChangeForm` so we get nice password fields. | ## Code Before:
from django.conf import settings
from django.contrib import admin
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUser
from polymorphic.admin import \
Polymorphi... | from django.conf import settings
from django.contrib import admin
+ from django.contrib.auth.forms import UserChangeForm
from django_polymorphic_auth.models import User
from django_polymorphic_auth.usertypes.email.models import EmailUser
from django_polymorphic_auth.usertypes.username.models import UsernameUs... |
fc70feec85f0b22ebef05b0fa1316214a48a465a | background/config/prod.py | background/config/prod.py | from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
| from decouple import config
from .base import BaseCeleryConfig
REDIS_URL = config('REDIS_URL')
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL',
default=REDIS_URL)
result_backend = ... | Use REDIS_URL by default for Celery | Use REDIS_URL by default for Celery
| Python | mit | RaitoBezarius/ryuzu-fb-bot | from decouple import config
from .base import BaseCeleryConfig
+ REDIS_URL = config('REDIS_URL')
+
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
- broker_url = config('CELERY_BROKER_URL')
+ broker_url = config('CELERY_BROKER_URL... | Use REDIS_URL by default for Celery | ## Code Before:
from decouple import config
from .base import BaseCeleryConfig
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
broker_url = config('CELERY_BROKER_URL')
result_backend = config('CELERY_RESULT_BACKEND')
## Instruction:
Use REDIS_U... | from decouple import config
from .base import BaseCeleryConfig
+ REDIS_URL = config('REDIS_URL')
+
class CeleryProduction(BaseCeleryConfig):
enable_utc = config('CELERY_ENABLE_UTC', default=True, cast=bool)
- broker_url = config('CELERY_BROKER_URL')
? ... |
f3ad7f31784ea35da8655efa97ad3dd102e6dddb | django_bundles/management/commands/create_bundle_manifests.py | django_bundles/management/commands/create_bundle_manifests.py | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
class Command(BaseCommand):
args = "target_directory"
help = "Writes out files containing the list of input files for each bundle"
requires_model_validation = False
def handle(self, target_dire... | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
from django_bundles.processors import processor_pipeline
from django_bundles.utils.files import FileChunkGenerator
class Command(BaseCommand):
args = "target_directory"
help = "Writes out files containi... | Create processed versions of files for manifests | Create processed versions of files for manifests
This means if we have resources which are processed by django templates
then the processing will be done first and thus will yield for example a
valid javascript file
| Python | mit | sdcooke/django_bundles | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
+ from django_bundles.processors import processor_pipeline
+ from django_bundles.utils.files import FileChunkGenerator
class Command(BaseCommand):
args = "target_directory"
help = "W... | Create processed versions of files for manifests | ## Code Before:
import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
class Command(BaseCommand):
args = "target_directory"
help = "Writes out files containing the list of input files for each bundle"
requires_model_validation = False
def handle(s... | import os
from django.core.management.base import BaseCommand
from django_bundles.core import get_bundles
+ from django_bundles.processors import processor_pipeline
+ from django_bundles.utils.files import FileChunkGenerator
class Command(BaseCommand):
args = "target_directory"
help = "W... |
6903f63e76ac5e7686ae55348225d06e3757a64b | giphy_magic.py | giphy_magic.py | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r = requests.get(... | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
RANDOM_ON_NO_MATCH = False
def get_params(tag):
params = {'api_key': API_KEY}
if tag is not None... | Add a constant that determines the response when no results are found | Add a constant that determines the response when no results are found
| Python | mit | AustinRochford/giphy-ipython-magic,AustinRochford/giphy-ipython-magic | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
+ RANDOM_ON_NO_MATCH = False
+
+ def get_params(tag):
+ params = {'api_key': API_KE... | Add a constant that determines the response when no results are found | ## Code Before:
from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
def giphy(tag):
params = {
'api_key': API_KEY,
'tag': tag
}
r... | from IPython.display import Image
import requests
API_ENDPOINT = 'http://api.giphy.com/v1/gifs/random'
# This is the Giphy API's public beta key, see https://github.com/Giphy/GiphyAPI
API_KEY = 'dc6zaTOxFJmzC'
+ RANDOM_ON_NO_MATCH = False
+
+ def get_params(tag):
+ params = {'api_key': API_KE... |
18998011bb52616a3002ca298a64ea61c5727a76 | skeleton/website/jasyscript.py | skeleton/website/jasyscript.py | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
| import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
assetManager = AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
# Copy ... | Copy used assets to output path | Copy used assets to output path
| Python | mit | fastner/konstrukteur,fastner/konstrukteur,fastner/konstrukteur | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
- AssetManager.AssetManager(profile, session)
+ assetManager = AssetManager.AssetManager(profile, session)
# Build ... | Copy used assets to output path | ## Code Before:
import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
AssetManager.AssetManager(profile, session)
# Build static website
konstrukteur.Konstrukteur.build(regenerate)
## Inst... | import konstrukteur.Konstrukteur
import jasy.asset.Manager2 as AssetManager
@task
def build(regenerate = False):
"""Generate source (development) version"""
# Initialize assets
- AssetManager.AssetManager(profile, session)
+ assetManager = AssetManager.AssetManager(profile, session)
? +++++++++++... |
8aceb4bcfeef05874bbd6eec66eeb7b69f20f02e | pinax/blog/templatetags/pinax_blog_tags.py | pinax/blog/templatetags/pinax_blog_tags.py | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
qs = qs.filter(scoper=scoper)
return qs[:5]
@register.assignment_tag
def latest_blog_post(scoper=Non... | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
qs = qs.filter(blog__scoper=scoper)
return qs[:5]
@register.assignment_tag
def latest_blog_post(scop... | Fix small bug in templatetags | Fix small bug in templatetags
| Python | mit | pinax/pinax-blog,pinax/pinax-blog,pinax/pinax-blog | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
- qs = qs.filter(scoper=scoper)
+ qs = qs.filter(blog__scoper=scoper)
... | Fix small bug in templatetags | ## Code Before:
from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
qs = qs.filter(scoper=scoper)
return qs[:5]
@register.assignment_tag
def latest_blog... | from django import template
from ..models import Post, Section
register = template.Library()
@register.assignment_tag
def latest_blog_posts(scoper=None):
qs = Post.objects.current()
if scoper:
- qs = qs.filter(scoper=scoper)
+ qs = qs.filter(blog__scoper=scoper)
? ... |
a260020f10b4d993635e579c8b130e754c49f7aa | dogebuild/dogefile_loader.py | dogebuild/dogefile_loader.py | from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHolder.create()
exec(code)
return ContextHolder.clear_and_get()
| import os
from pathlib import Path
from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
dir = Path(filename).resolve().parent
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHolder.create()
cwd =... | Add cirectoy switch on loading | Add cirectoy switch on loading
| Python | mit | dogebuild/dogebuild | + import os
+ from pathlib import Path
+
from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
+ dir = Path(filename).resolve().parent
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHol... | Add cirectoy switch on loading | ## Code Before:
from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHolder.create()
exec(code)
return ContextHolder.clear_and_get()
## Instruc... | + import os
+ from pathlib import Path
+
from dogebuild.plugins import ContextHolder
from dogebuild.common import DOGE_FILE
def load_doge_file(filename):
+ dir = Path(filename).resolve().parent
with open(filename) as f:
code = compile(f.read(), DOGE_FILE, 'exec')
ContextHol... |
791e03258c53379dde587a4bf0c05e0d2bc053ad | test_tbselenium.py | test_tbselenium.py |
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https://check.torproje... |
import os
import site
site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
home_dir = os.path.expanduser('~')
tbb_path = os.path.join(home_dir, 'tbb', 'tor-browser_en-US')
tbb_fx_path = os.path.join(tbb_path, 'Browser', 'firefox')
tbb_profile_path = os.pa... | Fix test to work with patched tbdriver.py (see NOTICE in diff) | Fix test to work with patched tbdriver.py (see NOTICE in diff)
| Python | agpl-3.0 | freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop,freedomofpress/FingerprintSecureDrop,freedomofpress/fingerprint-securedrop |
import os
import site
- import sys
- sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
- # site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
+ site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
- with TorBrowserDriv... | Fix test to work with patched tbdriver.py (see NOTICE in diff) | ## Code Before:
import os
import site
import sys
sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
# site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
from tbselenium.tbdriver import TorBrowserDriver
with TorBrowserDriver('~/.tb-stable/tor-browser_en-US/') as driver:
driver.get('https:... |
import os
import site
- import sys
- sys.path.append(os.path.join(os.getcwd(), 'tor-browser-selenium'))
- # site.addsitedir(path.join(getcwd(), 'tor-browser-selenium'))
? --
+ site.addsitedir(os.path.join(os.getcwd(), 'tor-browser-selenium'))
? +++ +++
from tbselenium.tbdriver import... |
18d973d71255d389369cc4450f721512a13ad6cb | src/impl/geocoder.py | src/impl/geocoder.py | import geopy
from rate_limiter import RateLimiter
class Geocoder(object):
def __init__(self, api_key=None, client_id=None, secret_key=None):
if api_key:
self._geolocator = geopy.GoogleV3(api_key=api_key)
elif client_id and secret_key:
self._geolocator = geopy.GoogleV3(clie... | from Geohash import geohash
import geopy
from rate_limiter import RateLimiter
class Geocoder(object):
def __init__(self, api_key=None, client_id=None, secret_key=None, reverse_cache_geohash=9):
if api_key:
self._geolocator = geopy.GoogleV3(api_key=api_key)
elif client_id and secret_ke... | Add in-memory geohash cache for reverse geocoding. | Add in-memory geohash cache for reverse geocoding.
| Python | mit | cbigler/jackrabbit-googlev3-geocoder | + from Geohash import geohash
import geopy
from rate_limiter import RateLimiter
class Geocoder(object):
- def __init__(self, api_key=None, client_id=None, secret_key=None):
+ def __init__(self, api_key=None, client_id=None, secret_key=None, reverse_cache_geohash=9):
if api_key:
... | Add in-memory geohash cache for reverse geocoding. | ## Code Before:
import geopy
from rate_limiter import RateLimiter
class Geocoder(object):
def __init__(self, api_key=None, client_id=None, secret_key=None):
if api_key:
self._geolocator = geopy.GoogleV3(api_key=api_key)
elif client_id and secret_key:
self._geolocator = geo... | + from Geohash import geohash
import geopy
from rate_limiter import RateLimiter
class Geocoder(object):
- def __init__(self, api_key=None, client_id=None, secret_key=None):
+ def __init__(self, api_key=None, client_id=None, secret_key=None, reverse_cache_geohash=9):
? ... |
fb82b4f77379ddd1525947cc61f1c46c34674da4 | froide/publicbody/admin.py | froide/publicbody/admin.py | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
list_filter = ('... | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
list_filter = ('... | Add list filter by jurisdiction for public bodies | Add list filter by jurisdiction for public bodies | Python | mit | LilithWittmann/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,okfse/froide,stefanw/froide,ryankanno/froide,okfse/froide,stefanw/froide,catcosmo/froide,fin/froide,ryankanno/froide,CodeforHawaii/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,okfse/froide,okfse/froide,LilithWittmann/froide,fin/f... | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
- ... | Add list filter by jurisdiction for public bodies | ## Code Before:
from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
... | from django.contrib import admin
from froide.publicbody.models import (PublicBody, FoiLaw, PublicBodyTopic,
Jurisdiction)
class PublicBodyAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("name",)}
list_display = ('name', 'email', 'url', 'classification', 'topic', 'depth',)
- ... |
7420d9208067f5144b301ff00d962b0b84e2a0f3 | tinymce/settings.py | tinymce/settings.py | import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBROWSER = getattr(s... | import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBROWSER = getattr(s... | Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3) | Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3)
| Python | mit | pterk/django-tinymce,pterk/django-tinymce | import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_F... | Use STATIC_URL/STATIC_ROOT when using django.contrib.staticfiles (django 1.3) | ## Code Before:
import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_FILEBRO... | import os
from django.conf import settings
DEFAULT_CONFIG = getattr(settings, 'TINYMCE_DEFAULT_CONFIG',
{'theme': "simple", 'relative_urls': False})
USE_SPELLCHECKER = getattr(settings, 'TINYMCE_SPELLCHECKER', False)
USE_COMPRESSOR = getattr(settings, 'TINYMCE_COMPRESSOR', False)
USE_F... |
34c427200c6ab50fb64fa0d6116366a8fa9186a3 | netman/core/objects/bond.py | netman/core/objects/bond.py |
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = members or []
| import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = ... | Support deprecated use of the interface property of Bond. | Support deprecated use of the interface property of Bond.
| Python | apache-2.0 | idjaw/netman,internaphosting/netman,internap/netman,godp1301/netman,mat128/netman,lindycoder/netman | + import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
... | Support deprecated use of the interface property of Bond. | ## Code Before:
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
self.members = ... | + import warnings
from netman.core.objects.interface import BaseInterface
class Bond(BaseInterface):
def __init__(self, number=None, link_speed=None, members=None, **interface):
super(Bond, self).__init__(**interface)
self.number = number
self.link_speed = link_speed
... |
5d35b947719106b7af67e4da92eaa4db0e5a6948 | doc/examples/plot_tutorial_example.py | doc/examples/plot_tutorial_example.py | import numpy as np
import matplotlib.pyplot as plt
'normal string'
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
"""
.. image:: PLOT2RST.current_figure
Here's an image plot:
"""
# code comment
plt.figure()
plt.imshow(np.random.random(size=(20, 20)))
"""
.. image:: PLOT2RST.current_figure
# docstring comment
... | import numpy as np
import matplotlib.pyplot as plt
'normal string'
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
def dummy():
"""Dummy docstring"""
pass
"""
.. image:: PLOT2RST.current_figure
Here's an image plot:
"""
# code comment
plt.figure()
plt.imshow(np.random.random(size=(20, 20)))
"""
.. imag... | Make plot2rst example more strict. | DOC: Make plot2rst example more strict.
| Python | bsd-3-clause | matteoicardi/mpltools,tonysyu/mpltools | import numpy as np
import matplotlib.pyplot as plt
'normal string'
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
+
+ def dummy():
+ """Dummy docstring"""
+ pass
"""
.. image:: PLOT2RST.current_figure
Here's an image plot:
"""
# code comment
plt.figure()
plt.imshow(np.ra... | Make plot2rst example more strict. | ## Code Before:
import numpy as np
import matplotlib.pyplot as plt
'normal string'
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
"""
.. image:: PLOT2RST.current_figure
Here's an image plot:
"""
# code comment
plt.figure()
plt.imshow(np.random.random(size=(20, 20)))
"""
.. image:: PLOT2RST.current_figure
# do... | import numpy as np
import matplotlib.pyplot as plt
'normal string'
x = np.linspace(0, 2*np.pi)
plt.plot(x, np.sin(x))
+
+ def dummy():
+ """Dummy docstring"""
+ pass
"""
.. image:: PLOT2RST.current_figure
Here's an image plot:
"""
# code comment
plt.figure()
plt.imshow(np.ra... |
12096f2961f72e250e16b168c053e89277e442a5 | test.py | test.py | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]),
pyte.tokens.RETURN_VALUE... | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
bc = [pyte.ops.CALL_FUNCTION(names[0], consts[1]),
pyte.ops.END_FUNCTION(con... | Add instruction for returning a value | Add instruction for returning a value
| Python | mit | SunDwarf/Pyte | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
- bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]),
+ bc... | Add instruction for returning a value | ## Code Before:
import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]),
pyte.tok... | import dis
import time
import pyte
# Create a new consts value.
consts = pyte.create_consts(None, "Hello, world!")
# New varnames values
varnames = pyte.create_varnames()
# Create names (for globals)
names = pyte.create_names("print")
- bc = [pyte.call.CALL_FUNCTION(names[0], consts[1]),
? ... |
c91e494f16301789f2ebcc9c245697b379b30eca | irco/explorer/filters.py | irco/explorer/filters.py | import csv
import collections
from StringIO import StringIO
from flask import render_template
from jinja2 import Markup
def init_app(app):
@app.template_filter('format_record')
def format_record(record):
val = record.unparsed_record_value
if 'csv' in record.unparsed_record_format:
... | import csv
import collections
from StringIO import StringIO
from flask import render_template
from jinja2 import Markup
def init_app(app):
@app.template_filter('format_record')
def format_record(record):
val = record.unparsed_record_value
fmt_csv = 'csv' in record.unparsed_record_format
... | Add support to render tsp data in the explorer. | Add support to render tsp data in the explorer.
| Python | mit | GaretJax/irco,GaretJax/irco,GaretJax/irco,GaretJax/irco | import csv
import collections
from StringIO import StringIO
from flask import render_template
from jinja2 import Markup
def init_app(app):
@app.template_filter('format_record')
def format_record(record):
val = record.unparsed_record_value
+
- if 'csv' in record.unpars... | Add support to render tsp data in the explorer. | ## Code Before:
import csv
import collections
from StringIO import StringIO
from flask import render_template
from jinja2 import Markup
def init_app(app):
@app.template_filter('format_record')
def format_record(record):
val = record.unparsed_record_value
if 'csv' in record.unparsed_record_for... | import csv
import collections
from StringIO import StringIO
from flask import render_template
from jinja2 import Markup
def init_app(app):
@app.template_filter('format_record')
def format_record(record):
val = record.unparsed_record_value
+
- if 'csv' in record.unpars... |
540493a69ff2e9a5e6cc93a75b34af3c9f79b808 | plugins/generic/syntax.py | plugins/generic/syntax.py |
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVal = expression
if quote... |
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVal = expression
if quote... | Fix for empty strings (previously '' was just removed) | Fix for empty strings (previously '' was just removed)
| Python | apache-2.0 | RexGene/monsu-server,RexGene/monsu-server,dtrip/.ubuntu,dtrip/.ubuntu |
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVa... | Fix for empty strings (previously '' was just removed) | ## Code Before:
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVal = expression
... |
import re
from lib.core.exception import SqlmapUndefinedMethod
class Syntax:
"""
This class defines generic syntax functionalities for plugins.
"""
def __init__(self):
pass
@staticmethod
def _escape(expression, quote=True, escaper=None):
retVa... |
75171ed80079630d22463685768072ad7323e653 | boundary/action_installed.py | boundary/action_installed.py | from api_cli import ApiCli
class ActionInstalled (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/actions/installed"
def getDescription(self):
return "Returns the actions associated with the Boundary account"
| from api_cli import ApiCli
class ActionInstalled (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/actions/installed"
def getDescription(self):
return "Returns the actions configured within a Boundary account"
| Change code to be PEP-8 compliant | Change code to be PEP-8 compliant
| Python | apache-2.0 | boundary/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/boundary-api-cli,jdgwartney/pulse-api-cli,wcainboundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/pulse-api-cli | from api_cli import ApiCli
class ActionInstalled (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/actions/installed"
def getDescription(self):
- return "Returns the actions associated with the Bou... | Change code to be PEP-8 compliant | ## Code Before:
from api_cli import ApiCli
class ActionInstalled (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/actions/installed"
def getDescription(self):
return "Returns the actions associated with the Boundary ... | from api_cli import ApiCli
class ActionInstalled (ApiCli):
def __init__(self):
ApiCli.__init__(self)
self.method = "GET"
self.path = "v1/actions/installed"
def getDescription(self):
- return "Returns the actions associated with the Bou... |
97c25703904a0f2508238d4268259692f9e7a665 | test/integration/ggrc/converters/test_import_automappings.py | test/integration/ggrc/converters/test_import_automappings.py |
from ggrc.models import Relationship
from ggrc.converters import errors
from integration.ggrc.converters import TestCase
from integration.ggrc.generator import ObjectGenerator
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.generator = ObjectGenerator()
self.client.get("... |
from integration.ggrc.converters import TestCase
from integration.ggrc.generator import ObjectGenerator
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.generator = ObjectGenerator()
self.client.get("/login")
def test_basic_automappings(self):
filename = "automappi... | Clean up import auto mappings tests | Clean up import auto mappings tests
| Python | apache-2.0 | edofic/ggrc-core,josthkko/ggrc-core,andrei-karalionak/ggrc-core,kr41/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,plamut/ggrc-core,VinnieJohns/ggrc-core,j0gurt/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,AleksNeStu/ggrc-core,andrei-karalionak/ggrc-core,edofi... |
- from ggrc.models import Relationship
- from ggrc.converters import errors
from integration.ggrc.converters import TestCase
from integration.ggrc.generator import ObjectGenerator
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.generator = ObjectGenerator... | Clean up import auto mappings tests | ## Code Before:
from ggrc.models import Relationship
from ggrc.converters import errors
from integration.ggrc.converters import TestCase
from integration.ggrc.generator import ObjectGenerator
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.generator = ObjectGenerator()
s... |
- from ggrc.models import Relationship
- from ggrc.converters import errors
from integration.ggrc.converters import TestCase
from integration.ggrc.generator import ObjectGenerator
class TestBasicCsvImport(TestCase):
def setUp(self):
TestCase.setUp(self)
self.generator = ObjectGenerator... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.