Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
b457eac63690deba408c4b5bdc1db179347f43da
postgres/fields/uuid_field.py
postgres/fields/uuid_field.py
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(mode...
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.with_metaclass(mode...
Make UUIDField have a fixed max-length
Make UUIDField have a fixed max-length
Python
bsd-3-clause
wlanslovenija/django-postgres
from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUI...
Make UUIDField have a fixed max-length
## Code Before: from __future__ import unicode_literals import uuid from django.core.exceptions import ValidationError from django.db import models from django.utils import six from django.utils.translation import ugettext_lazy as _ from psycopg2.extras import register_uuid register_uuid() class UUIDField(six.wit...
89fe38163426efe02da92974bac369538ab5532f
elmextensions/__init__.py
elmextensions/__init__.py
from .sortedlist import * from .embeddedterminal import * from .aboutwindow import * from .fileselector import * from .tabbedbox import * from .StandardButton import * from .StandardPopup import * from .SearchableList import *
from .sortedlist import * from .embeddedterminal import * from .aboutwindow import * from .fileselector import * from .fontselector import * from .tabbedbox import * from .StandardButton import * from .StandardPopup import * from .SearchableList import * __copyright__ = "Copyright 2015-2017 Jeff Hoogland" __license__...
Access to module level information
Access to module level information
Python
bsd-3-clause
JeffHoogland/python-elm-extensions
from .sortedlist import * from .embeddedterminal import * from .aboutwindow import * from .fileselector import * + from .fontselector import * from .tabbedbox import * from .StandardButton import * from .StandardPopup import * from .SearchableList import * + __copyright__ = "Copyright 2015-2017 Jeff...
Access to module level information
## Code Before: from .sortedlist import * from .embeddedterminal import * from .aboutwindow import * from .fileselector import * from .tabbedbox import * from .StandardButton import * from .StandardPopup import * from .SearchableList import * ## Instruction: Access to module level information ## Code After: from .sort...
f517442097b6ae12eb13b16f2fa6ca40a00b9998
__init__.py
__init__.py
from .features import Giraffe_Feature_Base from .features import Aligned_Feature
from .features import Giraffe_Feature_Base from .features import Aligned_Feature from .features import Feature_Type_Choices
Move Feature_Type_Choices to toplevel name sapce
Move Feature_Type_Choices to toplevel name sapce
Python
mit
benjiec/giraffe-features
from .features import Giraffe_Feature_Base from .features import Aligned_Feature + from .features import Feature_Type_Choices
Move Feature_Type_Choices to toplevel name sapce
## Code Before: from .features import Giraffe_Feature_Base from .features import Aligned_Feature ## Instruction: Move Feature_Type_Choices to toplevel name sapce ## Code After: from .features import Giraffe_Feature_Base from .features import Aligned_Feature from .features import Feature_Type_Choices
5a8788222d9a5765bf66a2c93eed25ca7879c856
__init__.py
__init__.py
import inspect import sys if sys.version_info[0] == 2: from .python2 import httplib2 else: from .python3 import httplib2 globals().update(inspect.getmembers(httplib2))
import os import sys path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0]) sys.path.insert(0, path) del sys.modules['httplib2'] import httplib2
Rewrite python version dependent import
Rewrite python version dependent import The top level of this external includes a __init__.py so that it may be imported with only 'externals' in sys.path. However it copies the contents of the python version dependent httplib2 code, resulting in module level variables appearing in two different namespaces. As a res...
Python
mit
jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2,jayvdb/httplib2,wikimedia/pywikibot-externals-httplib2
- import inspect + import os import sys - if sys.version_info[0] == 2: - from .python2 import httplib2 - else: - from .python3 import httplib2 - globals().update(inspect.getmembers(httplib2)) + path = os.path.dirname(__file__)+os.path.sep+'python'+str(sys.version_info[0]) + sys.path.insert(0, path) + del s...
Rewrite python version dependent import
## Code Before: import inspect import sys if sys.version_info[0] == 2: from .python2 import httplib2 else: from .python3 import httplib2 globals().update(inspect.getmembers(httplib2)) ## Instruction: Rewrite python version dependent import ## Code After: import os import sys path = os.path.dirname(__file__)+o...
01c5b53ba16a95ab77918d30dfa3a63f2ef2707f
var/spack/repos/builtin/packages/libxcb/package.py
var/spack/repos/builtin/packages/libxcb/package.py
from spack import * class Libxcb(Package): """The X protocol C-language Binding (XCB) is a replacement for Xlib featuring a small footprint, latency hiding, direct access to the protocol, improved threading support, and extensibility.""" homepage = "http://xcb.freedesktop.org/" url = "...
from spack import * class Libxcb(Package): """The X protocol C-language Binding (XCB) is a replacement for Xlib featuring a small footprint, latency hiding, direct access to the protocol, improved threading support, and extensibility.""" homepage = "http://xcb.freedesktop.org/" url = "htt...
Make libxcb compile with gcc 4.9.
Make libxcb compile with gcc 4.9.
Python
lgpl-2.1
krafczyk/spack,krafczyk/spack,mfherbst/spack,skosukhin/spack,tmerrick1/spack,iulian787/spack,EmreAtes/spack,lgarren/spack,EmreAtes/spack,matthiasdiener/spack,lgarren/spack,TheTimmy/spack,LLNL/spack,mfherbst/spack,lgarren/spack,iulian787/spack,skosukhin/spack,LLNL/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,matthias...
from spack import * class Libxcb(Package): - """The X protocol C-language Binding (XCB) is a replacement + """The X protocol C-language Binding (XCB) is a replacement - for Xlib featuring a small footprint, latency hiding, direct + for Xlib featuring a small footprint, latency hiding, direct - ...
Make libxcb compile with gcc 4.9.
## Code Before: from spack import * class Libxcb(Package): """The X protocol C-language Binding (XCB) is a replacement for Xlib featuring a small footprint, latency hiding, direct access to the protocol, improved threading support, and extensibility.""" homepage = "http://xcb.freedesktop.org/" ...
42f5b2c53474f20fbffbc0b8cdaa4e5b47a4751d
app/wsgi.py
app/wsgi.py
try: from gevent.monkey import patch_all patch_all() except ImportError: print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.environ.get('SENTRY_DSN'): from raven.contrib.flask import Sentry sentry = Sent...
import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.environ.get('SENTRY_DSN'): from raven.contrib.flask import Sentry sentry = Sentry() sentry.init_app(application) application.wsgi_app = ProxyFix(application.wsgi_app)
Comment out gevent until we need it
Comment out gevent until we need it
Python
mit
spacedogXYZ/email-validator,spacedogXYZ/email-validator,spacedogXYZ/email-validator
- try: - from gevent.monkey import patch_all - patch_all() - except ImportError: - print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.environ.get('SENTRY_DSN'): from raven.contrib.flask imp...
Comment out gevent until we need it
## Code Before: try: from gevent.monkey import patch_all patch_all() except ImportError: print "unable to apply gevent monkey.patch_all" import os from werkzeug.contrib.fixers import ProxyFix from app import app as application if os.environ.get('SENTRY_DSN'): from raven.contrib.flask import Sentry ...
785236ca766d832d859c2933389e23fd3d1bea20
djangocms_table/cms_plugins.py
djangocms_table/cms_plugins.py
from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from models import Table from djangocms_table.forms import TableForm from django.utils import simplejson from djangocms_table.utils import static_url...
import json from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from models import Table from djangocms_table.forms import TableForm from djangocms_table.utils import static_url from django.http import...
Fix another simplejson deprecation warning
Fix another simplejson deprecation warning
Python
bsd-3-clause
freelancersunion/djangocms-table,freelancersunion/djangocms-table,freelancersunion/djangocms-table,divio/djangocms-table,divio/djangocms-table,divio/djangocms-table
+ import json from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from models import Table from djangocms_table.forms import TableForm - from django.utils import simplejson from djangocms...
Fix another simplejson deprecation warning
## Code Before: from django.utils.translation import ugettext_lazy as _ from django.conf import settings from cms.plugin_pool import plugin_pool from cms.plugin_base import CMSPluginBase from models import Table from djangocms_table.forms import TableForm from django.utils import simplejson from djangocms_table.utils i...
6b3f568a6615e9439fc0df0eac68838b6cbda0d9
anti-XSS.py
anti-XSS.py
''' Copyright (c) 2016 anti-XSS developers ''' import sys from lib.core.link import Link from optparse import OptionParser from lib.core.engine import getPage from lib.core.engine import getScript from lib.core.engine import xssScanner from lib.generator.report import gnrReport def main(): parser = OptionParser...
''' Copyright (c) 2016 anti-XSS developers ''' import sys from lib.core.urlfun import * from lib.core.link import Link from optparse import OptionParser from lib.core.engine import getPage from lib.core.engine import getScript from lib.core.engine import xssScanner from lib.generator.report import gnrReport def ma...
Add initialization before get url
Add initialization before get url
Python
mit
lewangbtcc/anti-XSS,lewangbtcc/anti-XSS
''' Copyright (c) 2016 anti-XSS developers ''' import sys + + from lib.core.urlfun import * from lib.core.link import Link from optparse import OptionParser from lib.core.engine import getPage from lib.core.engine import getScript from lib.core.engine import xssScanner from lib.generator.r...
Add initialization before get url
## Code Before: ''' Copyright (c) 2016 anti-XSS developers ''' import sys from lib.core.link import Link from optparse import OptionParser from lib.core.engine import getPage from lib.core.engine import getScript from lib.core.engine import xssScanner from lib.generator.report import gnrReport def main(): parse...
a3df62c7da4aa29ab9977a0307e0634fd43e37e8
pywebfaction/exceptions.py
pywebfaction/exceptions.py
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswi...
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not exc_type.startswi...
Make code immune to bad fault messages
Make code immune to bad fault messages
Python
bsd-3-clause
dominicrodger/pywebfaction,dominicrodger/pywebfaction
import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. ...
Make code immune to bad fault messages
## Code Before: import ast EXCEPTION_TYPE_PREFIX = "<class 'webfaction_api.exceptions." EXCEPTION_TYPE_SUFFIX = "'>" def _parse_exc_type(exc_type): # This is horribly hacky, but there's not a particularly elegant # way to go from the exception type to a string representing that # exception. if not e...
e7e21188daba6efe02d44c2cef9c1b48c45c0636
readthedocs/donate/urls.py
readthedocs/donate/urls.py
from django.conf.urls import url, patterns, include from . import views urlpatterns = patterns( '', url(r'^$', views.DonateListView.as_view(), name='donate'), url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'), url(r'^contribute/thanks$', views.DonateSuccessView.as_view(), nam...
from django.conf.urls import url, patterns, include from .views import DonateCreateView from .views import DonateListView from .views import DonateSuccessView urlpatterns = patterns( '', url(r'^$', DonateListView.as_view(), name='donate'), url(r'^contribute/$', DonateCreateView.as_view(), name='donate_ad...
Resolve linting messages in readthedocs.donate.*
Resolve linting messages in readthedocs.donate.*
Python
mit
mhils/readthedocs.org,wijerasa/readthedocs.org,davidfischer/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,istresearch/readthedocs.org,wanghaven/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,hach-que/readthedocs.org,mhils/readthedocs.org,kenwang76/readthedocs.org,kenwang76/readt...
from django.conf.urls import url, patterns, include - from . import views + from .views import DonateCreateView + from .views import DonateListView + from .views import DonateSuccessView urlpatterns = patterns( '', - url(r'^$', views.DonateListView.as_view(), name='donate'), + url(r'^$', Dona...
Resolve linting messages in readthedocs.donate.*
## Code Before: from django.conf.urls import url, patterns, include from . import views urlpatterns = patterns( '', url(r'^$', views.DonateListView.as_view(), name='donate'), url(r'^contribute/$', views.DonateCreateView.as_view(), name='donate_add'), url(r'^contribute/thanks$', views.DonateSuccessVie...
a4eb952cc2e583d3b7786f5dea101d1e013c8159
services/controllers/utils.py
services/controllers/utils.py
def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
def lerp(a, b, t): return (1.0 - t) * a + t * b def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
Add function for linear interpolation (lerp)
Add function for linear interpolation (lerp)
Python
bsd-3-clause
gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2,gizmo-cda/g2x-submarine-v2
+ def lerp(a, b, t): + return (1.0 - t) * a + t * b + + def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min
Add function for linear interpolation (lerp)
## Code Before: def map_range(x, in_min, in_max, out_min, out_max): out_delta = out_max - out_min in_delta = in_max - in_min return (x - in_min) * out_delta / in_delta + out_min ## Instruction: Add function for linear interpolation (lerp) ## Code After: def lerp(a, b, t): return (1.0 - t) * a + t * b ...
a509cd74d1e49dd9f9585b8e4c43e88aaf2bc19d
tests/stonemason/service/tileserver/test_tileserver.py
tests/stonemason/service/tileserver/test_tileserver.py
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): resp = self.client.get('...
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_MODE'] = 'development' app = AppBuilder().build(config='settings.py') self.client = app.test_client() def test_app(self): ...
Update tests for the test app
TEST: Update tests for the test app
Python
mit
Kotaimen/stonemason,Kotaimen/stonemason
import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): - os.environ['EXAMPLE_APP_ENV'] = 'dev' + os.environ['EXAMPLE_APP_MODE'] = 'development' - app = AppBuilder().build() + app = Ap...
Update tests for the test app
## Code Before: import os import unittest from stonemason.service.tileserver import AppBuilder class TestExample(unittest.TestCase): def setUp(self): os.environ['EXAMPLE_APP_ENV'] = 'dev' app = AppBuilder().build() self.client = app.test_client() def test_app(self): resp = s...
7b66af8bea8e6c25e3c2f88efc22875504e8f87a
openstates/events.py
openstates/events.py
from pupa.scrape import Event from .base import OpenstatesBaseScraper import dateutil.parser dparse = lambda x: dateutil.parser.parse(x) if x else None class OpenstatesEventScraper(OpenstatesBaseScraper): def scrape(self): method = 'events/?state={}&dtstart=1776-07-04'.format(self.state) self.e...
from pupa.scrape import Event from .base import OpenstatesBaseScraper import dateutil.parser dparse = lambda x: dateutil.parser.parse(x) if x else None class OpenstatesEventScraper(OpenstatesBaseScraper): def scrape(self): method = 'events/?state={}&dtstart=1776-07-04'.format(self.state) self.e...
Add more keys in; validation
Add more keys in; validation
Python
bsd-3-clause
openstates/billy,sunlightlabs/billy,sunlightlabs/billy,openstates/billy,sunlightlabs/billy,openstates/billy
from pupa.scrape import Event from .base import OpenstatesBaseScraper import dateutil.parser dparse = lambda x: dateutil.parser.parse(x) if x else None class OpenstatesEventScraper(OpenstatesBaseScraper): def scrape(self): method = 'events/?state={}&dtstart=1776-07-04'.format(se...
Add more keys in; validation
## Code Before: from pupa.scrape import Event from .base import OpenstatesBaseScraper import dateutil.parser dparse = lambda x: dateutil.parser.parse(x) if x else None class OpenstatesEventScraper(OpenstatesBaseScraper): def scrape(self): method = 'events/?state={}&dtstart=1776-07-04'.format(self.state...
14bd2c0732b5871ac43991a237a8f12a334e982d
sirius/LI_V00/__init__.py
sirius/LI_V00/__init__.py
from . import lattice as _lattice from . import accelerator as _accelerator from . import record_names create_accelerator = accelerator.create_accelerator # -- default accelerator values for LI_V00 -- energy = _lattice._energy single_bunch_charge = _lattice._single_bunch_charge multi_bunch_charge = _lattice...
from . import lattice as _lattice from . import accelerator as _accelerator from . import record_names create_accelerator = accelerator.create_accelerator # -- default accelerator values for LI_V00 -- energy = _lattice._energy single_bunch_charge = _lattice._single_bunch_charge multi_bunch_charge = _lattice...
Add parameters of initial beam distribution at LI
Add parameters of initial beam distribution at LI
Python
mit
lnls-fac/sirius
from . import lattice as _lattice from . import accelerator as _accelerator from . import record_names create_accelerator = accelerator.create_accelerator # -- default accelerator values for LI_V00 -- energy = _lattice._energy single_bunch_charge = _lattice._single_bunch_charge multi_bunch_...
Add parameters of initial beam distribution at LI
## Code Before: from . import lattice as _lattice from . import accelerator as _accelerator from . import record_names create_accelerator = accelerator.create_accelerator # -- default accelerator values for LI_V00 -- energy = _lattice._energy single_bunch_charge = _lattice._single_bunch_charge multi_bunch_charge...
61448043a039543c38c5ca7b9828792cfc8afbb8
justwatch/justwatchapi.py
justwatch/justwatchapi.py
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None pay...
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs null = None pay...
Check and raise HTTP errors
Check and raise HTTP errors
Python
mit
dawoudt/JustWatchAPI
import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kw...
Check and raise HTTP errors
## Code Before: import requests from babel import Locale class JustWatch: def __init__(self, country='AU', **kwargs): self.kwargs = kwargs self.country = country self.language = Locale.parse('und_{}'.format(self.country)).language def search_for_item(self, **kwargs): if kwargs: self.kwargs = kwargs n...
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...
dd0cef83edbd3849484b7fc0ec5cb6372f99bb3a
batchflow/models/utils.py
batchflow/models/utils.py
""" Auxiliary functions for models """ def unpack_args(args, layer_no, layers_max): """ Return layer parameters """ new_args = {} for arg in args: if isinstance(args[arg], list) and layers_max > 1: if len(args[arg]) >= layers_max: arg_value = args[arg][layer_no] ...
""" Auxiliary functions for models """ def unpack_args(args, layer_no, layers_max): """ Return layer parameters """ new_args = {} for arg in args: if isinstance(args[arg], list): if len(args[arg]) >= layers_max: arg_value = args[arg][layer_no] else: ...
Allow for 1 arg in a list
Allow for 1 arg in a list
Python
apache-2.0
analysiscenter/dataset
""" Auxiliary functions for models """ def unpack_args(args, layer_no, layers_max): """ Return layer parameters """ new_args = {} for arg in args: - if isinstance(args[arg], list) and layers_max > 1: + if isinstance(args[arg], list): if len(args[arg]) >= layers_...
Allow for 1 arg in a list
## Code Before: """ Auxiliary functions for models """ def unpack_args(args, layer_no, layers_max): """ Return layer parameters """ new_args = {} for arg in args: if isinstance(args[arg], list) and layers_max > 1: if len(args[arg]) >= layers_max: arg_value = args[arg][l...
5c3863fdb366f857fb25b88c2e47508f23660cf3
tests/test_socket.py
tests/test_socket.py
import socket from unittest import TestCase try: from unitetest import mock except ImportError: import mock from routeros_api import api_socket class TestSocketWrapper(TestCase): def test_socket(self): inner = mock.Mock() wrapper = api_socket.SocketWrapper(inner) inner.recv.side_e...
import socket from unittest import TestCase try: from unitetest import mock except ImportError: import mock from routeros_api import api_socket class TestSocketWrapper(TestCase): def test_socket(self): inner = mock.Mock() wrapper = api_socket.SocketWrapper(inner) inner.recv.side_e...
Fix python2.6 compatibility in tests.
Fix python2.6 compatibility in tests.
Python
mit
kramarz/RouterOS-api,socialwifi/RouterOS-api,pozytywnie/RouterOS-api
import socket from unittest import TestCase try: from unitetest import mock except ImportError: import mock from routeros_api import api_socket class TestSocketWrapper(TestCase): def test_socket(self): inner = mock.Mock() wrapper = api_socket.SocketWrapper(inne...
Fix python2.6 compatibility in tests.
## Code Before: import socket from unittest import TestCase try: from unitetest import mock except ImportError: import mock from routeros_api import api_socket class TestSocketWrapper(TestCase): def test_socket(self): inner = mock.Mock() wrapper = api_socket.SocketWrapper(inner) i...
889473ba81816aa0ad349823515843c337a6b985
benchexec/tools/deagle.py
benchexec/tools/deagle.py
import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool): def executable(self): return util.find_executable("deagle") def name(self): return "Deagle" def version(self, executable): return self._...
import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool2): def executable(self, tool_locator): return tool_locator.find_executable("deagle") def name(self): return "Deagle" def version(self, executable)...
Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
Python
apache-2.0
ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,ultimate-pa/benchexec,sosy-lab/benchexec,sosy-lab/benchexec,sosy-lab/benchexec
import benchexec.result as result import benchexec.util as util import benchexec.tools.template - class Tool(benchexec.tools.template.BaseTool): + class Tool(benchexec.tools.template.BaseTool2): - def executable(self): + def executable(self, tool_locator): - return util.find_executable("d...
Move --closure and --no-unwinding-assertions to bench-defs; rewrite choices between --32 and --64
## Code Before: import benchexec.result as result import benchexec.util as util import benchexec.tools.template class Tool(benchexec.tools.template.BaseTool): def executable(self): return util.find_executable("deagle") def name(self): return "Deagle" def version(self, executable): ...
6bc1f6e466fa09dd0bc6a076f9081e1aa03efdc7
examples/translations/dutch_test_1.py
examples/translations/dutch_test_1.py
from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom") ...
from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia", "td.hp-welkom") ...
Update the Dutch example test
Update the Dutch example test
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia",...
Update the Dutch example test
## Code Before: from seleniumbase.translate.dutch import Testgeval class MijnTestklasse(Testgeval): def test_voorbeeld_1(self): self.openen("https://nl.wikipedia.org/wiki/Hoofdpagina") self.controleren_element('a[title*="hoofdpagina gaan"]') self.controleren_tekst("Welkom op Wikipedia", "...
dc2c960bb937cc287dedf95d407ed2e95f3f6724
sigma_files/serializers.py
sigma_files/serializers.py
from rest_framework import serializers from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.IntegerField(source='f...
from rest_framework import serializers from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(m...
Add permissions field on ImageSerializer
Add permissions field on ImageSerializer
Python
agpl-3.0
ProjetSigma/backend,ProjetSigma/backend
from rest_framework import serializers + from dry_rest_permissions.generics import DRYPermissionsField from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = ...
Add permissions field on ImageSerializer
## Code Before: from rest_framework import serializers from sigma.utils import CurrentUserCreateOnlyDefault from sigma_files.models import Image class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image file = serializers.ImageField(max_length=255) height = serializers.Intege...
05c9039c364d87c890cffdb9de7f0c8d1f7f9cb3
tfx/orchestration/config/kubernetes_component_config.py
tfx/orchestration/config/kubernetes_component_config.py
"""Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config class KubernetesCompon...
"""Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config from tfx.orchestration.l...
Convert k8s pod spec into dict structure to make sure that it's json serializable.
Convert k8s pod spec into dict structure to make sure that it's json serializable. PiperOrigin-RevId: 279162159
Python
apache-2.0
tensorflow/tfx,tensorflow/tfx
"""Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config + ...
Convert k8s pod spec into dict structure to make sure that it's json serializable.
## Code Before: """Component config for Kubernets Pod execution.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from typing import Any, Dict, Text, Union from kubernetes import client from tfx.orchestration.config import base_component_config class ...
525e7d5061326c7c815f4ede7757afb7c085ff78
apartments/models.py
apartments/models.py
from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Listing(Base): __tablename__ = 'listings' id = Column(Integer, primary_key=True) craigslist_id = Column(String, u...
from sqlalchemy import create_engine, Column, DateTime, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy.sql import func Base = declarative_base() class Listing(Base): __tablename__ = 'listings' id = Column(Integer, primary_key=...
Add timestamp field to Listing
Add timestamp field to Listing
Python
mit
rlucioni/apartments,rlucioni/craigbot,rlucioni/craigbot
- from sqlalchemy import create_engine, Column, Integer, String + from sqlalchemy import create_engine, Column, DateTime, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker + from sqlalchemy.sql import func Base = declarative_base() class ...
Add timestamp field to Listing
## Code Before: from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker Base = declarative_base() class Listing(Base): __tablename__ = 'listings' id = Column(Integer, primary_key=True) craigslist_id = ...
f67746750bdd2a1d6e662b1fc36d5a6fa13098c5
scripts/generate.py
scripts/generate.py
params = [ ("dict(dim=250, dim_mlp=250)", "run1"), ("dict(dim=500, dim_mlp=500)", "run2"), ("dict(rank_n_approx=200)", "run3"), ("dict(rank_n_approx=500)", "run4"), ("dict(avg_word=False)", "run5") ] for options, name in params: with open("{}.sh".format(name), "w") as script: log =...
params = [ ("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"), ("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"), ("dict(rank_n_approx=200, prefix='model_run3_')", "run3"), ("dict(rank_n_approx=500, prefix='model_run4_')", "run4"), ("dict(avg_word=False, prefix='model_run5_')",...
Add different prefixes for the experiments
Add different prefixes for the experiments
Python
bsd-3-clause
rizar/groundhog-private
params = [ - ("dict(dim=250, dim_mlp=250)", "run1"), + ("dict(dim=250, dim_mlp=250, prefix='model_run1_')", "run1"), - ("dict(dim=500, dim_mlp=500)", "run2"), + ("dict(dim=500, dim_mlp=500, prefix='model_run2_')", "run2"), - ("dict(rank_n_approx=200)", "run3"), + ("dict(rank_n_approx=200, p...
Add different prefixes for the experiments
## Code Before: params = [ ("dict(dim=250, dim_mlp=250)", "run1"), ("dict(dim=500, dim_mlp=500)", "run2"), ("dict(rank_n_approx=200)", "run3"), ("dict(rank_n_approx=500)", "run4"), ("dict(avg_word=False)", "run5") ] for options, name in params: with open("{}.sh".format(name), "w") as scrip...
1986000f7e3fff1366de245dadf8cd3b6e53f238
djstripe/contrib/rest_framework/permissions.py
djstripe/contrib/rest_framework/permissions.py
from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscriptions. """ ...
from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscriptions. """ ...
Fix missing return statement in DJStripeSubscriptionPermission
Fix missing return statement in DJStripeSubscriptionPermission Fixes #1250
Python
mit
dj-stripe/dj-stripe,dj-stripe/dj-stripe,pydanny/dj-stripe,pydanny/dj-stripe
from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscr...
Fix missing return statement in DJStripeSubscriptionPermission
## Code Before: from rest_framework.permissions import BasePermission from ...settings import subscriber_request_callback from ...utils import subscriber_has_active_subscription class DJStripeSubscriptionPermission(BasePermission): """ A permission to be used when wanting to permit users with active subscrip...
94351ce09112c7bd4c9ed58722334ee48fe99883
datapackage_pipelines_fiscal/processors/upload.py
datapackage_pipelines_fiscal/processors/upload.py
import os import zipfile import tempfile from datapackage_pipelines.wrapper import ingest, spew import gobble params, datapackage, res_iter = ingest() spew(datapackage, res_iter) user = gobble.user.User() in_filename = open(params['in-file'], 'rb') in_file = zipfile.ZipFile(in_filename) temp_dir = tempfile.mkdtemp...
import os import zipfile import tempfile from datapackage_pipelines.wrapper import ingest, spew import gobble params, datapackage, res_iter = ingest() spew(datapackage, res_iter) user = gobble.user.User() in_filename = open(params['in-file'], 'rb') in_file = zipfile.ZipFile(in_filename) temp_dir = tempfile.mkdtemp...
Set the publication with a parameter.
Set the publication with a parameter.
Python
mit
openspending/datapackage-pipelines-fiscal
import os import zipfile import tempfile from datapackage_pipelines.wrapper import ingest, spew import gobble params, datapackage, res_iter = ingest() spew(datapackage, res_iter) user = gobble.user.User() in_filename = open(params['in-file'], 'rb') in_file = zipfile.ZipFile(in_filenam...
Set the publication with a parameter.
## Code Before: import os import zipfile import tempfile from datapackage_pipelines.wrapper import ingest, spew import gobble params, datapackage, res_iter = ingest() spew(datapackage, res_iter) user = gobble.user.User() in_filename = open(params['in-file'], 'rb') in_file = zipfile.ZipFile(in_filename) temp_dir = ...
ec4d84e0b67d26dd9888d1b54adda6fbbcdc67da
packages/blueprints/api.py
packages/blueprints/api.py
from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from packages.objects import * from packages.common import * from packages.config import _cfg import os import zipfile import urllib api = Blueprint...
from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from packages.objects import * from packages.common import * from packages.config import _cfg import os import zipfile import urllib api = Blueprint...
Add API endpoint for logging in
Add API endpoint for logging in
Python
mit
KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org,MaxLeiter/packages.knightos.org,KnightOS/packages.knightos.org,KnightOS/packages.knightos.org,MaxLeiter/packages.knightos.org
from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from packages.objects import * from packages.common import * from packages.config import _cfg import os import zipfile import url...
Add API endpoint for logging in
## Code Before: from flask import Blueprint, render_template, abort, request, redirect, session, url_for from flask.ext.login import current_user, login_user from sqlalchemy import desc from packages.objects import * from packages.common import * from packages.config import _cfg import os import zipfile import urllib ...
58c97445c8d55d48e03498c758f7b7c6dee245aa
enabled/_50_admin_add_monitoring_panel.py
enabled/_50_admin_add_monitoring_panel.py
PANEL = 'monitoring' # The name of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'overcloud' # The name of the panel group the PANEL is associated with. #PANEL_GROUP = 'admin' # Python panel class of the PANEL to be added. ADD_PANEL = \ 'monitoring.panel.Monitoring' # A list of applications...
PANEL = 'monitoring' # The name of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'overcloud' # The name of the panel group the PANEL is associated with. #PANEL_GROUP = 'admin' DEFAULT_PANEL = 'monitoring' # Python panel class of the PANEL to be added. ADD_PANEL = \ 'monitoring.panel.Monitor...
Set DEFAULT_PANEL to monitoring panel
Set DEFAULT_PANEL to monitoring panel
Python
apache-2.0
stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,openstack/monasca-ui,openstack/monasca-ui,stackforge/monasca-ui,stackforge/monasca-ui
PANEL = 'monitoring' # The name of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'overcloud' # The name of the panel group the PANEL is associated with. #PANEL_GROUP = 'admin' + + DEFAULT_PANEL = 'monitoring' # Python panel class of the PANEL to be added. ADD_PANEL = \ 'mo...
Set DEFAULT_PANEL to monitoring panel
## Code Before: PANEL = 'monitoring' # The name of the dashboard the PANEL associated with. Required. PANEL_DASHBOARD = 'overcloud' # The name of the panel group the PANEL is associated with. #PANEL_GROUP = 'admin' # Python panel class of the PANEL to be added. ADD_PANEL = \ 'monitoring.panel.Monitoring' # A list...
7cedab4826d5d184e595864f4cf5ca3966a1921e
random_object_id/random_object_id.py
random_object_id/random_object_id.py
import binascii import os import time from optparse import OptionParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '__main__': parser = OptionParser() parser.add_option('-l...
import binascii import os import time from argparse import ArgumentParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '__main__': parser = ArgumentParser(description='Generate a...
Use argparse instead of optparse
Use argparse instead of optparse
Python
mit
mxr/random-object-id
import binascii import os import time - from optparse import OptionParser + from argparse import ArgumentParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '...
Use argparse instead of optparse
## Code Before: import binascii import os import time from optparse import OptionParser def gen_random_object_id(): timestamp = '{0:x}'.format(int(time.time())) rest = binascii.b2a_hex(os.urandom(8)).decode('ascii') return timestamp + rest if __name__ == '__main__': parser = OptionParser() parse...
404b9208d98753dfccffb6c87594cfc70faed073
filer/tests/general.py
filer/tests/general.py
from django.test import TestCase import filer class GeneralTestCase(TestCase): def test_version_is_set(self): self.assertTrue(len(filer.get_version())>0) def test_travisci_configuration(self): self.assertTrue(False)
from django.test import TestCase import filer class GeneralTestCase(TestCase): def test_version_is_set(self): self.assertTrue(len(filer.get_version())>0)
Revert "travis ci: test if it REALLY works"
Revert "travis ci: test if it REALLY works" This reverts commit 78d87177c71adea7cc06d968374d2c2197dc5289.
Python
bsd-3-clause
Flight/django-filer,obigroup/django-filer,DylannCordel/django-filer,vstoykov/django-filer,o-zander/django-filer,mitar/django-filer,stefanfoulis/django-filer,skirsdeda/django-filer,thomasbilk/django-filer,kriwil/django-filer,sbussetti/django-filer,jakob-o/django-filer,lory87/django-filer,rollstudio/django-filer,Flight/d...
from django.test import TestCase import filer class GeneralTestCase(TestCase): def test_version_is_set(self): self.assertTrue(len(filer.get_version())>0) - - def test_travisci_configuration(self): - self.assertTrue(False)
Revert "travis ci: test if it REALLY works"
## Code Before: from django.test import TestCase import filer class GeneralTestCase(TestCase): def test_version_is_set(self): self.assertTrue(len(filer.get_version())>0) def test_travisci_configuration(self): self.assertTrue(False) ## Instruction: Revert "travis ci: test if it REALLY works" #...
ffb8f3f0d1fe17e13b349f8f4bae8fd9acbbd146
linter.py
linter.py
"""This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provides an interface to raml-cop.""" syntax = 'raml' cmd = 'raml-cop --no-color' version_requirement = '>= 1.0.0' regex = ( r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] ...
"""This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provides an interface to raml-cop.""" syntax = 'raml' cmd = 'raml-cop --no-color' version_requirement = '>= 1.0.0' regex = ( r'^\[.+:(?P<line>\d+):(?P<col>\d+)\] ...
Update regex to match new parser output
Update regex to match new parser output
Python
mit
thebinarypenguin/SublimeLinter-contrib-raml-cop
"""This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provides an interface to raml-cop.""" syntax = 'raml' cmd = 'raml-cop --no-color' version_requirement = '>= 1.0.0' regex = ( r'^\[.+...
Update regex to match new parser output
## Code Before: """This module exports the RamlCop plugin class.""" from SublimeLinter.lint import NodeLinter class RamlCop(NodeLinter): """Provides an interface to raml-cop.""" syntax = 'raml' cmd = 'raml-cop --no-color' version_requirement = '>= 1.0.0' regex = ( r'^\[.+:(?P<line>\d+)...
69c81b16e07b67ba0a0bc8e1f55049e7987c5b8c
openstack_dashboard/dashboards/admin/instances/panel.py
openstack_dashboard/dashboards/admin/instances/panel.py
from django.utils.translation import ugettext_lazy as _ import horizon class Instances(horizon.Panel): name = _("Instances") slug = 'instances' permissions = ('openstack.services.compute',) policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:get_all")),)
from django.utils.translation import ugettext_lazy as _ import horizon class Instances(horizon.Panel): name = _("Instances") slug = 'instances' permissions = ('openstack.services.compute',) policy_rules = ((("compute", "context_is_admin"), ("compute", "os_compute_api:servers:det...
Fix an incorrect policy rule in Admin > Instances
Fix an incorrect policy rule in Admin > Instances Change-Id: I765ae0c36d19c88138fbea9545a2ca4791377ffb Closes-Bug: #1703066
Python
apache-2.0
BiznetGIO/horizon,BiznetGIO/horizon,noironetworks/horizon,ChameleonCloud/horizon,yeming233/horizon,NeCTAR-RC/horizon,yeming233/horizon,BiznetGIO/horizon,yeming233/horizon,openstack/horizon,noironetworks/horizon,NeCTAR-RC/horizon,yeming233/horizon,ChameleonCloud/horizon,NeCTAR-RC/horizon,noironetworks/horizon,openstack/...
from django.utils.translation import ugettext_lazy as _ import horizon class Instances(horizon.Panel): name = _("Instances") slug = 'instances' permissions = ('openstack.services.compute',) policy_rules = ((("compute", "context_is_admin"), - ("compute", "co...
Fix an incorrect policy rule in Admin > Instances
## Code Before: from django.utils.translation import ugettext_lazy as _ import horizon class Instances(horizon.Panel): name = _("Instances") slug = 'instances' permissions = ('openstack.services.compute',) policy_rules = ((("compute", "context_is_admin"), ("compute", "compute:ge...
5516b125bb00b928d85a044d3df777e1b0004d03
ovp_organizations/migrations/0008_auto_20161207_1941.py
ovp_organizations/migrations/0008_auto_20161207_1941.py
from __future__ import unicode_literals from django.db import migrations from ovp_organizations.models import Organization def add_members(apps, schema_editor): for organization in Organization.objects.all(): organization.members.add(organization.owner) def remove_members(apps, schema_editor): for organiza...
from __future__ import unicode_literals from django.db import migrations from ovp_organizations.models import Organization def add_members(apps, schema_editor): for organization in Organization.objects.only('pk', 'members').all(): organization.members.add(organization.owner) def remove_members(apps, schema_e...
Add ".only" restriction to query on migration 0008
Add ".only" restriction to query on migration 0008
Python
agpl-3.0
OpenVolunteeringPlatform/django-ovp-organizations,OpenVolunteeringPlatform/django-ovp-organizations
from __future__ import unicode_literals from django.db import migrations from ovp_organizations.models import Organization def add_members(apps, schema_editor): - for organization in Organization.objects.all(): + for organization in Organization.objects.only('pk', 'members').all(): organizati...
Add ".only" restriction to query on migration 0008
## Code Before: from __future__ import unicode_literals from django.db import migrations from ovp_organizations.models import Organization def add_members(apps, schema_editor): for organization in Organization.objects.all(): organization.members.add(organization.owner) def remove_members(apps, schema_editor)...
4ec16018192c1bd8fbe60a9e4c410c6c898149f0
server/ec2spotmanager/migrations/0007_instance_type_to_list.py
server/ec2spotmanager/migrations/0007_instance_type_to_list.py
from __future__ import unicode_literals from django.db import migrations, models def instance_types_to_list(apps, schema_editor): PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration") for pool in PoolConfiguration.objects.all(): pool.ec2_instance_types_list = [pool.ec2_instance_ty...
from __future__ import print_function, unicode_literals import json import sys from django.db import migrations, models def instance_type_to_list(apps, schema_editor): PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration") for pool in PoolConfiguration.objects.all(): if pool.ec2_in...
Fix migration. Custom triggers are not run in data migrations.
Fix migration. Custom triggers are not run in data migrations.
Python
mpl-2.0
MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager,MozillaSecurity/FuzzManager
- from __future__ import unicode_literals + from __future__ import print_function, unicode_literals + import json + import sys from django.db import migrations, models - def instance_types_to_list(apps, schema_editor): + def instance_type_to_list(apps, schema_editor): PoolConfiguration = apps.get_model...
Fix migration. Custom triggers are not run in data migrations.
## Code Before: from __future__ import unicode_literals from django.db import migrations, models def instance_types_to_list(apps, schema_editor): PoolConfiguration = apps.get_model("ec2spotmanager", "PoolConfiguration") for pool in PoolConfiguration.objects.all(): pool.ec2_instance_types_list = [pool...
19cd85215a7a305e6f253405a88d087aef114811
candidates/tests/test_constituencies_view.py
candidates/tests/test_constituencies_view.py
import re from django_webtest import WebTest class TestConstituencyDetailView(WebTest): def test_constituencies_page(self): # Just a smoke test to check that the page loads: response = self.app.get('/constituencies') aberdeen_north = response.html.find( 'a', text=re.compile(r'...
import re from mock import patch from django_webtest import WebTest class TestConstituencyDetailView(WebTest): @patch('candidates.popit.PopIt') def test_constituencies_page(self, mock_popit): # Just a smoke test to check that the page loads: response = self.app.get('/constituencies') ...
Make test_constituencies_page work without PopIt
Make test_constituencies_page work without PopIt
Python
agpl-3.0
DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,mysociety/yournextmp-popit,neavouli/yournextrepresentative,DemocracyClub/yournextrepresentative,YoQuieroSaber/yournextrepresentative,mysociety/yournextrepresentative,YoQuieroSaber/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/...
import re + + from mock import patch from django_webtest import WebTest class TestConstituencyDetailView(WebTest): + @patch('candidates.popit.PopIt') - def test_constituencies_page(self): + def test_constituencies_page(self, mock_popit): # Just a smoke test to check that the page l...
Make test_constituencies_page work without PopIt
## Code Before: import re from django_webtest import WebTest class TestConstituencyDetailView(WebTest): def test_constituencies_page(self): # Just a smoke test to check that the page loads: response = self.app.get('/constituencies') aberdeen_north = response.html.find( 'a', te...
723a102d6272e7ba4b9df405b7c1493c34ac5b77
masters/master.chromium.fyi/master_site_config.py
masters/master.chromium.fyi/master_site_config.py
"""ActiveMaster definition.""" from config_bootstrap import Master class ChromiumFYI(Master.Master1): project_name = 'Chromium FYI' master_port = 8011 slave_port = 8111 master_port_alt = 8211 buildbot_url = 'http://build.chromium.org/p/chromium.fyi/' reboot_on_step_timeout = True pubsub_service_account...
"""ActiveMaster definition.""" from config_bootstrap import Master class ChromiumFYI(Master.Master1): project_name = 'Chromium FYI' master_port = 8011 slave_port = 8111 master_port_alt = 8211 buildbot_url = 'http://build.chromium.org/p/chromium.fyi/' reboot_on_step_timeout = True
Revert pubsub roll on FYI
Revert pubsub roll on FYI BUG= TBR=estaab Review URL: https://codereview.chromium.org/1688503002 git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@298680 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
"""ActiveMaster definition.""" from config_bootstrap import Master class ChromiumFYI(Master.Master1): project_name = 'Chromium FYI' master_port = 8011 slave_port = 8111 master_port_alt = 8211 buildbot_url = 'http://build.chromium.org/p/chromium.fyi/' reboot_on_step_timeout = True ...
Revert pubsub roll on FYI
## Code Before: """ActiveMaster definition.""" from config_bootstrap import Master class ChromiumFYI(Master.Master1): project_name = 'Chromium FYI' master_port = 8011 slave_port = 8111 master_port_alt = 8211 buildbot_url = 'http://build.chromium.org/p/chromium.fyi/' reboot_on_step_timeout = True pubsub...
39d3f605d240a8abef22107424ec1d6f76161580
static_precompiler/models.py
static_precompiler/models.py
from django.db import models class Dependency(models.Model): source = models.CharField(max_length=255, db_index=True) depends_on = models.CharField(max_length=255, db_index=True) class Meta: unique_together = ("source", "depends_on")
from __future__ import unicode_literals from django.db import models class Dependency(models.Model): source = models.CharField(max_length=255, db_index=True) depends_on = models.CharField(max_length=255, db_index=True) class Meta: unique_together = ("source", "depends_on") def __unicode__(s...
Add __unicode__ to Dependency model
Add __unicode__ to Dependency model
Python
mit
jaheba/django-static-precompiler,jaheba/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,jaheba/django-static-precompiler,liumengjun/django-static-precompiler,paera/django-static-precompiler,liumengjun/django-static-precompiler,liumengjun/django-static-precompiler,liumengju...
+ from __future__ import unicode_literals from django.db import models class Dependency(models.Model): source = models.CharField(max_length=255, db_index=True) depends_on = models.CharField(max_length=255, db_index=True) class Meta: unique_together = ("source", "depends_on") ...
Add __unicode__ to Dependency model
## Code Before: from django.db import models class Dependency(models.Model): source = models.CharField(max_length=255, db_index=True) depends_on = models.CharField(max_length=255, db_index=True) class Meta: unique_together = ("source", "depends_on") ## Instruction: Add __unicode__ to Dependency...
d2051073d48873408a711b56676ee099e5ff685a
sunpy/timeseries/__init__.py
sunpy/timeseries/__init__.py
from __future__ import absolute_import from sunpy.timeseries.metadata import TimeSeriesMetaData from sunpy.timeseries.timeseries_factory import TimeSeries from sunpy.timeseries.timeseriesbase import GenericTimeSeries from sunpy.timeseries.sources.eve import EVESpWxTimeSeries from sunpy.timeseries.sources.goes import XR...
from __future__ import absolute_import from sunpy.timeseries.metadata import TimeSeriesMetaData from sunpy.timeseries.timeseries_factory import TimeSeries from sunpy.timeseries.timeseriesbase import GenericTimeSeries from sunpy.timeseries.sources.eve import EVESpWxTimeSeries from sunpy.timeseries.sources.goes import XR...
Fix matplotlib / pandas 0.21 bug in examples
Fix matplotlib / pandas 0.21 bug in examples Here we manually register the pandas matplotlib converters so people doing manual plotting with pandas works under pandas 0.21
Python
bsd-2-clause
dpshelio/sunpy,dpshelio/sunpy,dpshelio/sunpy
from __future__ import absolute_import from sunpy.timeseries.metadata import TimeSeriesMetaData from sunpy.timeseries.timeseries_factory import TimeSeries from sunpy.timeseries.timeseriesbase import GenericTimeSeries from sunpy.timeseries.sources.eve import EVESpWxTimeSeries from sunpy.timeseries.sources.go...
Fix matplotlib / pandas 0.21 bug in examples
## Code Before: from __future__ import absolute_import from sunpy.timeseries.metadata import TimeSeriesMetaData from sunpy.timeseries.timeseries_factory import TimeSeries from sunpy.timeseries.timeseriesbase import GenericTimeSeries from sunpy.timeseries.sources.eve import EVESpWxTimeSeries from sunpy.timeseries.source...
2de7222ffd3d9f4cc7971ad142aa2542eb7ca117
yunity/stores/models.py
yunity/stores/models.py
from config import settings from yunity.base.base_models import BaseModel, LocationModel from django.db import models class PickupDate(BaseModel): date = models.DateTimeField() collectors = models.ManyToManyField(settings.AUTH_USER_MODEL) store = models.ForeignKey('stores.store', related_name='pickupdates...
from config import settings from yunity.base.base_models import BaseModel, LocationModel from django.db import models class PickupDate(BaseModel): date = models.DateTimeField() collectors = models.ManyToManyField(settings.AUTH_USER_MODEL) store = models.ForeignKey('stores.store', related_name='pickupdates...
Add related name for group of store
Add related name for group of store
Python
agpl-3.0
yunity/yunity-core,yunity/foodsaving-backend,yunity/yunity-core,yunity/foodsaving-backend,yunity/foodsaving-backend
from config import settings from yunity.base.base_models import BaseModel, LocationModel from django.db import models class PickupDate(BaseModel): date = models.DateTimeField() collectors = models.ManyToManyField(settings.AUTH_USER_MODEL) store = models.ForeignKey('stores.store', related...
Add related name for group of store
## Code Before: from config import settings from yunity.base.base_models import BaseModel, LocationModel from django.db import models class PickupDate(BaseModel): date = models.DateTimeField() collectors = models.ManyToManyField(settings.AUTH_USER_MODEL) store = models.ForeignKey('stores.store', related_n...
7ddc4b975910bf9c77b753e8e0aeaebc45949e4e
linkatos.py
linkatos.py
import os import time from slackclient import SlackClient import pyrebase import linkatos.parser as parser import linkatos.confirmation as confirmation import linkatos.printer as printer import linkatos.utils as utils import linkatos.firebase as fb # starterbot environment variables BOT_ID = os.environ.get("BOT_ID") S...
import os import time from slackclient import SlackClient import pyrebase import linkatos.firebase as fb # starterbot environment variables BOT_ID = os.environ.get("BOT_ID") SLACK_BOT_TOKEN = os.environ.get("SLACK_BOT_TOKEN") # instantiate Slack clients slack_client = SlackClient(SLACK_BOT_TOKEN) # firebase environm...
Remove old imports from main
refactor: Remove old imports from main
Python
mit
iwi/linkatos,iwi/linkatos
import os import time from slackclient import SlackClient import pyrebase - import linkatos.parser as parser - import linkatos.confirmation as confirmation - import linkatos.printer as printer - import linkatos.utils as utils import linkatos.firebase as fb # starterbot environment variables BOT_ID = os...
Remove old imports from main
## Code Before: import os import time from slackclient import SlackClient import pyrebase import linkatos.parser as parser import linkatos.confirmation as confirmation import linkatos.printer as printer import linkatos.utils as utils import linkatos.firebase as fb # starterbot environment variables BOT_ID = os.environ...
d5cd1eddf1ecf0c463a90d0e69413aadd311977a
lots/urls.py
lots/urls.py
from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='status'), url(r'^appl...
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='status'), url(r'^apply/$', 'lots_client.views.apply', ...
Revert "Picture access from admin console"
Revert "Picture access from admin console" This reverts commit 324fa160fb629f6c4537ca15212c0822e8ac436d.
Python
mit
opencleveland/large-lots,skorasaurus/large-lots,opencleveland/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,skorasaurus/large-lots,opencleveland/large-lots,opencleveland/large-lots
from django.conf.urls import patterns, include, url - from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='statu...
Revert "Picture access from admin console"
## Code Before: from django.conf.urls import patterns, include, url from django.conf import settings from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', # Examples: url(r'^$', 'lots_client.views.home', name='home'), url(r'^status/$', 'lots_client.views.status', name='status'),...
88a31ebcd7b65f9282bb0d0a19ad299c1ad431ec
spectral_cube/__init__.py
spectral_cube/__init__.py
# Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: ...
# Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- if not _ASTROPY_SETUP_: ...
Make Projection importable from the top level of the package
Make Projection importable from the top level of the package
Python
bsd-3-clause
e-koch/spectral-cube,jzuhone/spectral-cube,radio-astro-tools/spectral-cube,keflavich/spectral-cube,low-sky/spectral-cube
# Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- if not _ASTR...
Make Projection importable from the top level of the package
## Code Before: # Affiliated packages may add whatever they like to this file, but # should keep this content at the top. # ---------------------------------------------------------------------------- from ._astropy_init import * # ---------------------------------------------------------------------------- if not _AS...
6a4046aafe43930c202e2f18a55b1cd8517d95f9
testanalyzer/javaanalyzer.py
testanalyzer/javaanalyzer.py
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) # TODO: Accept angle brackets and decline "else if" def get_function_count(self, content): ...
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) def get_function_count(self, content): matches = re.findall( "[a-zA-Z <>]+ ...
Fix regex to match generics
Fix regex to match generics
Python
mpl-2.0
CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer
import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( - re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) + re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_<>, ]+\n*\{", content)) - ...
Fix regex to match generics
## Code Before: import re from fileanalyzer import FileAnalyzer class JavaAnalyzer(FileAnalyzer): def get_class_count(self, content): return len( re.findall("[a-zA-Z ]*class +[a-zA-Z0-9_]+ *\n*\{", content)) # TODO: Accept angle brackets and decline "else if" def get_function_count(se...
ea1c62ae3f13d47ee820eae31a2e284e3d66b6ab
libPiLite.py
libPiLite.py
def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] ro...
def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = grid[i] ro...
Add setGrid and resetGrid functions
Add setGrid and resetGrid functions
Python
mit
rorasa/RPiClockArray
def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): ...
Add setGrid and resetGrid functions
## Code Before: def createBlankGrid(row,column): blankgrid = [[0 for x in range(column)] for y in range(row)] return blankgrid def getHeight(grid): return len(grid) def getWidth(grid): return len(grid[0]) def printGrid(grid): numRow = len(grid) for i in range(0,numRow): row = gr...
e0b3b767ccb7fc601eb7b40d336f94d75f8aa43c
2016/python/aoc_2016_03.py
2016/python/aoc_2016_03.py
from __future__ import annotations from typing import List, Tuple from aoc_common import load_puzzle_input, report_solution def parse_horizontal(string: str) -> List[Tuple[int, int, int]]: """Parse the instruction lines into sorted triples of side lengths.""" sorted_sides = [ sorted(int(x) for x in ...
from __future__ import annotations from typing import List, Tuple from aoc_common import load_puzzle_input, report_solution def parse_horizontal(string: str) -> List[Tuple[int, int, int]]: """Parse the instruction lines into triples of side lengths.""" sides = [[int(x) for x in line.split()] for line in str...
Sort triples in separate step
2016-03.py: Sort triples in separate step
Python
mit
robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions
from __future__ import annotations from typing import List, Tuple from aoc_common import load_puzzle_input, report_solution def parse_horizontal(string: str) -> List[Tuple[int, int, int]]: - """Parse the instruction lines into sorted triples of side lengths.""" + """Parse the instruction lin...
Sort triples in separate step
## Code Before: from __future__ import annotations from typing import List, Tuple from aoc_common import load_puzzle_input, report_solution def parse_horizontal(string: str) -> List[Tuple[int, int, int]]: """Parse the instruction lines into sorted triples of side lengths.""" sorted_sides = [ sorted(...
8b5337878172df95400a708b096e012436f8a706
dags/main_summary.py
dags/main_summary.py
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['telemetry-alerts...
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 25), 'email': ['telemetry-alerts...
Prepare "Main Summary" job for backfill
Prepare "Main Summary" job for backfill Set the max number of active runs so we don't overwhelm the system, and rewind the start date by a couple of days to test that the scheduler does the right thing.
Python
mpl-2.0
opentrials/opentrials-airflow,opentrials/opentrials-airflow
from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, - 'start_date': datetime(2016, 6, 27), + 'start_...
Prepare "Main Summary" job for backfill
## Code Before: from airflow import DAG from datetime import datetime, timedelta from operators.emr_spark_operator import EMRSparkOperator from airflow.operators import BashOperator default_args = { 'owner': 'mreid@mozilla.com', 'depends_on_past': False, 'start_date': datetime(2016, 6, 27), 'email': ['...
847375a5cd6cbc160c190c9fb5e9fa2b1f0cdea9
lustro/db.py
lustro/db.py
from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.meta = MetaData() ...
from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.meta = MetaData() ...
Fix arguments to diff method
Fix arguments to diff method
Python
mit
ashwoods/lustro
from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.me...
Fix arguments to diff method
## Code Before: from sqlalchemy import MetaData, create_engine from sqlalchemy.orm import Session from sqlalchemy.ext.automap import automap_base class DB(object): """Facade for the low level DB operations""" def __init__(self, dsn, schema=None): self.engine = create_engine(dsn) self.meta = M...
3131ea5c8dd41d18192f685e61c1bc8987038193
vcs_info_panel/tests/test_clients/test_git.py
vcs_info_panel/tests/test_clients/test_git.py
import subprocess from unittest.mock import patch from django.test import TestCase from vcs_info_panel.clients.git import GitClient class GitClientTestCase(TestCase): def setUp(self): self.client = GitClient() def _test_called_check_output(self, commands): with patch('subprocess.check_output...
import subprocess from unittest.mock import patch from django.test import TestCase from vcs_info_panel.clients.git import GitClient def without_git_repository(func): def inner(*args, **kwargs): with patch('subprocess.check_output') as _check_output: _check_output.side_effect = subprocess.Call...
Use decorator to patch git repository is not exist
Use decorator to patch git repository is not exist
Python
mit
giginet/django-debug-toolbar-vcs-info,giginet/django-debug-toolbar-vcs-info
import subprocess from unittest.mock import patch from django.test import TestCase from vcs_info_panel.clients.git import GitClient + + + def without_git_repository(func): + def inner(*args, **kwargs): + with patch('subprocess.check_output') as _check_output: + _check_output.side_ef...
Use decorator to patch git repository is not exist
## Code Before: import subprocess from unittest.mock import patch from django.test import TestCase from vcs_info_panel.clients.git import GitClient class GitClientTestCase(TestCase): def setUp(self): self.client = GitClient() def _test_called_check_output(self, commands): with patch('subproc...
f4adce54b573b7776cf3f56230821f982c16b49f
modules/helloworld/helloworld.py
modules/helloworld/helloworld.py
def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def callback(result): """ callback function to ca...
import time def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def callback(result): """ callback ...
Add time.sleep(0.05) in test module
Add time.sleep(0.05) in test module
Python
mit
RickGray/cyberbot
+ import time + + def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def...
Add time.sleep(0.05) in test module
## Code Before: def run(seed): """ function to run Args: seed: The value of each line striped in seed file Returns: String, object, list, directory, etc. """ name, age = seed.split(',') return 'Hello World! {}, {}'.format(seed, int(age)) def callback(result): """ callbac...
41ba2d55ed00269465d49ba22a1cb07eb899273a
test/test_run.py
test/test_run.py
from exp_test_helper import run_exp import pytest class TestRun(): """ Run and check return code. """ @pytest.mark.fast def test_run(self): run_exp('1deg_jra55_ryf') @pytest.mark.slow def test_slow_run(self): run_exp('025deg_jra55_ryf')
from exp_test_helper import run_exp import pytest class TestRun(): """ Run and check return code. """ @pytest.mark.fast def test_1deg_jra55_run(self): run_exp('1deg_jra55_ryf') @pytest.mark.slow def test_1deg_core_run(self): run_exp('1deg_core_nyf') @pytest.mark.slo...
Include the 1deg core experiment in tests.
Include the 1deg core experiment in tests.
Python
apache-2.0
CWSL/access-om
from exp_test_helper import run_exp import pytest class TestRun(): """ Run and check return code. """ @pytest.mark.fast - def test_run(self): + def test_1deg_jra55_run(self): run_exp('1deg_jra55_ryf') + + @pytest.mark.slow + def test_1deg_core_run(sel...
Include the 1deg core experiment in tests.
## Code Before: from exp_test_helper import run_exp import pytest class TestRun(): """ Run and check return code. """ @pytest.mark.fast def test_run(self): run_exp('1deg_jra55_ryf') @pytest.mark.slow def test_slow_run(self): run_exp('025deg_jra55_ryf') ## Instruction: I...
cc3d89d4357099ba2df1628e9d91e48c743bd471
api/common/views.py
api/common/views.py
import subprocess from django.conf import settings from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deploy_secret_key = request...
import subprocess from django.conf import settings from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deploy_secret_key = request...
Fix incorrect social redirect link
Fix incorrect social redirect link
Python
apache-2.0
prattl/teamfinder,prattl/teamfinder,prattl/teamfinder,prattl/teamfinder
import subprocess from django.conf import settings from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deplo...
Fix incorrect social redirect link
## Code Before: import subprocess from django.conf import settings from django.http import JsonResponse, HttpResponseBadRequest from django.shortcuts import redirect from django.views.decorators.csrf import csrf_exempt from rest_framework.authtoken.models import Token @csrf_exempt def deploy(request): deploy_secr...
107b97e952d731f8c55c9ca3208ecd2a41512b8d
tests/integration/modules/sysmod.py
tests/integration/modules/sysmod.py
import integration class SysModuleTest(integration.ModuleCase): ''' Validate the sys module ''' def test_list_functions(self): ''' sys.list_functions ''' funcs = self.run_function('sys.list_functions') self.assertTrue('hosts.list_hosts' in funcs) self.as...
import integration class SysModuleTest(integration.ModuleCase): ''' Validate the sys module ''' def test_list_functions(self): ''' sys.list_functions ''' funcs = self.run_function('sys.list_functions') self.assertTrue('hosts.list_hosts' in funcs) self.as...
Add test to verify loader modules
Add test to verify loader modules
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
import integration class SysModuleTest(integration.ModuleCase): ''' Validate the sys module ''' def test_list_functions(self): ''' sys.list_functions ''' funcs = self.run_function('sys.list_functions') self.assertTrue('hosts.list_hosts'...
Add test to verify loader modules
## Code Before: import integration class SysModuleTest(integration.ModuleCase): ''' Validate the sys module ''' def test_list_functions(self): ''' sys.list_functions ''' funcs = self.run_function('sys.list_functions') self.assertTrue('hosts.list_hosts' in funcs)...
9058d2ddc9a89913710df0efc8d7c88471592795
back2back/management/commands/import_entries.py
back2back/management/commands/import_entries.py
import csv from optparse import make_option from django.core.management import BaseCommand from back2back.models import Entry class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '-i', '--input', action='store', dest='input_file', ...
import collections import csv from optparse import make_option from django.core.management import BaseCommand from back2back.models import Entry class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '-i', '--input', action='store', dest='i...
Save indexes as well when importing entries.
Save indexes as well when importing entries.
Python
bsd-2-clause
mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back,mjtamlyn/back2back
+ import collections import csv from optparse import make_option from django.core.management import BaseCommand from back2back.models import Entry class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '-i', '--input', action=...
Save indexes as well when importing entries.
## Code Before: import csv from optparse import make_option from django.core.management import BaseCommand from back2back.models import Entry class Command(BaseCommand): option_list = BaseCommand.option_list + ( make_option( '-i', '--input', action='store', dest='inpu...
47a9271a00fae3f55c79323c93feb4dc2e1fd515
portal/tests/models/test_profile.py
portal/tests/models/test_profile.py
from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.users: self.UserModel....
from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.users: self.UserModel....
Add more profile model tests
Add more profile model tests
Python
mit
huangsam/chowist,huangsam/chowist,huangsam/chowist
from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.user...
Add more profile model tests
## Code Before: from django.contrib.auth import get_user_model from django.test import TestCase from portal.models import Profile class TestProfile(TestCase): """Profile test suite""" users = ["john", "jane"] UserModel = get_user_model() def setUp(self): for user in self.users: ...
416dea771c5750044b99e8c8bfe0755feeb3ee71
astropy/vo/samp/constants.py
astropy/vo/samp/constants.py
"""Defines constants used in `astropy.vo.samp`.""" import os DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') __all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR', 'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE', 'SAFE_MTYPES', 'SAMP_ICON'] __profile_versi...
"""Defines constants used in `astropy.vo.samp`.""" import os from ...utils.data import get_pkg_data_filename __all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR', 'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE', 'SAFE_MTYPES', 'SAMP_ICON'] __profile_version__ = "1.3...
Make use of get_pkg_data_filename for icon
Make use of get_pkg_data_filename for icon
Python
bsd-3-clause
StuartLittlefair/astropy,StuartLittlefair/astropy,bsipocz/astropy,saimn/astropy,bsipocz/astropy,tbabej/astropy,dhomeier/astropy,aleksandr-bakanov/astropy,AustereCuriosity/astropy,larrybradley/astropy,mhvk/astropy,stargaser/astropy,dhomeier/astropy,pllim/astropy,kelle/astropy,DougBurke/astropy,AustereCuriosity/astropy,d...
"""Defines constants used in `astropy.vo.samp`.""" import os - DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') + from ...utils.data import get_pkg_data_filename __all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR', 'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_...
Make use of get_pkg_data_filename for icon
## Code Before: """Defines constants used in `astropy.vo.samp`.""" import os DATA_DIR = os.path.join(os.path.dirname(__file__), 'data') __all__ = ['SAMP_STATUS_OK', 'SAMP_STATUS_WARNING', 'SAMP_STATUS_ERROR', 'SAMP_HUB_SINGLE_INSTANCE', 'SAMP_HUB_MULTIPLE_INSTANCE', 'SAFE_MTYPES', 'SAMP_ICON'] ...
745ec6f3dd227cc00c3db0d100b005fb6fd4d903
test/on_yubikey/test_cli_openpgp.py
test/on_yubikey/test_cli_openpgp.py
import unittest from ykman.util import TRANSPORT from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli) @unittest.skipIf(*missing_mode(TRANSPORT.CCID)) class TestOpenPGP(DestructiveYubikeyTestCase): def test_openpgp_info(self): output = ykman_cli('openpgp', 'info') self.assertIn(...
import unittest from ykman.util import TRANSPORT from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli) @unittest.skipIf(*missing_mode(TRANSPORT.CCID)) class TestOpenPGP(DestructiveYubikeyTestCase): def setUp(self): ykman_cli('openpgp', 'reset', '-f') def test_openpgp_info(self): ...
Reset OpenPGP applet before each test
Reset OpenPGP applet before each test
Python
bsd-2-clause
Yubico/yubikey-manager,Yubico/yubikey-manager
import unittest from ykman.util import TRANSPORT from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli) @unittest.skipIf(*missing_mode(TRANSPORT.CCID)) class TestOpenPGP(DestructiveYubikeyTestCase): + + def setUp(self): + ykman_cli('openpgp', 'reset', '-f') def tes...
Reset OpenPGP applet before each test
## Code Before: import unittest from ykman.util import TRANSPORT from .util import (DestructiveYubikeyTestCase, missing_mode, ykman_cli) @unittest.skipIf(*missing_mode(TRANSPORT.CCID)) class TestOpenPGP(DestructiveYubikeyTestCase): def test_openpgp_info(self): output = ykman_cli('openpgp', 'info') ...
2b1e60a9910561de5a71e83d042b845f6be0bc73
__init__.py
__init__.py
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(): main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.run()
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(loop=None): if loop is not None: every(seconds=1.0/30)(loop) main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_a...
Allow run argument to avoid @every template
Allow run argument to avoid @every template
Python
bsd-2-clause
furbrain/tingbot-python
from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() - def run(): + def run(loop=None): + if loop is not None: + every(seconds=1.0/30)(loop) + main_run_loop.add_wait_callback(input.check_for_qu...
Allow run argument to avoid @every template
## Code Before: from . import platform_specific, input from .graphics import screen from .run_loop import main_run_loop, every platform_specific.fixup_env() def run(): main_run_loop.add_wait_callback(input.check_for_quit_event) main_run_loop.add_after_action_callback(screen.after_loop) main_run_loop.ru...
0d42aa0158bb4f13098bdb5341bead9b1d7c686a
__init__.py
__init__.py
from django.core.mail import mail_managers from django.dispatch import dispatcher from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from kamu.comments.models import KamuComment import settings def comment_notificati...
from django.core.mail import mail_managers from django.dispatch import dispatcher from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from kamu.comments.models import KamuComment import settings def comment_notificati...
Make sure to send email only when a new user is created
Make sure to send email only when a new user is created
Python
agpl-3.0
kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu,kansanmuisti/kamu
from django.core.mail import mail_managers from django.dispatch import dispatcher from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from kamu.comments.models import KamuComment import settings def ...
Make sure to send email only when a new user is created
## Code Before: from django.core.mail import mail_managers from django.dispatch import dispatcher from django.contrib.auth.models import User from django.db.models.signals import post_save from django.contrib.comments.signals import comment_was_posted from kamu.comments.models import KamuComment import settings def co...
ad7e93fa74054e3d962e34807f5d04acd719df33
website/search_migration/migrate.py
website/search_migration/migrate.py
'''Migration script for Search-enabled Models.''' from __future__ import absolute_import import logging from modularodm.query.querydialect import DefaultQueryDialect as Q from website.models import Node from framework.auth import User import website.search.search as search from website.app import init_app logger = l...
'''Migration script for Search-enabled Models.''' from __future__ import absolute_import import logging from modularodm.query.querydialect import DefaultQueryDialect as Q from website.models import Node from framework.auth import User import website.search.search as search from website.app import init_app logger = l...
Add additional logging for users'
Add additional logging for users'
Python
apache-2.0
KAsante95/osf.io,hmoco/osf.io,petermalcolm/osf.io,amyshi188/osf.io,rdhyee/osf.io,samanehsan/osf.io,GaryKriebel/osf.io,mluo613/osf.io,ticklemepierce/osf.io,jnayak1/osf.io,GaryKriebel/osf.io,bdyetton/prettychart,mfraezz/osf.io,GaryKriebel/osf.io,ticklemepierce/osf.io,caneruguz/osf.io,crcresearch/osf.io,abought/osf.io,zac...
'''Migration script for Search-enabled Models.''' from __future__ import absolute_import import logging from modularodm.query.querydialect import DefaultQueryDialect as Q from website.models import Node from framework.auth import User import website.search.search as search from website.app import ...
Add additional logging for users'
## Code Before: '''Migration script for Search-enabled Models.''' from __future__ import absolute_import import logging from modularodm.query.querydialect import DefaultQueryDialect as Q from website.models import Node from framework.auth import User import website.search.search as search from website.app import init...
305849d57cc6897c65b4e0996f70a21f1d873d25
awp/main.py
awp/main.py
import argparse import json import jsonschema import awp.packager import awp.validator # Parse arguments given via command-line interface def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument( '--force', '-f', action='store_true', help='forces the copying of all file...
import argparse import json import jsonschema import awp.packager import awp.validator # Parse arguments given via command-line interface def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument( '--force', '-f', action='store_true', help='forces the copying of all file...
Clarify where packager.json validation error originates
Clarify where packager.json validation error originates
Python
mit
caleb531/alfred-workflow-packager
import argparse import json import jsonschema import awp.packager import awp.validator # Parse arguments given via command-line interface def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument( '--force', '-f', action='store_true', he...
Clarify where packager.json validation error originates
## Code Before: import argparse import json import jsonschema import awp.packager import awp.validator # Parse arguments given via command-line interface def parse_cli_args(): parser = argparse.ArgumentParser() parser.add_argument( '--force', '-f', action='store_true', help='forces the cop...
ad7507f795f465425e72fb6821115e395046b84d
pyshtools/shio/yilm_index_vector.py
pyshtools/shio/yilm_index_vector.py
def YilmIndexVector(i, l, m): """ Compute the index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of an 1D array of spherical harmonic coefficients correspo...
def YilmIndexVector(i, l, m): """ Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of a 1D array of spherical harmonic coefficients correspond...
Add error checks to YilmIndexVector (and update docs)
Add error checks to YilmIndexVector (and update docs)
Python
bsd-3-clause
SHTOOLS/SHTOOLS,MarkWieczorek/SHTOOLS,MarkWieczorek/SHTOOLS,SHTOOLS/SHTOOLS
def YilmIndexVector(i, l, m): """ - Compute the index of an 1D array of spherical harmonic coefficients + Compute the index of a 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns -----...
Add error checks to YilmIndexVector (and update docs)
## Code Before: def YilmIndexVector(i, l, m): """ Compute the index of an 1D array of spherical harmonic coefficients corresponding to i, l, and m. Usage ----- index = YilmIndexVector (i, l, m) Returns ------- index : integer Index of an 1D array of spherical harmonic coeff...
2c7621143a9d110ebb1ea5dc7884f2c21e2786b5
microgear/cache.py
microgear/cache.py
import os import json import sys def get_item(key): try: return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"] except (IOError, ValueError): return None def set_item(key,value): open(os.path.join(os.path.abspat...
import os import json import sys CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0])) def get_item(key): """Return content in cached file in JSON format""" CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) try: return json.loads(open(CACHED_KEY_FILE, "rb").read().decode('UTF-...
Add docstring to function and refactor some code for clarification
Add docstring to function and refactor some code for clarification
Python
isc
netpieio/microgear-python
import os import json import sys + + CURRENT_DIR = os.path.abspath(os.path.dirname(sys.argv[0])) + + def get_item(key): + """Return content in cached file in JSON format""" + CACHED_KEY_FILE = os.path.join(CURRENT_DIR, key) + try: - return json.loads(open(os.path.join(o...
Add docstring to function and refactor some code for clarification
## Code Before: import os import json import sys def get_item(key): try: return json.loads(open(os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])),key), "rb").read().decode('UTF-8'))["_"] except (IOError, ValueError): return None def set_item(key,value): open(os.path.join(os.path.a...
562fa35a036a43526b55546d97490b3f36001a18
robotpy_ext/misc/periodic_filter.py
robotpy_ext/misc/periodic_filter.py
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher """ def __ini...
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher, unless given ...
Create example usage. Rename bypass_level
Create example usage. Rename bypass_level
Python
bsd-3-clause
robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities,robotpy/robotpy-wpilib-utilities,Twinters007/robotpy-wpilib-utilities
import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. - The logger will always print logging levels of WARNING or higher ...
Create example usage. Rename bypass_level
## Code Before: import logging import time class PeriodicFilter: """ Periodic Filter to help keep down clutter in the console. Simply add this filter to your logger and the logger will only print periodically. The logger will always print logging levels of WARNING or higher ""...
ef72be28dc83ff2c73335c6eb13135cab8affe53
troposphere/sso.py
troposphere/sso.py
from . import AWSObject from troposphere import Tags class Assignment(AWSObject): resource_type = "AWS::SSO::Assignment" props = { 'InstanceArn': (basestring, True), 'PermissionSetArn': (basestring, True), 'PrincipalId': (basestring, True), 'PrincipalType': (basestring, True...
from . import AWSObject from . import AWSProperty from troposphere import Tags class Assignment(AWSObject): resource_type = "AWS::SSO::Assignment" props = { 'InstanceArn': (basestring, True), 'PermissionSetArn': (basestring, True), 'PrincipalId': (basestring, True), 'Princip...
Update SSO per 2020-12-18 changes
Update SSO per 2020-12-18 changes
Python
bsd-2-clause
cloudtools/troposphere,cloudtools/troposphere
from . import AWSObject + from . import AWSProperty from troposphere import Tags class Assignment(AWSObject): resource_type = "AWS::SSO::Assignment" props = { 'InstanceArn': (basestring, True), 'PermissionSetArn': (basestring, True), 'PrincipalId': (basestr...
Update SSO per 2020-12-18 changes
## Code Before: from . import AWSObject from troposphere import Tags class Assignment(AWSObject): resource_type = "AWS::SSO::Assignment" props = { 'InstanceArn': (basestring, True), 'PermissionSetArn': (basestring, True), 'PrincipalId': (basestring, True), 'PrincipalType': (...
7c3a3283b3da0c01da012bb823d781036d1847b6
packages/syft/src/syft/core/node/common/node_table/node_route.py
packages/syft/src/syft/core/node/common/node_table/node_route.py
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_...
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement=True) node_...
ADD vpn_endpoint and vpn_key columns
ADD vpn_endpoint and vpn_key columns
Python
apache-2.0
OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft,OpenMined/PySyft
from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, a...
ADD vpn_endpoint and vpn_key columns
## Code Before: from sqlalchemy import Boolean from sqlalchemy import Column from sqlalchemy import ForeignKey from sqlalchemy import Integer from sqlalchemy import String # relative from . import Base class NodeRoute(Base): __tablename__ = "node_route" id = Column(Integer(), primary_key=True, autoincrement...
1f697a2c7bcf0f7769a9fc4f81be676ed5ee97c6
examples/flask/flask_seguro/cart.py
examples/flask/flask_seguro/cart.py
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict={}): if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total = cart_dict["total"] self...
from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict=None): cart_dict = cart_dict or {} if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total...
Fix dangerous default mutable value
Fix dangerous default mutable value
Python
mit
rgcarrasqueira/python-pagseguro,vintasoftware/python-pagseguro,rochacbruno/python-pagseguro
from flask_seguro.products import Products from flask import current_app as app class Cart: - def __init__(self, cart_dict={}): + def __init__(self, cart_dict=None): + cart_dict = cart_dict or {} if cart_dict == {}: self.total = 0 self.subtotal = 0 ...
Fix dangerous default mutable value
## Code Before: from flask_seguro.products import Products from flask import current_app as app class Cart: def __init__(self, cart_dict={}): if cart_dict == {}: self.total = 0 self.subtotal = 0 self.items = [] else: self.total = cart_dict["total"] ...
45ee803cad9b16351a2d02c7ce9d39a36f8f2480
stutuz/__init__.py
stutuz/__init__.py
from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import NestedSetup from flask import Flask, request from flaskext.babel import Babel, get_locale from stutuz.extensio...
from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import NestedSetup from flask import Flask, request from flaskext.babel import Babel, get_locale from stutuz.extensio...
Allow setting locale with a query parameter
Allow setting locale with a query parameter
Python
bsd-2-clause
dag/stutuz
from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import NestedSetup from flask import Flask, request from flaskext.babel import Babel, get_locale ...
Allow setting locale with a query parameter
## Code Before: from __future__ import division from __future__ import absolute_import from __future__ import with_statement from __future__ import print_function from __future__ import unicode_literals from logbook import NestedSetup from flask import Flask, request from flaskext.babel import Babel, get_locale from...
8bfe6e791228ccbc3143f3a8747c68d2e8b0cbb5
runtests.py
runtests.py
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") django.setup() module_root = os.path.dirname(os.path.realpath(__file__)) sys...
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") if django.VERSION >= (1,7): django.setup() module_root = os.path.dirname...
Fix running tests on lower Django versions
Fix running tests on lower Django versions
Python
apache-2.0
AdrianLC/django-parler-rest,edoburu/django-parler-rest
from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") + if django.VERSION >= (1,7): - django.setup() + djang...
Fix running tests on lower Django versions
## Code Before: from django.conf import settings from django.core.management import execute_from_command_line import django import os import sys if not settings.configured: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "testproj.settings") django.setup() module_root = os.path.dirname(os.path.realpath(__...
b6836dd7bccd40eec146bc034cc8ac83b4e7f16a
runtests.py
runtests.py
import sys import os from coverage import coverage from optparse import OptionParser # This envar must be set before importing NoseTestSuiteRunner, # silence flake8 E402 ("module level import not at top of file"). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings") from django_nose import NoseTestSuiteRun...
import sys import os from coverage import coverage from optparse import OptionParser # This envar must be set before importing NoseTestSuiteRunner, # silence flake8 E402 ("module level import not at top of file"). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings") from django_nose import NoseTestSuiteRun...
Extend sys.path with required paths from edx-platform submodule
Extend sys.path with required paths from edx-platform submodule
Python
agpl-3.0
hastexo/edx-shopify,fghaas/edx-shopify
import sys import os from coverage import coverage from optparse import OptionParser # This envar must be set before importing NoseTestSuiteRunner, # silence flake8 E402 ("module level import not at top of file"). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings") from django_nose impor...
Extend sys.path with required paths from edx-platform submodule
## Code Before: import sys import os from coverage import coverage from optparse import OptionParser # This envar must be set before importing NoseTestSuiteRunner, # silence flake8 E402 ("module level import not at top of file"). os.environ.setdefault("DJANGO_SETTINGS_MODULE", "test_settings") from django_nose import ...
bde09206bf308167a11bcb012753d10d845dc810
test_project/blog/models.py
test_project/blog/models.py
from django.db import models from django.contrib.auth.models import User class Entry(models.Model): content = models.TextField() author = models.ForeignKey(User) created = models.DateTimeField() class Comment(models.Model): post = models.ForeignKey(Entry, related_name='comments') content = model...
from django.db import models from django.contrib.auth.models import User class Entry(models.Model): content = models.TextField() author = models.ForeignKey(User) created = models.DateTimeField() class Comment(models.Model): post = models.ForeignKey(Entry, related_name='comments') content = model...
Create SmartTag model to demonstrate multi-word resource names.
Create SmartTag model to demonstrate multi-word resource names.
Python
bsd-3-clause
juanique/django-chocolate,juanique/django-chocolate,juanique/django-chocolate
from django.db import models from django.contrib.auth.models import User class Entry(models.Model): content = models.TextField() author = models.ForeignKey(User) created = models.DateTimeField() class Comment(models.Model): post = models.ForeignKey(Entry, related_name='commen...
Create SmartTag model to demonstrate multi-word resource names.
## Code Before: from django.db import models from django.contrib.auth.models import User class Entry(models.Model): content = models.TextField() author = models.ForeignKey(User) created = models.DateTimeField() class Comment(models.Model): post = models.ForeignKey(Entry, related_name='comments') ...
f35163ad752a52983d7d5ff9bfd383e98db06f0b
tests/test_pycookiecheat.py
tests/test_pycookiecheat.py
from pycookiecheat import chrome_cookies from uuid import uuid4 import pytest def test_raises_on_empty(): with pytest.raises(TypeError): broken = chrome_cookies() def test_no_cookies(): never_been_here = 'http://{}.com'.format(uuid4()) empty_dict = chrome_cookies(never_been_here) assert empty...
from pycookiecheat import chrome_cookies from uuid import uuid4 import pytest import os def test_raises_on_empty(): with pytest.raises(TypeError): broken = chrome_cookies() def test_no_cookies(): if os.getenv('TRAVIS', False) == 'true': never_been_here = 'http://{}.com'.format(uuid4()) ...
Test for travis-CI and skip tests accordingly.
Test for travis-CI and skip tests accordingly.
Python
mit
fxxkhand/pycookiecheat,n8henrie/pycookiecheat
from pycookiecheat import chrome_cookies from uuid import uuid4 import pytest + import os + def test_raises_on_empty(): with pytest.raises(TypeError): broken = chrome_cookies() + def test_no_cookies(): + if os.getenv('TRAVIS', False) == 'true': - never_been_here = 'http://{}...
Test for travis-CI and skip tests accordingly.
## Code Before: from pycookiecheat import chrome_cookies from uuid import uuid4 import pytest def test_raises_on_empty(): with pytest.raises(TypeError): broken = chrome_cookies() def test_no_cookies(): never_been_here = 'http://{}.com'.format(uuid4()) empty_dict = chrome_cookies(never_been_here) ...
5b282d9322a676b4185fcd253f338a342ec5e5ce
.config/i3/py3status/playerctlbar.py
.config/i3/py3status/playerctlbar.py
import subprocess def run(*cmdlist): return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode() def player_args(players): if not players: return 'playerctl', else: return 'playerctl', '-p', players def get_status(players): status = run(*player_args(players), 'status')[:-1...
import subprocess def run(*cmdlist): return subprocess.run( cmdlist, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL).stdout.decode() def player_args(players): if not players: return 'playerctl', else: return 'playerctl', '-p', players def get_status...
Fix stderr from playerctl bar
Fix stderr from playerctl bar
Python
unlicense
louisswarren/dotfiles,louisswarren/dotfiles
import subprocess def run(*cmdlist): - return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode() + return subprocess.run( + cmdlist, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL).stdout.decode() def player_args(players): if not playe...
Fix stderr from playerctl bar
## Code Before: import subprocess def run(*cmdlist): return subprocess.run(cmdlist, stdout=subprocess.PIPE).stdout.decode() def player_args(players): if not players: return 'playerctl', else: return 'playerctl', '-p', players def get_status(players): status = run(*player_args(players...
7527ce1b48f769d33eb5ede3d54413e51eb2ac12
senkumba/models.py
senkumba/models.py
from django.contrib.auth.models import User def user_new_str(self): return self.username if self.get_full_name() == "" else self.get_full_name() # Replace the __str__ method in the User class with our new implementation User.__str__ = user_new_str
from django.contrib import admin from django.contrib.auth.models import User def user_new_str(self): return self.username if self.get_full_name() == "" else self.get_full_name() # Replace the __str__ method in the User class with our new implementation User.__str__ = user_new_str admin.site.site_header = 'SENK...
Change titles for the site
Change titles for the site
Python
mit
lubegamark/senkumba
+ from django.contrib import admin from django.contrib.auth.models import User def user_new_str(self): return self.username if self.get_full_name() == "" else self.get_full_name() # Replace the __str__ method in the User class with our new implementation User.__str__ = user_new_str + + admin....
Change titles for the site
## Code Before: from django.contrib.auth.models import User def user_new_str(self): return self.username if self.get_full_name() == "" else self.get_full_name() # Replace the __str__ method in the User class with our new implementation User.__str__ = user_new_str ## Instruction: Change titles for the site ## Co...
d3a203725d13a7abef091f0070f90826d3225dbc
settings_travis.py
settings_travis.py
import ssl LDAP_SERVER = 'ldap.rserver.de' LDAP_PORT = 3389 LDAP_SSL_PORT = 6636 LDAP_REQUIRE_CERT = ssl.CERT_NONE
import ssl LDAP_SERVER = 'ldap.rserver.de' LDAP_PORT = 3389 LDAP_SSL_PORT = 6636 LDAP_REQUIRE_CERT = ssl.CERT_NONE LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
Fix travis unit test for python 3.3
Fix travis unit test for python 3.3
Python
bsd-2-clause
rroemhild/flask-ldapconn
import ssl LDAP_SERVER = 'ldap.rserver.de' LDAP_PORT = 3389 LDAP_SSL_PORT = 6636 LDAP_REQUIRE_CERT = ssl.CERT_NONE + LDAP_TLS_VERSION = ssl.PROTOCOL_TLSv1
Fix travis unit test for python 3.3
## Code Before: import ssl LDAP_SERVER = 'ldap.rserver.de' LDAP_PORT = 3389 LDAP_SSL_PORT = 6636 LDAP_REQUIRE_CERT = ssl.CERT_NONE ## Instruction: Fix travis unit test for python 3.3 ## Code After: import ssl LDAP_SERVER = 'ldap.rserver.de' LDAP_PORT = 3389 LDAP_SSL_PORT = 6636 LDAP_REQUIRE_CERT = ssl.CERT_NONE LDAP...
c84e22824cd5546406656ecc06a7dcd37a013954
shopit_app/urls.py
shopit_app/urls.py
from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() import authentication_app.views urlpatterns = patterns('', # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', authentication_a...
from rest_frmaework_nested import routers from authentication_app.views import AccountViewSet router = routers.SimpleRouter() router.register(r'accounts', AccountViewSet) urlpatterns = patterns('', # APIendpoints url(r'^api/v1/', include(router.urls)), url('^.*$', IndexView.as_view(), name='index'), )
Add the API endpoint url for the account view set.
Add the API endpoint url for the account view set.
Python
mit
mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app,mvpgomes/shopit-app
- from django.conf.urls import patterns, include, url + from rest_frmaework_nested import routers + from authentication_app.views import AccountViewSet + router = routers.SimpleRouter() + router.register(r'accounts', AccountViewSet) - from django.contrib import admin - admin.autodiscover() - - import authentication...
Add the API endpoint url for the account view set.
## Code Before: from django.conf.urls import patterns, include, url from django.contrib import admin admin.autodiscover() import authentication_app.views urlpatterns = patterns('', # Examples: # url(r'^$', 'gettingstarted.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^$', ...
a57f7c43bc7749de5acd42b6db95d77074308cef
scaper/__init__.py
scaper/__init__.py
"""Top-level module for scaper""" from .core import * __version__ = '0.1.0'
"""Top-level module for scaper""" from .core import * import jams from pkg_resources import resource_filename __version__ = '0.1.0' # Add sound_event namesapce namespace_file = resource_filename(__name__, 'namespaces/sound_event.json') jams.schema.add_namespace(namespace_file)
Add sound_event namespace to jams during init
Add sound_event namespace to jams during init
Python
bsd-3-clause
justinsalamon/scaper
"""Top-level module for scaper""" from .core import * + import jams + from pkg_resources import resource_filename __version__ = '0.1.0' + # Add sound_event namesapce + namespace_file = resource_filename(__name__, 'namespaces/sound_event.json') + jams.schema.add_namespace(namespace_file) -
Add sound_event namespace to jams during init
## Code Before: """Top-level module for scaper""" from .core import * __version__ = '0.1.0' ## Instruction: Add sound_event namespace to jams during init ## Code After: """Top-level module for scaper""" from .core import * import jams from pkg_resources import resource_filename __version__ = '0.1.0' # Add sound...
b62c8c905cdd332a0073ce462be3e5c5b17b282d
api/webview/views.py
api/webview/views.py
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import Docum...
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializers import Docum...
Make the view List only remove Create
Make the view List only remove Create
Python
apache-2.0
erinspace/scrapi,CenterForOpenScience/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,CenterForOpenScience/scrapi,fabianvf/scrapi,felliott/scrapi
from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializ...
Make the view List only remove Create
## Code Before: from rest_framework import generics from rest_framework import permissions from rest_framework.response import Response from rest_framework.decorators import api_view from django.views.decorators.clickjacking import xframe_options_exempt from api.webview.models import Document from api.webview.serializ...
067b557258a85945635a880ced65454cfa2b61af
supermega/tests/test_session.py
supermega/tests/test_session.py
import unittest import hashlib from .. import Session from .. import models class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9431103cb989f2913cbc5037670...
import unittest import hashlib from .. import Session from .. import models class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9431103cb989f2913cbc5037670...
Add test for key derivation
Add test for key derivation
Python
bsd-3-clause
lmb/Supermega
import unittest import hashlib from .. import Session from .. import models class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9...
Add test for key derivation
## Code Before: import unittest import hashlib from .. import Session from .. import models class TestSession(unittest.TestCase): def setUp(self): self.sess = Session() def test_public_file_download(self): url = 'https://mega.co.nz/#!2ctGgQAI!AkJMowjRiXVcSrRLn3d-e1vl47ZxZEK0CbrHGIKFY-E' sha256 = '9431103cb98...
bbfe056602075a46b231dc28ddcada7f525ce927
conftest.py
conftest.py
import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='pa...
import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hello", password='pa...
Use yield_fixture for app fixture
Use yield_fixture for app fixture
Python
agpl-3.0
ideascube/ideascube,Lcaracol/ideasbox.lan,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,Lcaracol/ideasbox.lan,Lcaracol/ideasbox.lan
import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(...
Use yield_fixture for app fixture
## Code Before: import pytest import django_webtest from django.core.urlresolvers import reverse from ideasbox.tests.factories import UserFactory @pytest.fixture() def user(): return UserFactory(short_name="Hello", password='password') @pytest.fixture() def staffuser(): return UserFactory(short_name="Hell...
9e7aed847c2d5fcd6e00bc787d8b3558b590f605
api/logs/urls.py
api/logs/urls.py
from django.conf.urls import url from api.logs import views urlpatterns = [ url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name), url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name), ]
from django.conf.urls import url from api.logs import views urlpatterns = [ url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name), url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name), url(r'^(?P<log_id>\w+)/added_contribut...
Add /v2/logs/log_id/added_contributors/ to list of URL's.
Add /v2/logs/log_id/added_contributors/ to list of URL's.
Python
apache-2.0
abought/osf.io,mfraezz/osf.io,TomHeatwole/osf.io,chennan47/osf.io,RomanZWang/osf.io,alexschiller/osf.io,billyhunt/osf.io,crcresearch/osf.io,saradbowman/osf.io,acshi/osf.io,jnayak1/osf.io,RomanZWang/osf.io,emetsger/osf.io,KAsante95/osf.io,zachjanicki/osf.io,mattclark/osf.io,RomanZWang/osf.io,emetsger/osf.io,monikagrabow...
from django.conf.urls import url from api.logs import views urlpatterns = [ url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name), url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name), + url(r'^(?P<log_id>\w+)...
Add /v2/logs/log_id/added_contributors/ to list of URL's.
## Code Before: from django.conf.urls import url from api.logs import views urlpatterns = [ url(r'^(?P<log_id>\w+)/$', views.NodeLogDetail.as_view(), name=views.NodeLogDetail.view_name), url(r'^(?P<log_id>\w+)/nodes/$', views.LogNodeList.as_view(), name=views.LogNodeList.view_name), ] ## Instruction: Add /v2...
a9c6e045631103fe8508fd1b60d6076c05092fe1
tests/examples/customnode/nodes.py
tests/examples/customnode/nodes.py
from viewflow.activation import AbstractGateActivation, Activation from viewflow.flow import base from viewflow.token import Token class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._split_count = self.flow_task._task_count_callback(self.process) @Activation.status.s...
from viewflow.activation import AbstractGateActivation from viewflow.flow import base from viewflow.token import Token class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._split_count = self.flow_task._task_count_callback(self.process) def activate_next(self): ...
Add undo to custom node sample
Add undo to custom node sample
Python
agpl-3.0
ribeiro-ucl/viewflow,codingjoe/viewflow,pombredanne/viewflow,pombredanne/viewflow,codingjoe/viewflow,codingjoe/viewflow,viewflow/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow,viewflow/viewflow,ribeiro-ucl/viewflow
- from viewflow.activation import AbstractGateActivation, Activation + from viewflow.activation import AbstractGateActivation from viewflow.flow import base from viewflow.token import Token class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._split_count = se...
Add undo to custom node sample
## Code Before: from viewflow.activation import AbstractGateActivation, Activation from viewflow.flow import base from viewflow.token import Token class DynamicSplitActivation(AbstractGateActivation): def calculate_next(self): self._split_count = self.flow_task._task_count_callback(self.process) @Act...
fffca3d2198f7c65b2e4fa2b805efa54f4c9fdb9
tests/zeus/artifacts/test_xunit.py
tests/zeus/artifacts/test_xunit.py
from io import BytesIO from zeus.artifacts.xunit import XunitHandler from zeus.constants import Result from zeus.models import Job from zeus.utils.testresult import TestResult as ZeusTestResult def test_result_generation(sample_xunit): job = Job() fp = BytesIO(sample_xunit.encode("utf8")) handler = Xun...
from io import BytesIO from zeus.artifacts.xunit import XunitHandler from zeus.constants import Result from zeus.models import Job from zeus.utils.testresult import TestResult as ZeusTestResult def test_result_generation(sample_xunit): job = Job() fp = BytesIO(sample_xunit.encode("utf8")) handler = Xun...
Fix test case being integers
test: Fix test case being integers
Python
apache-2.0
getsentry/zeus,getsentry/zeus,getsentry/zeus,getsentry/zeus
from io import BytesIO from zeus.artifacts.xunit import XunitHandler from zeus.constants import Result from zeus.models import Job from zeus.utils.testresult import TestResult as ZeusTestResult def test_result_generation(sample_xunit): job = Job() fp = BytesIO(sample_xunit.encode("ut...
Fix test case being integers
## Code Before: from io import BytesIO from zeus.artifacts.xunit import XunitHandler from zeus.constants import Result from zeus.models import Job from zeus.utils.testresult import TestResult as ZeusTestResult def test_result_generation(sample_xunit): job = Job() fp = BytesIO(sample_xunit.encode("utf8")) ...
cfde8a339c52c1875cb3b863ace3cad6174eb54c
account_cost_spread/models/account_invoice.py
account_cost_spread/models/account_invoice.py
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Override, button Validate on invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line...
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Invoked when validating the invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: rec.invoice_line_...
Fix method description in account_cost_spread
Fix method description in account_cost_spread
Python
agpl-3.0
onesteinbv/addons-onestein,onesteinbv/addons-onestein,onesteinbv/addons-onestein
from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): - """Override, button Validate on invoices.""" + """Invoked when validating the invoices.""" res = super(AccountInvoice, self...
Fix method description in account_cost_spread
## Code Before: from odoo import api, models class AccountInvoice(models.Model): _inherit = 'account.invoice' @api.multi def action_move_create(self): """Override, button Validate on invoices.""" res = super(AccountInvoice, self).action_move_create() for rec in self: ...
08f633cdf0f5dcd1940da46e91c175e81b39ad3f
setup.py
setup.py
from distutils.core import setup from distutils.extension import Extension try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", "dtrace_cyt...
from distutils.core import setup from distutils.extension import Extension import sys try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", ...
Set Cython language_level to 3 when compiling for python3
Set Cython language_level to 3 when compiling for python3
Python
mit
tmetsch/python-dtrace,tmetsch/python-dtrace
from distutils.core import setup from distutils.extension import Extension + import sys try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", ...
Set Cython language_level to 3 when compiling for python3
## Code Before: from distutils.core import setup from distutils.extension import Extension try: from Cython.Build import build_ext, cythonize BUILD_EXTENSION = {'build_ext': build_ext} EXT_MODULES = cythonize([Extension("dtrace", ["dtrace_cython/dtrace_h.pxd", ...
6a5c9ccf0bd2582cf42577712309b8fd6e912966
blo/__init__.py
blo/__init__.py
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'] self._template_dir = config...
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'].replace('"', '') self._temp...
Add replace double quotation mark from configuration file parameters.
Add replace double quotation mark from configuration file parameters.
Python
mit
10nin/blo,10nin/blo
import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) - self._db_file_path = config['DB']['DB_PATH'] + self....
Add replace double quotation mark from configuration file parameters.
## Code Before: import configparser from blo.BloArticle import BloArticle from blo.DBControl import DBControl class Blo: def __init__(self, config_file_path): config = configparser.ConfigParser() config.read(config_file_path) self._db_file_path = config['DB']['DB_PATH'] self._templ...
1fffdb60aa4eb875bfbd961773d0cf5066dc38e2
django_website/views.py
django_website/views.py
from __future__ import absolute_import from django.contrib.comments.models import Comment from django.contrib.sitemaps import views as sitemap_views from django.shortcuts import render from django.views.decorators.cache import cache_page from django.views.decorators.csrf import requires_csrf_token from django.views.ge...
from django.shortcuts import render from django.views.decorators.csrf import requires_csrf_token @requires_csrf_token def server_error(request, template_name='500.html'): """ Custom 500 error handler for static stuff. """ return render(request, template_name)
Remove dead code. This isn't wired in any URLconf.
Remove dead code. This isn't wired in any URLconf.
Python
bsd-3-clause
nanuxbe/django,xavierdutreilh/djangoproject.com,vxvinh1511/djangoproject.com,rmoorman/djangoproject.com,gnarf/djangoproject.com,django/djangoproject.com,rmoorman/djangoproject.com,relekang/djangoproject.com,hassanabidpk/djangoproject.com,alawnchen/djangoproject.com,alawnchen/djangoproject.com,khkaminska/djangoproject.c...
- from __future__ import absolute_import - - from django.contrib.comments.models import Comment - from django.contrib.sitemaps import views as sitemap_views from django.shortcuts import render - from django.views.decorators.cache import cache_page from django.views.decorators.csrf import requires_csrf_token - from...
Remove dead code. This isn't wired in any URLconf.
## Code Before: from __future__ import absolute_import from django.contrib.comments.models import Comment from django.contrib.sitemaps import views as sitemap_views from django.shortcuts import render from django.views.decorators.cache import cache_page from django.views.decorators.csrf import requires_csrf_token from...
27a0226ec444523034d739a00a999b089ce116ba
enthought/chaco/tools/api.py
enthought/chaco/tools/api.py
from better_zoom import BetterZoom from better_selecting_zoom import BetterSelectingZoom from broadcaster import BroadcasterTool from dataprinter import DataPrinter from data_label_tool import DataLabelTool from drag_zoom import DragZoom from enthought.enable.tools.drag_tool import DragTool from draw_points_tool import...
from better_zoom import BetterZoom from better_selecting_zoom import BetterSelectingZoom from broadcaster import BroadcasterTool from dataprinter import DataPrinter from data_label_tool import DataLabelTool from enthought.enable.tools.drag_tool import DragTool from draw_points_tool import DrawPointsTool from highlight_...
Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
[Chaco] Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
Python
bsd-3-clause
ContinuumIO/chaco,tommy-u/chaco,tommy-u/chaco,ContinuumIO/chaco,tommy-u/chaco,ContinuumIO/chaco,burnpanck/chaco,burnpanck/chaco,ContinuumIO/chaco,burnpanck/chaco
from better_zoom import BetterZoom from better_selecting_zoom import BetterSelectingZoom from broadcaster import BroadcasterTool from dataprinter import DataPrinter from data_label_tool import DataLabelTool - from drag_zoom import DragZoom from enthought.enable.tools.drag_tool import DragTool from draw_po...
Remove deprecated DragZoom from Chaco tools API to eliminate irrelevant BaseZoomTool deprecation warning. DragZoom is still used in 4 Chaco examples
## Code Before: from better_zoom import BetterZoom from better_selecting_zoom import BetterSelectingZoom from broadcaster import BroadcasterTool from dataprinter import DataPrinter from data_label_tool import DataLabelTool from drag_zoom import DragZoom from enthought.enable.tools.drag_tool import DragTool from draw_po...
0df76d66fb6a2425c6ccc8a3a75d41599b2545c6
auth0/v2/authentication/delegated.py
auth0/v2/authentication/delegated.py
from .base import AuthenticationBase class Delegated(AuthenticationBase): def __init__(self, domain): self.domain = domain def get_token(self, client_id, target, api_type, grant_type, id_token=None, refresh_token=None): if id_token and refresh_token: raise Valu...
from .base import AuthenticationBase class Delegated(AuthenticationBase): """Delegated authentication endpoints. Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def __init__(self, domain): self.domain = domain def get_token(self, client_id, target, api_type,...
Add docstrings in Delegated class
Add docstrings in Delegated class
Python
mit
auth0/auth0-python,auth0/auth0-python
from .base import AuthenticationBase class Delegated(AuthenticationBase): + + """Delegated authentication endpoints. + + Args: + domain (str): Your auth0 domain (e.g: username.auth0.com) + """ def __init__(self, domain): self.domain = domain def get_token(self...
Add docstrings in Delegated class
## Code Before: from .base import AuthenticationBase class Delegated(AuthenticationBase): def __init__(self, domain): self.domain = domain def get_token(self, client_id, target, api_type, grant_type, id_token=None, refresh_token=None): if id_token and refresh_token: ...
305969cedb966d1e5cd340d531727bb984ac35a8
whitenoise/generators/sqlalchemy.py
whitenoise/generators/sqlalchemy.py
import random from whitenoise.generators import BaseGenerator class SelectGenerator(BaseGenerator): ''' Creates a value by selecting from another SQLAlchemy table Depends on SQLAlchemy, and receiving a session object from the Fixture runner the SQLAlchemy fixture runner handles this for us Receives...
import random from whitenoise.generators import BaseGenerator class SelectGenerator(BaseGenerator): ''' Creates a value by selecting from another SQLAlchemy table Depends on SQLAlchemy, and receiving a session object from the Fixture runner the SQLAlchemy fixture runner handles this for us Receives...
Add a generator for association tables
Add a generator for association tables
Python
mit
James1345/white-noise
import random from whitenoise.generators import BaseGenerator class SelectGenerator(BaseGenerator): ''' Creates a value by selecting from another SQLAlchemy table Depends on SQLAlchemy, and receiving a session object from the Fixture runner the SQLAlchemy fixture runner handles this for...
Add a generator for association tables
## Code Before: import random from whitenoise.generators import BaseGenerator class SelectGenerator(BaseGenerator): ''' Creates a value by selecting from another SQLAlchemy table Depends on SQLAlchemy, and receiving a session object from the Fixture runner the SQLAlchemy fixture runner handles this for...
ee5ab61090cef682f37631a8c3f5764bdda63772
xpserver_web/tests/unit/test_web.py
xpserver_web/tests/unit/test_web.py
from django.core.urlresolvers import resolve from xpserver_web.views import main def test_root_resolves_to_hello_world(): found = resolve('/') assert found.func == main
from django.core.urlresolvers import resolve from xpserver_web.views import main, register def test_root_resolves_to_main(): found = resolve('/') assert found.func == main def test_register_resolves_to_main(): found = resolve('/register/') assert found.func == register
Add unit test for register
Add unit test for register
Python
mit
xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server,xp2017-hackergarden/server
from django.core.urlresolvers import resolve - from xpserver_web.views import main + from xpserver_web.views import main, register - def test_root_resolves_to_hello_world(): + def test_root_resolves_to_main(): found = resolve('/') assert found.func == main + def test_register_resolves_to_main(...
Add unit test for register
## Code Before: from django.core.urlresolvers import resolve from xpserver_web.views import main def test_root_resolves_to_hello_world(): found = resolve('/') assert found.func == main ## Instruction: Add unit test for register ## Code After: from django.core.urlresolvers import resolve from xpserver_web.vi...
e120858d5cb123e9f3422ddb15ce79bde8d05d64
statsd/__init__.py
statsd/__init__.py
import socket try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd'] VERSION = (0, 4, 0) __version__ = '.'.join(map(str, VERSION)) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localhost') ...
import socket import os try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd'] VERSION = (0, 4, 0) __version__ = '.'.join(map(str, VERSION)) if settings: try: host = getattr(settings, 'STATSD_HOST', 'localho...
Read settings from environment, if available
Read settings from environment, if available
Python
mit
lyft/pystatsd,jsocol/pystatsd,deathowl/pystatsd,Khan/pystatsd,Khan/pystatsd,smarkets/pystatsd,wujuguang/pystatsd,lyft/pystatsd
import socket + import os try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd'] VERSION = (0, 4, 0) __version__ = '.'.join(map(str, VERSION)) if settings: try: host = g...
Read settings from environment, if available
## Code Before: import socket try: from django.conf import settings except ImportError: settings = None from client import StatsClient __all__ = ['StatsClient', 'statsd'] VERSION = (0, 4, 0) __version__ = '.'.join(map(str, VERSION)) if settings: try: host = getattr(settings, 'STATSD_HOST', 'l...
7d3ffe4582a5b4032f9a59a3ea8edfded57a7a1f
src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py
src/nodeconductor_openstack/openstack/migrations/0031_tenant_backup_storage.py
from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.db import migrations from nodeconductor.quotas import models as quotas_models from .. import models def cleanup_tenant_quotas(apps, schema_editor): for obj in models.Tenant.objects.all(): quot...
from __future__ import unicode_literals from django.db import migrations from .. import models def cleanup_tenant_quotas(apps, schema_editor): quota_names = models.Tenant.get_quotas_names() for obj in models.Tenant.objects.all(): obj.quotas.exclude(name__in=quota_names).delete() class Migration(mi...
Clean up quota cleanup migration
Clean up quota cleanup migration [WAL-433]
Python
mit
opennode/nodeconductor-openstack
from __future__ import unicode_literals - from django.contrib.contenttypes.models import ContentType from django.db import migrations - - from nodeconductor.quotas import models as quotas_models from .. import models def cleanup_tenant_quotas(apps, schema_editor): + quota_names = models.Tenant....
Clean up quota cleanup migration
## Code Before: from __future__ import unicode_literals from django.contrib.contenttypes.models import ContentType from django.db import migrations from nodeconductor.quotas import models as quotas_models from .. import models def cleanup_tenant_quotas(apps, schema_editor): for obj in models.Tenant.objects.all...
e45fff968f37f558a49cf82b582d1f514a97b5af
tests/test_pool.py
tests/test_pool.py
import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r = s.select([1, 2...
import asyncio import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool from aioes.transport import Endpoint from aioes.connection import Connection class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): ...
Add more tests for pool
Add more tests for pool
Python
apache-2.0
aio-libs/aioes
+ import asyncio import random import unittest - from aioes.pool import RandomSelector, RoundRobinSelector + from aioes.pool import RandomSelector, RoundRobinSelector, ConnectionPool + from aioes.transport import Endpoint + from aioes.connection import Connection class TestRandomSelector(unittest.TestCas...
Add more tests for pool
## Code Before: import random import unittest from aioes.pool import RandomSelector, RoundRobinSelector class TestRandomSelector(unittest.TestCase): def setUp(self): random.seed(123456) def tearDown(self): random.seed(None) def test_select(self): s = RandomSelector() r ...
aa8820bd7b78ba5729e0a7a17e43b87bfd033980
tests/runtests.py
tests/runtests.py
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import unittest import util_tests import jsonpickle_test import thirdparty_tests def suite(): suite = unittest.TestSuite() suite.addTest(util_tests.suite()) suite.addTest(jsonpickle_test.suite()) suite.addTest(thirdp...
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import unittest import util_tests import jsonpickle_test import thirdparty_tests def suite(): suite = unittest.TestSuite() suite.addTest(util_tests.suite()) suite.addTest(jsonpickle_test.suite()) suite.addTest(thirdp...
Return correct status code to shell when tests fail.
Return correct status code to shell when tests fail. When tests fail (due to e.g. missing feedparser), then the exit code of tests/runtests.py is 0, which is treated by shell as success. Patch by Arfrever Frehtes Taifersar Arahesis.
Python
bsd-3-clause
mandx/jsonpickle,dongguangming/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle,mandx/jsonpickle,dongguangming/jsonpickle
import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import unittest import util_tests import jsonpickle_test import thirdparty_tests def suite(): suite = unittest.TestSuite() suite.addTest(util_tests.suite()) suite.addTest(jsonpickle_test.sui...
Return correct status code to shell when tests fail.
## Code Before: import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import unittest import util_tests import jsonpickle_test import thirdparty_tests def suite(): suite = unittest.TestSuite() suite.addTest(util_tests.suite()) suite.addTest(jsonpickle_test.suite()) suit...
4bac0cfeb2d8def6183b4249f0ea93329b282cb4
botbot/envchecks.py
botbot/envchecks.py
"""Tools for checking environment variables""" import os from configparser import NoOptionError from .config import CONFIG def path_sufficient(): """ Checks whether all of the given paths are in the PATH environment variable """ paths = CONFIG.get('important', 'pathitems').split(':') for path...
"""Tools for checking environment variables""" import os from configparser import NoOptionError from .config import CONFIG def path_sufficient(): """ Checks whether all of the given paths are in the PATH environment variable """ paths = CONFIG.get('important', 'pathitems').split(':') for path...
Add checker for LD_LIBRARY_PATH env variable
Add checker for LD_LIBRARY_PATH env variable
Python
mit
jackstanek/BotBot,jackstanek/BotBot
"""Tools for checking environment variables""" import os from configparser import NoOptionError from .config import CONFIG def path_sufficient(): """ Checks whether all of the given paths are in the PATH environment variable """ paths = CONFIG.get('important', 'pathitems...
Add checker for LD_LIBRARY_PATH env variable
## Code Before: """Tools for checking environment variables""" import os from configparser import NoOptionError from .config import CONFIG def path_sufficient(): """ Checks whether all of the given paths are in the PATH environment variable """ paths = CONFIG.get('important', 'pathitems').split('...
805e67ad540e3072929dea30b8894af87fc622ef
uiharu/__init__.py
uiharu/__init__.py
import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as weather_blueprint app....
import logging log = logging.getLogger(__name__)
Remove flask usage in init
Remove flask usage in init
Python
mit
kennydo/uiharu
import logging - - from flask import Flask log = logging.getLogger(__name__) - def create_app(config_dict): - app = Flask(__name__, static_folder=None) - app.config.update(**config_dict) - - from uiharu.api.views import api as api_blueprint - from uiharu.weather.views import weather as...
Remove flask usage in init
## Code Before: import logging from flask import Flask log = logging.getLogger(__name__) def create_app(config_dict): app = Flask(__name__, static_folder=None) app.config.update(**config_dict) from uiharu.api.views import api as api_blueprint from uiharu.weather.views import weather as weather_blu...
b047685088b9179e0c784114ff4a41509dbfdf7d
tests/test_utils.py
tests/test_utils.py
from django_logutils.utils import add_items_to_message def test_add_items_to_message(): msg = "log message" items = {'user': 'benny', 'email': 'benny@example.com'} msg = add_items_to_message(msg, items) assert msg == 'log message user=benny email=benny@example.com'
from django_logutils.utils import add_items_to_message def test_add_items_to_message(): msg = "log message" items = {'user': 'benny', 'email': 'benny@example.com'} msg = add_items_to_message(msg, items) assert msg.startswith('log message') assert 'user=benny' in msg assert 'email=benny@example...
Fix utils test and add an extra test.
Fix utils test and add an extra test.
Python
bsd-3-clause
jsmits/django-logutils,jsmits/django-logutils
from django_logutils.utils import add_items_to_message def test_add_items_to_message(): msg = "log message" items = {'user': 'benny', 'email': 'benny@example.com'} msg = add_items_to_message(msg, items) - assert msg == 'log message user=benny email=benny@example.com' + assert msg.sta...
Fix utils test and add an extra test.
## Code Before: from django_logutils.utils import add_items_to_message def test_add_items_to_message(): msg = "log message" items = {'user': 'benny', 'email': 'benny@example.com'} msg = add_items_to_message(msg, items) assert msg == 'log message user=benny email=benny@example.com' ## Instruction: Fix...
34db760c5b763ad2df02398d58ea417b47b785e7
geotrek/zoning/views.py
geotrek/zoning/views.py
from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_page from django.conf import settings from django.utils.decorators import method_decorator from djgeojson.views import GeoJSONLayerView from .models import City, RestrictedArea, RestrictedAreaType, District class LandLayer...
from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_page from django.conf import settings from django.utils.decorators import method_decorator from djgeojson.views import GeoJSONLayerView from .models import City, RestrictedArea, RestrictedAreaType, District class LandLayer...
Change cache land, use settings mapentity
Change cache land, use settings mapentity
Python
bsd-2-clause
GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_page from django.conf import settings from django.utils.decorators import method_decorator from djgeojson.views import GeoJSONLayerView from .models import City, RestrictedArea, RestrictedAreaType, District ...
Change cache land, use settings mapentity
## Code Before: from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_page from django.conf import settings from django.utils.decorators import method_decorator from djgeojson.views import GeoJSONLayerView from .models import City, RestrictedArea, RestrictedAreaType, District ...
3875b1ec7d056d337cc1c02d9567cd7ff1ae9748
utils/sub8_ros_tools/sub8_ros_tools/init_helpers.py
utils/sub8_ros_tools/sub8_ros_tools/init_helpers.py
import rospy from time import time def wait_for_param(param_name, timeout=None, poll_rate=0.1): '''Blocking wait for a parameter named $parameter_name to exist Poll at frequency $poll_rate Once the parameter exists, return get and return it. This function intentionally leaves failure logging ...
import rospy import rostest import time def wait_for_param(param_name, timeout=None, poll_rate=0.1): '''Blocking wait for a parameter named $parameter_name to exist Poll at frequency $poll_rate Once the parameter exists, return get and return it. This function intentionally leaves failure log...
Add init-helper 'wait for subscriber'
UTILS: Add init-helper 'wait for subscriber' For integration-testing purposes it is often useful to wait until a particular node subscribes to you
Python
mit
pemami4911/Sub8,pemami4911/Sub8,pemami4911/Sub8
import rospy - from time import time + import rostest + import time def wait_for_param(param_name, timeout=None, poll_rate=0.1): '''Blocking wait for a parameter named $parameter_name to exist Poll at frequency $poll_rate Once the parameter exists, return get and return it. ...
Add init-helper 'wait for subscriber'
## Code Before: import rospy from time import time def wait_for_param(param_name, timeout=None, poll_rate=0.1): '''Blocking wait for a parameter named $parameter_name to exist Poll at frequency $poll_rate Once the parameter exists, return get and return it. This function intentionally leaves ...
7376a29d69ac78cabc5d392cb748f708ffa0e68c
tests/pretty_format_json_test.py
tests/pretty_format_json_test.py
import tempfile import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(fil...
import io import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty_format_json(filename,...
Write to temp directories in such a way that files get cleaned up
Write to temp directories in such a way that files get cleaned up
Python
mit
Coverfox/pre-commit-hooks,Harwood/pre-commit-hooks,pre-commit/pre-commit-hooks
- import tempfile + import io import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), ...
Write to temp directories in such a way that files get cleaned up
## Code Before: import tempfile import pytest from pre_commit_hooks.pretty_format_json import pretty_format_json from testing.util import get_resource_path @pytest.mark.parametrize(('filename', 'expected_retval'), ( ('not_pretty_formatted_json.json', 1), ('pretty_formatted_json.json', 0), )) def test_pretty...