commit
stringlengths
40
40
old_file
stringlengths
4
106
new_file
stringlengths
4
106
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
2.95k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
7
43k
ndiff
stringlengths
52
3.31k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
diff
stringlengths
49
3.61k
d48e59f4b1174529a4d2eca8731472a5bf371621
simpleseo/templatetags/seo.py
simpleseo/templatetags/seo.py
from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('simpleseo/metadata...
from django.forms.models import model_to_dict from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'')...
Allow to set default value in template
Allow to set default value in template
Python
bsd-3-clause
Glamping-Hub/django-painless-seo,Glamping-Hub/django-painless-seo,AMongeMoreno/django-painless-seo,AMongeMoreno/django-painless-seo
+ from django.forms.models import model_to_dict from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return descr...
Allow to set default value in template
## Code Before: from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return description.replace('\"', '\'') @register.inclusion_tag('si...
+ from django.forms.models import model_to_dict from django.template import Library from django.utils.translation import get_language from simpleseo import settings from simpleseo.models import SeoMetadata register = Library() @register.filter def single_quotes(description): return descr...
2c8077039573296ecbc31ba9b7c5d6463cf39124
cmakelists_parsing/parsing.py
cmakelists_parsing/parsing.py
'''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z...
'''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z...
Fix up output by including endls.
Fix up output by including endls.
Python
apache-2.0
wjwwood/parse_cmake,ijt/cmakelists_parsing
'''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): gr...
Fix up output by including endls.
## Code Before: '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compi...
'''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): gr...
dfdeaf536466cfa8003af4cd5341d1d7127ea6b7
py/_test_py2go.py
py/_test_py2go.py
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def return_m...
import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3}] def ...
Update python script for pep8 style
Update python script for pep8 style
Python
mit
sensorbee/py,sensorbee/py
import datetime + def return_true(): return True + def return_false(): return False + def return_int(): return 123 + def return_float(): return 1.0 + def return_string(): return "ABC" + def return_bytearray(): return bytearray('abcdefg') + ...
Update python script for pep8 style
## Code Before: import datetime def return_true(): return True def return_false(): return False def return_int(): return 123 def return_float(): return 1.0 def return_string(): return "ABC" def return_bytearray(): return bytearray('abcdefg') def return_array(): return [1, 2, {"key": 3...
import datetime + def return_true(): return True + def return_false(): return False + def return_int(): return 123 + def return_float(): return 1.0 + def return_string(): return "ABC" + def return_bytearray(): return bytearray('abcdefg') + ...
6336e8e13c01b6a81b8586499e7a3e8fc8b532a8
launch_control/commands/interface.py
launch_control/commands/interface.py
from launch_control.utils.registry import RegistryBase class Command(RegistryBase): """ Base class for all command line tool sub-commands. """ def __init__(self, parser, args): """ Prepare instance for executing commands. This method is called immediately after all arguments a...
import inspect from launch_control.utils.registry import RegistryBase class Command(RegistryBase): """ Base class for all command line tool sub-commands. """ def __init__(self, parser, args): """ Prepare instance for executing commands. This method is called immediately afte...
Use inspect.getdoc() instead of plain __doc__
Use inspect.getdoc() instead of plain __doc__
Python
agpl-3.0
Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server,Linaro/lava-server
+ import inspect + from launch_control.utils.registry import RegistryBase + class Command(RegistryBase): """ Base class for all command line tool sub-commands. """ def __init__(self, parser, args): """ Prepare instance for executing commands. This met...
Use inspect.getdoc() instead of plain __doc__
## Code Before: from launch_control.utils.registry import RegistryBase class Command(RegistryBase): """ Base class for all command line tool sub-commands. """ def __init__(self, parser, args): """ Prepare instance for executing commands. This method is called immediately after...
+ import inspect + from launch_control.utils.registry import RegistryBase + class Command(RegistryBase): """ Base class for all command line tool sub-commands. """ def __init__(self, parser, args): """ Prepare instance for executing commands. This met...
2e406c8cca9e55c9b8e2dcbf33005aa580ef74ea
tests/state/test_in_memory_key_value_store.py
tests/state/test_in_memory_key_value_store.py
from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore def test_inMemoryKeyValueStore(): store = InMemoryKeyValueStore('teststore') store['a'] = 1 assert store['a'] == 1 store['a'] = 2 assert store['a'] == 2
import pytest from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore def test_inMemoryKeyValueStore(): store = InMemoryKeyValueStore('teststore') store['a'] = 1 assert store['a'] == 1 store['a'] = 2 assert store['a'] == 2 del store['a'] assert store.get('...
Test behaviour of key deletion
Test behaviour of key deletion
Python
apache-2.0
wintoncode/winton-kafka-streams
+ import pytest from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore def test_inMemoryKeyValueStore(): store = InMemoryKeyValueStore('teststore') store['a'] = 1 assert store['a'] == 1 store['a'] = 2 assert store['a'] == 2 + del store...
Test behaviour of key deletion
## Code Before: from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore def test_inMemoryKeyValueStore(): store = InMemoryKeyValueStore('teststore') store['a'] = 1 assert store['a'] == 1 store['a'] = 2 assert store['a'] == 2 ## Instruction: Test behaviour of key d...
+ import pytest from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore def test_inMemoryKeyValueStore(): store = InMemoryKeyValueStore('teststore') store['a'] = 1 assert store['a'] == 1 store['a'] = 2 assert store['a'] == 2 + + del store...
a6061ef140e371101c3d04c5b85562586293eee8
scrappyr/scraps/tests/test_models.py
scrappyr/scraps/tests/test_models.py
from test_plus.test import TestCase from ..models import Scrap class TestScrap(TestCase): def test__str__(self): scrap = Scrap(raw_title='hello') assert str(scrap) == 'hello' def test_html_title(self): scrap = Scrap(raw_title='hello') assert scrap.html_title == 'hello' ...
from test_plus.test import TestCase from ..models import Scrap class TestScrap(TestCase): def test__str__(self): scrap = Scrap(raw_title='hello') assert str(scrap) == 'hello' def test_html_title(self): scrap = Scrap(raw_title='hello') assert scrap.html_title == 'hello' ...
Add test of block-elements in scrap title
Add test of block-elements in scrap title
Python
mit
tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app,tonysyu/scrappyr-app
from test_plus.test import TestCase from ..models import Scrap class TestScrap(TestCase): def test__str__(self): scrap = Scrap(raw_title='hello') assert str(scrap) == 'hello' def test_html_title(self): scrap = Scrap(raw_title='hello') assert scrap...
Add test of block-elements in scrap title
## Code Before: from test_plus.test import TestCase from ..models import Scrap class TestScrap(TestCase): def test__str__(self): scrap = Scrap(raw_title='hello') assert str(scrap) == 'hello' def test_html_title(self): scrap = Scrap(raw_title='hello') assert scrap.html_title ...
from test_plus.test import TestCase from ..models import Scrap class TestScrap(TestCase): def test__str__(self): scrap = Scrap(raw_title='hello') assert str(scrap) == 'hello' def test_html_title(self): scrap = Scrap(raw_title='hello') assert scrap...
3c1357627bf1921fdee114b60f96f42c328120b4
caramel/__init__.py
caramel/__init__.py
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = C...
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = C...
Move pyramid_tm include to caramel.main
Caramel: Move pyramid_tm include to caramel.main Move the setting to include pyramid_tm to caramel.main from ini files. This is a vital setting that should never be changed by the user.
Python
agpl-3.0
ModioAB/caramel,ModioAB/caramel
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_sessio...
Move pyramid_tm include to caramel.main
## Code Before: from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine...
from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_sessio...
013a3f11453787e18f7acd08c7e54fede59b1b01
letsencrypt/__init__.py
letsencrypt/__init__.py
"""Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 __version__ = '0.1.0.dev0'
"""Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 # '0.1.0.dev0' __version__ = '0.1.0'
Switch to "next production release" as the version in the tree
Switch to "next production release" as the version in the tree
Python
apache-2.0
mitnk/letsencrypt,brentdax/letsencrypt,brentdax/letsencrypt,goofwear/letsencrypt,jtl999/certbot,dietsche/letsencrypt,lmcro/letsencrypt,TheBoegl/letsencrypt,xgin/letsencrypt,letsencrypt/letsencrypt,wteiken/letsencrypt,wteiken/letsencrypt,thanatos/lets-encrypt-preview,VladimirTyrin/letsencrypt,jtl999/certbot,twstrike/le_...
"""Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 + # '0.1.0.dev0' - __version__ = '0.1.0.dev0' + __version__ = '0.1.0'
Switch to "next production release" as the version in the tree
## Code Before: """Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 __version__ = '0.1.0.dev0' ## Instruction: Switch to "next production release" as the version in the tree ## Code After: """Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 part...
"""Let's Encrypt client.""" # version number like 1.2.3a0, must have at least 2 parts, like 1.2 + # '0.1.0.dev0' - __version__ = '0.1.0.dev0' ? ----- + __version__ = '0.1.0'
55d22f95301c4c96c42e30fa037df5bc957dc7b4
incunafein/module/page/extensions/prepared_date.py
incunafein/module/page/extensions/prepared_date.py
from django.db import models def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True))
from django.db import models def get_prepared_date(cls): return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) cls.add_to_class('get_prepared_date', get_prepared_date)
Add a get prepared date method
Add a get prepared date method Child pages won't necessarily have a prepared date and it makes sense to use the parent date to avoid repetition.
Python
bsd-2-clause
incuna/incuna-feincms,incuna/incuna-feincms,incuna/incuna-feincms
from django.db import models + + def get_prepared_date(cls): + return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) + cls.add_to_class('get_prepared_date', get_prepared_d...
Add a get prepared date method
## Code Before: from django.db import models def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) ## Instruction: Add a get prepared date method ## Code After: from django.db import models def get_prepared_date(cls): return cls.prepa...
from django.db import models + + def get_prepared_date(cls): + return cls.prepared_date or cls.parent.prepared_date def register(cls, admin_cls): cls.add_to_class('prepared_date', models.TextField('Date of Preparation', blank=True, null=True)) + cls.add_to_class('get_prepared_date', get_prepared_d...
e3287b9669e07dc4265efe768ba2b4c3351839d3
base_geoengine/geo_db.py
base_geoengine/geo_db.py
"""Helper to setup Postgis""" import logging from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS support to the database. PostGIS is a spatial database extender for PostgreSQL object-relational database. It adds su...
"""Helper to setup Postgis""" import logging from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS support to the database. PostGIS is a spatial database extender for PostgreSQL object-relational d...
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Make MissingError translatable for auto install of postgis extension, plus fix some typos
Python
agpl-3.0
OCA/geospatial,OCA/geospatial,OCA/geospatial
"""Helper to setup Postgis""" import logging + from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS support to the database. PostGIS is a spatial database extender for Post...
Make MissingError translatable for auto install of postgis extension, plus fix some typos
## Code Before: """Helper to setup Postgis""" import logging from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS support to the database. PostGIS is a spatial database extender for PostgreSQL object-relational data...
"""Helper to setup Postgis""" import logging + from odoo import _ from odoo.exceptions import MissingError logger = logging.getLogger('geoengine.sql') def init_postgis(cr): """ Initialize postgis Add PostGIS support to the database. PostGIS is a spatial database extender for Post...
c5e47e61a6b51da99126a9faa4064a621acf017c
tests/handhistory/speed_tests.py
tests/handhistory/speed_tests.py
from timeit import timeit, repeat results, single_results = [], [] for handnr in range(1, 5): single_results.append( timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000, setup="from handhistory import PokerStarsHandHistory; " f"from stars_hands import HAND{hand...
from timeit import timeit, repeat results, single_results = [], [] for handnr in range(1, 5): single_results.append( timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000, setup="from poker.room.pokerstars import PokerStarsHandHistory; " f"from tests.handhistory....
Make handhistory speed test work from root dir
Make handhistory speed test work from root dir
Python
mit
pokerregion/poker
from timeit import timeit, repeat results, single_results = [], [] for handnr in range(1, 5): single_results.append( timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000, - setup="from handhistory import PokerStarsHandHistory; " + setup="from poker.room....
Make handhistory speed test work from root dir
## Code Before: from timeit import timeit, repeat results, single_results = [], [] for handnr in range(1, 5): single_results.append( timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000, setup="from handhistory import PokerStarsHandHistory; " f"from stars_hands ...
from timeit import timeit, repeat results, single_results = [], [] for handnr in range(1, 5): single_results.append( timeit(f'PokerStarsHandHistory(HAND{handnr})', number=100000, - setup="from handhistory import PokerStarsHandHistory; " ? ^^^^^^ ^ ^...
fe5eb7db52725f8d136cbeba4341f5c3a33cf199
tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py
tensorflow_model_optimization/python/core/api/quantization/keras/quantizers/__init__.py
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimization.python.core...
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization.python.core...
Include AllValuesQuantizer in external APIs
Include AllValuesQuantizer in external APIs PiperOrigin-RevId: 320104499
Python
apache-2.0
tensorflow/model-optimization,tensorflow/model-optimization
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. + from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization...
Include AllValuesQuantizer in external APIs
## Code Before: """Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. from tensorflow_model_optimization.python.core.quantization.keras.quantizers import LastValueQuantizer from tensorflow_model_optimiza...
"""Module containing Quantization abstraction and quantizers.""" # quantize with custom quantization parameterization or implementation, or # handle custom Keras layers. + from tensorflow_model_optimization.python.core.quantization.keras.quantizers import AllValuesQuantizer from tensorflow_model_optimization...
003d3921bb6c801c5a2efdede20ed70ee07edf3d
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 delete_backup_storage_quota_from_tenant(apps, schema_editor): tenant_content_type = ContentType....
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...
Replace quota deletion with cleanup
Replace quota deletion with cleanup [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 delete_backup_storage_quota_from_tenant(apps, schema_editor): - tenant_con...
Replace quota deletion with cleanup
## 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 delete_backup_storage_quota_from_tenant(apps, schema_editor): tenant_content_typ...
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 delete_backup_storage_quota_from_tenant(apps, schema_editor): - tenant_con...
b35d4292e50e8a8dc56635bddeac5a1fc42a5d19
tveebot_tracker/source.py
tveebot_tracker/source.py
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obtain episode file...
Rename Source's get_episodes_for() method to fetch()
Rename Source's get_episodes_for() method to fetch()
Python
mit
tveebot/tracker
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracke...
Rename Source's get_episodes_for() method to fetch()
## Code Before: from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracker to obt...
from abc import ABC, abstractmethod class TVShowNotFound(Exception): """ Raised when a reference does not match any TV Show available """ class EpisodeSource(ABC): """ Abstract base class to define the interface for and episode source. An episode source is used by the tracke...
ac4f5451baaefd67392d9b908c9ccffc4083a9ad
fluidsynth/fluidsynth.py
fluidsynth/fluidsynth.py
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* settings); fluid_audio_...
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* settings); fluid_audio_...
Change the LD search path
Change the LD search path
Python
mit
paultag/python-fluidsynth
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* set...
Change the LD search path
## Code Before: from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* setting...
from cffi import FFI ffi = FFI() ffi.cdef(""" typedef struct _fluid_hashtable_t fluid_settings_t; typedef struct _fluid_synth_t fluid_synth_t; typedef struct _fluid_audio_driver_t fluid_audio_driver_t; fluid_settings_t* new_fluid_settings(void); fluid_synth_t* new_fluid_synth(fluid_settings_t* set...
a2f1cdc05e63b7b68c16f3fd1e5203608888b059
traits/util/deprecated.py
traits/util/deprecated.py
""" A decorator for marking methods/functions as deprecated. """ # Standard library imports. import logging # We only warn about each function or method once! _cache = {} def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorator(fn): ...
""" A decorator for marking methods/functions as deprecated. """ # Standard library imports. import functools import warnings def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorator(fn): """ A decorator for marking methods/functions a...
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
+ """ A decorator for marking methods/functions as deprecated. """ - # Standard library imports. + import functools + import warnings - import logging - - # We only warn about each function or method once! - _cache = {} def deprecated(message): """ A factory for decorators for marking methods/fu...
Simplify deprecation machinery: don't cache previous messages, and use warnings instead of logging.
## Code Before: """ A decorator for marking methods/functions as deprecated. """ # Standard library imports. import logging # We only warn about each function or method once! _cache = {} def deprecated(message): """ A factory for decorators for marking methods/functions as deprecated. """ def decorat...
+ """ A decorator for marking methods/functions as deprecated. """ - # Standard library imports. + import functools + import warnings - import logging - - # We only warn about each function or method once! - _cache = {} def deprecated(message): """ A factory for decorators for marking methods/fu...
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: ...
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...
71c47c8374cf6c5f53cdfbb71763f165bcd6c013
oneflow/base/tests/__init__.py
oneflow/base/tests/__init__.py
import redis from mongoengine.connection import connect, disconnect from django.conf import settings TEST_REDIS = redis.StrictRedis(host=settings.REDIS_TEST_HOST, port=settings.REDIS_TEST_PORT, db=settings.REDIS_TEST_DB) def connect_mongodb_testsuite()...
import redis from mongoengine.connection import connect, disconnect from django.conf import settings TEST_REDIS = redis.StrictRedis(host=settings.REDIS_TEST_HOST, port=settings.REDIS_TEST_PORT, db=settings.REDIS_TEST_DB) def connect_mongodb_testsuite()...
Make the test MongoDB database TZ aware like the production one, else some date comparisons fail, whereas they succeed in production.
Make the test MongoDB database TZ aware like the production one, else some date comparisons fail, whereas they succeed in production.
Python
agpl-3.0
1flow/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,WillianPaiva/1flow,1flow/1flow,WillianPaiva/1flow,1flow/1flow
import redis from mongoengine.connection import connect, disconnect from django.conf import settings TEST_REDIS = redis.StrictRedis(host=settings.REDIS_TEST_HOST, port=settings.REDIS_TEST_PORT, db=settings.REDIS_TEST_DB) def c...
Make the test MongoDB database TZ aware like the production one, else some date comparisons fail, whereas they succeed in production.
## Code Before: import redis from mongoengine.connection import connect, disconnect from django.conf import settings TEST_REDIS = redis.StrictRedis(host=settings.REDIS_TEST_HOST, port=settings.REDIS_TEST_PORT, db=settings.REDIS_TEST_DB) def connect_mon...
import redis from mongoengine.connection import connect, disconnect from django.conf import settings TEST_REDIS = redis.StrictRedis(host=settings.REDIS_TEST_HOST, port=settings.REDIS_TEST_PORT, db=settings.REDIS_TEST_DB) def c...
6ac70bb24b7fab272adb9805fa0509aa2282add4
pysswords/db.py
pysswords/db.py
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_b...
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = create_gpg(gpg_b...
Fix get gpg key from database
Fix get gpg key from database
Python
mit
scorphus/passpie,marcwebbie/pysswords,marcwebbie/passpie,scorphus/passpie,eiginn/passpie,eiginn/passpie,marcwebbie/passpie
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): ...
Fix get gpg key from database
## Code Before: from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): gpg = ...
from glob import glob import os from .credential import Credential from .crypt import create_gpg, load_gpg class Database(object): def __init__(self, path, gpg): self.path = path self.gpg = gpg @classmethod def create(cls, path, passphrase, gpg_bin="gpg"): ...
ac725f0d96cfe6ef989d3377e5e7ed9e339fe7e5
djangoautoconf/auth/ldap_backend_wrapper.py
djangoautoconf/auth/ldap_backend_wrapper.py
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "username" in kwa...
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "username" in kwa...
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
Python
bsd-3-clause
weijia/djangoautoconf,weijia/djangoautoconf
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "...
Update codes for ldap wrapper so the username and password are passed to authenticate correctly.
## Code Before: from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "...
from django_auth_ldap.backend import LDAPBackend class LDAPBackendWrapper(LDAPBackend): # def authenticate(self, identification, password, **kwargs): # return super(LDAPBackendWrapper, self).authenticate(identification, password, **kwargs) def authenticate(self, **kwargs): if "...
35255e3c6bda4f862ed3d891b356e383eef02bda
dsppkeras/datasets/dspp.py
dsppkeras/datasets/dspp.py
from ..utils.data_utils import get_file import numpy as np import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple ...
from ..utils.data_utils import get_file import json import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Returns Tuple of Numpy arrays: `(x_train, y_tr...
Switch to JSON containing database.tar.gz
Switch to JSON containing database.tar.gz
Python
agpl-3.0
PeptoneInc/dspp-keras
from ..utils.data_utils import get_file + import json - import numpy as np - import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/data...
Switch to JSON containing database.tar.gz
## Code Before: from ..utils.data_utils import get_file import numpy as np import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/datasets). # Return...
from ..utils.data_utils import get_file + import json - import numpy as np - import cPickle as pickle import tarfile def load_data(path='peptone_dspp.tar.gz'): """Loads the MNIST dataset. # Arguments path: path where to cache the dataset locally (relative to ~/.keras/data...
4aeb2496eb02e130b7dbc37baef787669f8dd1e7
typesetter/typesetter.py
typesetter/typesetter.py
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] with open('typesetter/data/words...
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) # Read in the entire wordlist at startup and keep it in memory. # Optimization for improving search response time. with open('typesetter/data/words.txt') as f: WORDS = f.read().spli...
Reduce search response time by keeping wordlist in memory
Reduce search response time by keeping wordlist in memory
Python
mit
rlucioni/typesetter,rlucioni/typesetter,rlucioni/typesetter
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) + + # Read in the entire wordlist at startup and keep it in memory. + # Optimization for improving search response time. + with open('typesetter/data/words.txt') as f: + ...
Reduce search response time by keeping wordlist in memory
## Code Before: from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) @app.route('/') def index(): return render_template('index.html') @app.route('/api/search/<fragment>') def search(fragment): results = [] with open('types...
from flask import Flask, render_template, jsonify app = Flask(__name__) app.config.update( JSONIFY_PRETTYPRINT_REGULAR=False, ) + + # Read in the entire wordlist at startup and keep it in memory. + # Optimization for improving search response time. + with open('typesetter/data/words.txt') as f: + ...
20a8d57f5e3d00898c7362d650b37f7962fdfe7a
tests/test_distributions.py
tests/test_distributions.py
from __future__ import division import sympy from symfit import Variable, Parameter from symfit.distributions import Gaussian, Exp def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ x0 = Parameter() sig = Parameter(positive=True...
from __future__ import division import sympy from symfit import Variable, Parameter from symfit.distributions import Gaussian, Exp def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ x0 = Parameter('x0') sig = Parameter('sig', po...
Add names to Parameters/Variables to surpress DepricationWarnings
Add names to Parameters/Variables to surpress DepricationWarnings
Python
mit
tBuLi/symfit
from __future__ import division import sympy from symfit import Variable, Parameter from symfit.distributions import Gaussian, Exp def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ - x0 = Parameter() + ...
Add names to Parameters/Variables to surpress DepricationWarnings
## Code Before: from __future__ import division import sympy from symfit import Variable, Parameter from symfit.distributions import Gaussian, Exp def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ x0 = Parameter() sig = Paramet...
from __future__ import division import sympy from symfit import Variable, Parameter from symfit.distributions import Gaussian, Exp def test_gaussian(): """ Make sure that symfit.distributions.Gaussians produces the expected sympy expression. """ - x0 = Parameter() + ...
12327b28697e3d27a6f92863091a84d9b56c0eec
openrcv/test/test_datagen.py
openrcv/test/test_datagen.py
from unittest import TestCase from unittest.mock import patch from openrcv.datagen import gen_random_list class ModuleTest(TestCase): def make_randint(self, values): values = iter(values) def randint(*args): try: return next(values) except StopIteration: ...
from unittest import TestCase from unittest.mock import patch from openrcv.datagen import gen_random_list class ModuleTest(TestCase): def make_randint(self, values): values = iter(values) def randint(*args): try: return next(values) except StopIteration: ...
Add more datagen test cases.
Add more datagen test cases.
Python
mit
cjerdonek/open-rcv,cjerdonek/open-rcv
from unittest import TestCase from unittest.mock import patch from openrcv.datagen import gen_random_list class ModuleTest(TestCase): def make_randint(self, values): values = iter(values) def randint(*args): try: return next(values) ...
Add more datagen test cases.
## Code Before: from unittest import TestCase from unittest.mock import patch from openrcv.datagen import gen_random_list class ModuleTest(TestCase): def make_randint(self, values): values = iter(values) def randint(*args): try: return next(values) except...
from unittest import TestCase from unittest.mock import patch from openrcv.datagen import gen_random_list class ModuleTest(TestCase): def make_randint(self, values): values = iter(values) def randint(*args): try: return next(values) ...
2adfcea14f292bacfbae906a70d6395304acf607
addons/bestja_volunteer_pesel/models.py
addons/bestja_volunteer_pesel/models.py
from operator import mul from openerp import models, fields, api, exceptions class Volunteer(models.Model): _inherit = 'res.users' pesel = fields.Char(string=u"PESEL") def __init__(self, pool, cr): super(Volunteer, self).__init__(pool, cr) self._add_permitted_fields(level='owner', fields...
from operator import mul from openerp import models, fields, api, exceptions class Volunteer(models.Model): _inherit = 'res.users' pesel = fields.Char(string=u"PESEL") def __init__(self, pool, cr): super(Volunteer, self).__init__(pool, cr) self._add_permitted_fields(level='owner', fields...
Fix a problem with PESEL validation
Fix a problem with PESEL validation
Python
agpl-3.0
KrzysiekJ/bestja,ludwiktrammer/bestja,EE/bestja,ludwiktrammer/bestja,EE/bestja,EE/bestja,KrzysiekJ/bestja,ludwiktrammer/bestja,KrzysiekJ/bestja
from operator import mul from openerp import models, fields, api, exceptions class Volunteer(models.Model): _inherit = 'res.users' pesel = fields.Char(string=u"PESEL") def __init__(self, pool, cr): super(Volunteer, self).__init__(pool, cr) self._add_permitted_fiel...
Fix a problem with PESEL validation
## Code Before: from operator import mul from openerp import models, fields, api, exceptions class Volunteer(models.Model): _inherit = 'res.users' pesel = fields.Char(string=u"PESEL") def __init__(self, pool, cr): super(Volunteer, self).__init__(pool, cr) self._add_permitted_fields(level...
from operator import mul from openerp import models, fields, api, exceptions class Volunteer(models.Model): _inherit = 'res.users' pesel = fields.Char(string=u"PESEL") def __init__(self, pool, cr): super(Volunteer, self).__init__(pool, cr) self._add_permitted_fiel...
ca1fe65c5008ddba3467b962f2a51f6c034a5006
mopidy_subsonic/__init__.py
mopidy_subsonic/__init__.py
from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError __doc__ = """A extension for playing music from Subsonic. This extension handles URIs starting with ``subsonic:`` and enables you to play music using a Subsonic server. See https://github.co...
from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError __version__ = '0.2' class SubsonicExtension(ext.Extension): dist_name = 'Mopidy-Subsonic' ext_name = 'subsonic' version = __version__ def get_default_config(self): ...
Remove module docstring copied from an old Mopidy extension
Remove module docstring copied from an old Mopidy extension
Python
mit
rattboi/mopidy-subsonic
from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError - __doc__ = """A extension for playing music from Subsonic. + __version__ = '0.2' - This extension handles URIs starting with ``subsonic:`` and enables you to play music using a...
Remove module docstring copied from an old Mopidy extension
## Code Before: from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError __doc__ = """A extension for playing music from Subsonic. This extension handles URIs starting with ``subsonic:`` and enables you to play music using a Subsonic server. See h...
from __future__ import unicode_literals import os from mopidy import ext, config from mopidy.exceptions import ExtensionError - __doc__ = """A extension for playing music from Subsonic. + __version__ = '0.2' - This extension handles URIs starting with ``subsonic:`` and enables you to play music using a...
15519437a0197582c4b321b9e55544320a759c28
src/lib/sd2/workspace.py
src/lib/sd2/workspace.py
from . import myhosts class Workspace(object): def __init__(self, node): self._node = node def get_targets(self): hosts = self._node.get('targets', []) hosts = [x for x in hosts if myhosts.is_enabled(x['name'])] for host in hosts: assert 'name' in host retu...
from . import myhosts class Workspace(object): def __init__(self, node): self._node = node def get_targets(self): hosts = self._node.get('targets', []) rr = [x for x in hosts if myhosts.is_enabled(x['name'])] rr.extend([x for x in hosts if not myhosts.is_known_host(x['name'])]...
Add containers in hosts so we can rsync into containers
Add containers in hosts so we can rsync into containers
Python
apache-2.0
gae123/sd2,gae123/sd2
from . import myhosts class Workspace(object): def __init__(self, node): self._node = node def get_targets(self): hosts = self._node.get('targets', []) - hosts = [x for x in hosts if myhosts.is_enabled(x['name'])] + rr = [x for x in hosts if myhosts.is_enable...
Add containers in hosts so we can rsync into containers
## Code Before: from . import myhosts class Workspace(object): def __init__(self, node): self._node = node def get_targets(self): hosts = self._node.get('targets', []) hosts = [x for x in hosts if myhosts.is_enabled(x['name'])] for host in hosts: assert 'name' in h...
from . import myhosts class Workspace(object): def __init__(self, node): self._node = node def get_targets(self): hosts = self._node.get('targets', []) - hosts = [x for x in hosts if myhosts.is_enabled(x['name'])] ? ^^^^^ + rr = [x for x in hosts if ...
b7106307baf97ba32cb29fe2a4bb9ed925c194ca
custom/onse/management/commands/update_onse_facility_cases.py
custom/onse/management/commands/update_onse_facility_cases.py
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args, **options): ...
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args, **options): ...
Fix passing keyword arg to task
Fix passing keyword arg to task
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *...
Fix passing keyword arg to task
## Code Before: from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *args...
from django.core.management import BaseCommand from custom.onse.tasks import update_facility_cases_from_dhis2_data_elements class Command(BaseCommand): help = ('Update facility_supervision cases with indicators collected ' 'in DHIS2 over the last quarter.') def handle(self, *...
7a7e824b63c4498ee12c59a6af459e6fe8639003
server.py
server.py
import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_controller = contro...
import bottle from cso_parser import CsoParser import waitress from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler from breathe import Breathe from controller import Controller bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/...
Add scheduled cso_job method - Retrieves the CSO status and updates the breathe rate
Add scheduled cso_job method - Retrieves the CSO status and updates the breathe rate
Python
mit
tipsqueal/duwamish-lighthouse,tipsqueal/duwamish-lighthouse,illumenati/duwamish-lighthouse,illumenati/duwamish-lighthouse
import bottle + from cso_parser import CsoParser import waitress - import controller - import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler + from breathe import Breathe + from controller import Controller bottle_app = bottle.app() scheduler = Backgro...
Add scheduled cso_job method - Retrieves the CSO status and updates the breathe rate
## Code Before: import bottle import waitress import controller import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler bottle_app = bottle.app() scheduler = BackgroundScheduler() scheduler.configure(timezone=timezone('US/Pacific')) breather = breathe.Breathe() my_con...
import bottle + from cso_parser import CsoParser import waitress - import controller - import breathe from pytz import timezone from apscheduler.schedulers.background import BackgroundScheduler + from breathe import Breathe + from controller import Controller bottle_app = bottle.app() scheduler = Backgro...
343baa4b8a0ed9d4db0727c514d9ff97b937c7ee
adLDAP.py
adLDAP.py
import ldap def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + controller + '.' + domain ldapUsername = username + '@' + domain ldapPassword = password b...
import ldap validEditAccessGroups = ['Office Assistants', 'Domain Admins'] def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + controller + '.' + domain ldap...
Add group fetching from AD
Add group fetching from AD
Python
mit
lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory
import ldap + + validEditAccessGroups = ['Office Assistants', 'Domain Admins'] def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + con...
Add group fetching from AD
## Code Before: import ldap def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + controller + '.' + domain ldapUsername = username + '@' + domain ldapPassword...
import ldap + + validEditAccessGroups = ['Office Assistants', 'Domain Admins'] def checkCredentials(username, password): if password == "": return 'Empty Password' controller = 'devdc' domainA = 'dev' domainB = 'devlcdi' domain = domainA + '.' + domainB ldapServer = 'ldap://' + con...
9506fa3a0382ba7a156ba6188c8d05bff8be5da3
falcom/api/common/read_only_data_structure.py
falcom/api/common/read_only_data_structure.py
class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove_null_keys (self...
class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __repr__ (self): ...
Add repr to data structures
Add repr to data structures
Python
bsd-3-clause
mlibrary/image-conversion-and-validation,mlibrary/image-conversion-and-validation
class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) + ...
Add repr to data structures
## Code Before: class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) def __remove...
class ReadOnlyDataStructure: def __init__ (self, **kwargs): self.__internal = kwargs self.__remove_null_keys() def get (self, key, default = None): return self.__internal.get(key, default) def __bool__ (self): return bool(self.__internal) + ...
2205ea40f64b09f611b7f6cb4c9716d8e29136d4
grammpy/Rule.py
grammpy/Rule.py
class Rule: pass
from grammpy import EPSILON class Rule: right = [EPSILON] left = [EPSILON] rule = ([EPSILON], [EPSILON]) rules = [([EPSILON], [EPSILON])] def is_regular(self): return False def is_contextfree(self): return False def is_context(self): return False def is_unr...
Add base interface for rule
Add base interface for rule
Python
mit
PatrikValkovic/grammpy
+ + from grammpy import EPSILON class Rule: - pass + right = [EPSILON] + left = [EPSILON] + rule = ([EPSILON], [EPSILON]) + rules = [([EPSILON], [EPSILON])] + def is_regular(self): + return False + + def is_contextfree(self): + return False + + def is_contex...
Add base interface for rule
## Code Before: class Rule: pass ## Instruction: Add base interface for rule ## Code After: from grammpy import EPSILON class Rule: right = [EPSILON] left = [EPSILON] rule = ([EPSILON], [EPSILON]) rules = [([EPSILON], [EPSILON])] def is_regular(self): return False def is_cont...
+ + from grammpy import EPSILON class Rule: - pass + right = [EPSILON] + left = [EPSILON] + rule = ([EPSILON], [EPSILON]) + rules = [([EPSILON], [EPSILON])] + + def is_regular(self): + return False + + def is_contextfree(self): + return False + + def is_contex...
db45239e050e6699a2c49fe4156b100c42481c9f
wsme/tests/test_spore.py
wsme/tests/test_spore.py
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoot()) print(spore) ...
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoot()) print(spore) ...
Test SPORE crud function descriptions
Test SPORE crud function descriptions
Python
mit
stackforge/wsme
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoo...
Test SPORE crud function descriptions
## Code Before: import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoot()) ...
import unittest try: import simplejson as json except ImportError: import json from wsme.tests.protocol import WSTestRoot import wsme.tests.test_restjson import wsme.spore class TestSpore(unittest.TestCase): def test_spore(self): spore = wsme.spore.getdesc(WSTestRoo...
453b6a8697b066174802257156ac364aed2c650a
emission/storage/timeseries/aggregate_timeseries.py
emission/storage/timeseries/aggregate_timeseries.py
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {}
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_query = {} ...
Implement a sort key method for the aggregate timeseries
Implement a sort key method for the aggregate timeseries This should return null because we want to mix up the identifying information from the timeseries and sorting will re-impose some order. Also sorting takes too much time!
Python
bsd-3-clause
shankari/e-mission-server,yw374cornell/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,e-mission/e-mission-server,sunil07t/e-mission-server,shankari/e-mission-server,shankari/e-mission-server,e-mission/e-mission-server,yw374cornell/e-mission-server,sunil07t/e-mission-server,yw374cornell/e-mission-...
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self...
Implement a sort key method for the aggregate timeseries
## Code Before: import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self.user_...
import logging import pandas as pd import pymongo import emission.core.get_database as edb import emission.storage.timeseries.builtin_timeseries as bits class AggregateTimeSeries(bits.BuiltinTimeSeries): def __init__(self): super(AggregateTimeSeries, self).__init__(None) self...
eed33b6ba9a3d5cf5d841d451ad03fd2f57c43bf
openfisca_senegal/senegal_taxbenefitsystem.py
openfisca_senegal/senegal_taxbenefitsystem.py
import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities, scenarios COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) class SenegalTaxBenefitSystem(TaxBenefitSystem): """Senegalese tax and benefit system""" CURRENCY = u"FCFA" def __init__(self): s...
import os import xml.etree.ElementTree from openfisca_core import conv, legislationsxml from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities, scenarios COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) class SenegalTaxBenefitSystem(TaxBenefitSystem): """Senegalese tax a...
Implement adding legislation XML from string
Implement adding legislation XML from string
Python
agpl-3.0
openfisca/senegal
import os + import xml.etree.ElementTree + from openfisca_core import conv, legislationsxml from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities, scenarios COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) class SenegalTaxBenefitSystem(TaxBenefitSyst...
Implement adding legislation XML from string
## Code Before: import os from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities, scenarios COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) class SenegalTaxBenefitSystem(TaxBenefitSystem): """Senegalese tax and benefit system""" CURRENCY = u"FCFA" def __init__(...
import os + import xml.etree.ElementTree + from openfisca_core import conv, legislationsxml from openfisca_core.taxbenefitsystems import TaxBenefitSystem from . import entities, scenarios COUNTRY_DIR = os.path.dirname(os.path.abspath(__file__)) class SenegalTaxBenefitSystem(TaxBenefitSyst...
3421fe2542a5b71f6b604e30f2c800400b5e40d8
datawire/store/common.py
datawire/store/common.py
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn): data ...
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = JSONEncoder().encode(frame) return self._store(urn, data) def load(self, urn): data = self....
Fix encoding of store serialisation.
Fix encoding of store serialisation.
Python
mit
arc64/datawi.re,arc64/datawi.re,arc64/datawi.re
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') - data = json.dumps(frame, cls=JSONEncoder) + data = JSONEncoder().encode(frame) ...
Fix encoding of store serialisation.
## Code Before: import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') data = json.dumps(frame, cls=JSONEncoder) return self._store(urn, data) def load(self, urn...
import json from datawire.views.util import JSONEncoder class Store(object): def __init__(self, url): self.url = url def store(self, frame): urn = frame.get('urn') - data = json.dumps(frame, cls=JSONEncoder) + data = JSONEncoder().encode(frame) ...
912b8a90472fc39f7c5d3b8e1e44b57aa88c0b02
setup.py
setup.py
from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['numspell'], data_fil...
from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['numspell'], scripts=...
Add more idiomatic (and also portable) way to install `spellnum` script
Add more idiomatic (and also portable) way to install `spellnum` script
Python
mit
alco/numspell,alco/numspell
from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['nums...
Add more idiomatic (and also portable) way to install `spellnum` script
## Code Before: from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['numspell']...
from distutils.core import setup setup(name='Numspell', version='0.9', description='A Python module for spelling numbers', author='Alexei Sholik', author_email='alcosholik@gmail.com', url='https://github.com/alco/numspell', license="MIT", packages=['nums...
d1a96f13204ad7028432096d25718e611d4d3d9d
depot/gpg.py
depot/gpg.py
import getpass import os import gnupg class GPG(object): def __init__(self, keyid): self.gpg = gnupg.GPG(use_agent=False) self.keyid = keyid if not self.keyid: # Compat with how Freight does it. self.keyid = os.environ.get('GPG') self.passphrase = None ...
import getpass import os import gnupg class GPG(object): def __init__(self, keyid, key=None, home=None): self.gpg = gnupg.GPG(use_agent=False, gnupghome=home) if key: if not home: raise ValueError('Cowardly refusing to import key in to default key store') r...
Allow passing in a raw key and homedir.
Allow passing in a raw key and homedir.
Python
apache-2.0
coderanger/depot
import getpass import os import gnupg class GPG(object): - def __init__(self, keyid): + def __init__(self, keyid, key=None, home=None): - self.gpg = gnupg.GPG(use_agent=False) + self.gpg = gnupg.GPG(use_agent=False, gnupghome=home) + if key: + if not home: + ...
Allow passing in a raw key and homedir.
## Code Before: import getpass import os import gnupg class GPG(object): def __init__(self, keyid): self.gpg = gnupg.GPG(use_agent=False) self.keyid = keyid if not self.keyid: # Compat with how Freight does it. self.keyid = os.environ.get('GPG') self.passph...
import getpass import os import gnupg class GPG(object): - def __init__(self, keyid): + def __init__(self, keyid, key=None, home=None): - self.gpg = gnupg.GPG(use_agent=False) + self.gpg = gnupg.GPG(use_agent=False, gnupghome=home) ? +...
f59852e0db6941ce0862545f552a2bc17081086a
schedule/tests/test_templatetags.py
schedule/tests/test_templatetags.py
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) self.assert...
Update unit test to use escaped ampersands in comparision.
Update unit test to use escaped ampersands in comparision.
Python
bsd-3-clause
Gustavosdo/django-scheduler,erezlife/django-scheduler,Gustavosdo/django-scheduler,nharsch/django-scheduler,nharsch/django-scheduler,drodger/django-scheduler,GrahamDigital/django-scheduler,sprightco/django-scheduler,llazzaro/django-scheduler,llazzaro/django-scheduler,rowbot-dev/django-scheduler,nwaxiomatic/django-schedu...
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(dat...
Update unit test to use escaped ampersands in comparision.
## Code Before: import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(date) ...
import datetime from django.test import TestCase from schedule.templatetags.scheduletags import querystring_for_date class TestTemplateTags(TestCase): def test_querystring_for_datetime(self): date = datetime.datetime(2008,1,1,0,0,0) query_string=querystring_for_date(dat...
3e9a90890f122090be027a3af3d6cbd8a713963c
test/test_issue655.py
test/test_issue655.py
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float...
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value = Literal(float...
Add tests requested by @joernhees
Add tests requested by @joernhees
Python
bsd-3-clause
RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib,RDFLib/rdflib
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") ...
Add tests requested by @joernhees
## Code Before: from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") value...
from rdflib import Graph, Namespace, URIRef, Literal from rdflib.compare import to_isomorphic import unittest class TestIssue655(unittest.TestCase): def test_issue655(self): PROV = Namespace('http://www.w3.org/ns/prov#') bob = URIRef("http://example.org/object/Bob") ...
94529f62757886d2291cf90596a179dc2d0b6642
yutu.py
yutu.py
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ''' await ctx.send('{0....
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ''' await ctx.send('{0....
Make cute respect guild nicknames
Make cute respect guild nicknames
Python
mit
HarkonenBade/yutu
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ...
Make cute respect guild nicknames
## Code Before: import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ''' awa...
import discord from discord.ext.commands import Bot import json client = Bot("~", game=discord.Game(name="~help")) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.command() async def highfive(ctx): ''' Give Yutu a high-five ...
5cf839df99a03299215db7c2f6d9a78ac724c155
src/rinoh/language/__init__.py
src/rinoh/language/__init__.py
from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = [] for string_...
from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = ['Localized string...
Fix the rendering of language instance docstrings
Fix the rendering of language instance docstrings
Python
agpl-3.0
brechtm/rinohtype,brechtm/rinohtype,brechtm/rinohtype
from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_re...
Fix the rendering of language instance docstrings
## Code Before: from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_ref() lines = []...
from .cls import Language from .en import EN from .fr import FR from .it import IT from .nl import NL __all__ = ['Language', 'EN', 'FR', 'IT', 'NL'] # generate docstrings for the Language instances for code, language_ref in Language.languages.items(): language = language_re...
71fd42a92b41529d9f5c784840ab4c190946adef
social_auth/backends/pipeline/associate.py
social_auth/backends/pipeline/associate.py
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(details, user=None...
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(details, user=None...
Remove spammy warning which doesn't apply when stores check emails
Remove spammy warning which doesn't apply when stores check emails
Python
bsd-3-clause
antoviaque/django-social-auth-norel
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(...
Remove spammy warning which doesn't apply when stores check emails
## Code Before: from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(de...
from django.core.exceptions import MultipleObjectsReturned, ObjectDoesNotExist from social_auth.utils import setting from social_auth.models import UserSocialAuth from social_auth.backends.pipeline import warn_setting from social_auth.backends.exceptions import AuthException def associate_by_email(...
dbb15e4919c5d54d2e755cea700cc287bf164ad4
bom_data_parser/climate_data_online.py
bom_data_parser/climate_data_online.py
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.convert_key(column)) df.co...
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.convert_key(column)) df.co...
Handle just the zip file name when splitting
Handle just the zip file name when splitting This fixes a bug where the zip file name isn't correctly handled when splitting on the '.'. This causes a failure if passing a relative path (e.g '../'). Would also be a problem if directories had periods in their name.
Python
bsd-3-clause
amacd31/bom_data_parser,amacd31/bom_data_parser
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.conve...
Handle just the zip file name when splitting
## Code Before: import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.convert_key(col...
import os import numpy as np import pandas as pd import zipfile from bom_data_parser import mapper def read_climate_data_online_csv(fname): df = pd.read_csv(fname, parse_dates={'Date': [2,3,4]}) column_names = [] for column in df.columns: column_names.append(mapper.conve...
e743bcddbc53d51142f3e1277919a3f65afaad90
tests/conftest.py
tests/conftest.py
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ.get('TRAVIS_GH3') else...
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ.get('TRAVIS_GH3') else...
Revert "For travis, let us print the mode"
Revert "For travis, let us print the mode" This reverts commit 0c8e9c36219214cf08b33c0ff1812e6cefa53353.
Python
bsd-3-clause
sigmavirus24/github3.py,agamdua/github3.py,christophelec/github3.py,jim-minter/github3.py,ueg1990/github3.py,degustaf/github3.py,balloob/github3.py,h4ck3rm1k3/github3.py,icio/github3.py,wbrefvem/github3.py,krxsky/github3.py,itsmemattchung/github3.py
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ....
Revert "For travis, let us print the mode"
## Code Before: import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ.get('T...
import base64 import betamax import os credentials = [os.environ.get('GH_USER', 'foo').encode(), os.environ.get('GH_PASSWORD', 'bar').encode()] with betamax.Betamax.configure() as config: config.cassette_library_dir = 'tests/cassettes' record_mode = 'never' if os.environ....
5eb96c599dbbef56853dfb9441ab2eb54d36f9b7
ckanext/syndicate/tests/test_plugin.py
ckanext/syndicate/tests/test_plugin.py
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() self.entity = model.Package() ...
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() self.entity = model.Package() ...
Add test for notify dataset/delete
Add test for notify dataset/delete
Python
agpl-3.0
aptivate/ckanext-syndicate,aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues,sorki/ckanext-redmine-autoissues
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() sel...
Add test for notify dataset/delete
## Code Before: from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() self.entity = m...
from mock import patch import unittest import ckan.model as model from ckan.model.domain_object import DomainObjectOperation from ckanext.syndicate.plugin import SyndicatePlugin class TestNotify(unittest.TestCase): def setUp(self): super(TestNotify, self).setUp() sel...
bde734dc751cbfd59b40c1c2f0d60229795fae4a
tests/app/main/test_request_header.py
tests/app/main/test_request_header.py
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, heade...
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_proxy_header, heade...
Use test_client() as context manager
Use test_client() as context manager
Python
mit
gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,gov-cjwaszczuk/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin,alphagov/notifications-admin
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, c...
Use test_client() as context manager
## Code Before: import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, check_pro...
import pytest from tests.conftest import set_config_values @pytest.mark.parametrize('check_proxy_header,header_value,expected_code', [ (True, 'key_1', 200), (True, 'wrong_key', 403), (False, 'wrong_key', 200), (False, 'key_1', 200), ]) def test_route_correct_secret_key(app_, c...
43bae84b1359d56ad150b49b38c2f8d400b05af2
opps/core/cache/managers.py
opps/core/cache/managers.py
from django.db import models from django.core.cache import cache from django.conf import settings class CacheManager(models.Manager): def __cache_key(self, id): return u'{}:{}:{}'.format(settings.CACHE_PREFIX, self.model._meta.db_table, i...
from django.db import models from django.core.cache import cache from django.conf import settings def _cache_key(model, id): return u'{}:{}:{}'.format(settings.CACHE_PREFIX, model._meta.db_table, id) class CacheManager(models.Manager): def get(self...
Fix cache key set, on core cache
Fix cache key set, on core cache
Python
mit
jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,YACOWS/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,YACOWS/opps,opps/opps,opps/opps,opps/opps
from django.db import models from django.core.cache import cache from django.conf import settings + def _cache_key(model, id): + return u'{}:{}:{}'.format(settings.CACHE_PREFIX, + model._meta.db_table, + id) + + class CacheManager(models.Ma...
Fix cache key set, on core cache
## Code Before: from django.db import models from django.core.cache import cache from django.conf import settings class CacheManager(models.Manager): def __cache_key(self, id): return u'{}:{}:{}'.format(settings.CACHE_PREFIX, self.model._meta.db_table, ...
from django.db import models from django.core.cache import cache from django.conf import settings + def _cache_key(model, id): + return u'{}:{}:{}'.format(settings.CACHE_PREFIX, + model._meta.db_table, + id) + + class CacheManager(models.Ma...
8842bbf45ffe2a76832075e053dce90a95964bcd
Bookie/bookie/tests/__init__.py
Bookie/bookie/tests/__init__.py
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite database to run our t...
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() # we need to pull the right ini for the test we want to run # by default pullup test.ini, but we might want to test mysql, pgsql, etc test_ini = os.en...
Add ability to set test ini via env variable
Add ability to set test ini via env variable
Python
agpl-3.0
charany1/Bookie,teodesson/Bookie,skmezanul/Bookie,teodesson/Bookie,skmezanul/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,adamlincoln/Bookie,GreenLunar/Bookie,bookieio/Bookie,pombredanne/Bookie,wangjun/Bookie,adamlincoln/Bookie,pombredanne/Bookie,pombredanne/Bookie,skmezanul/Bookie,bookieio/Bookie,charany1/Bookie,Green...
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() + + # we need to pull the right ini for the test we want to run + # by default pullup test.ini, but we might want to test mysql, pgs...
Add ability to set test ini via env variable
## Code Before: import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() ini.read('test.ini') settings = dict(ini.items('app:bookie')) def setup_db(settings): """ We need to create the test sqlite datab...
import ConfigParser import os import unittest from pyramid.config import Configurator from pyramid import testing global_config = {} ini = ConfigParser.ConfigParser() + + # we need to pull the right ini for the test we want to run + # by default pullup test.ini, but we might want to test mysql, pgs...
ec441eb63a785ad1ab15356f60f812a57a726788
lib/Subcommands/Pull.py
lib/Subcommands/Pull.py
from lib.Wrappers.ArgumentParser import ArgumentParser from lib.DockerManagerFactory import DockerManagerFactory class Pull: def __init__(self, manager_factory=None): self.manager_factory = manager_factory or DockerManagerFactory() def execute(self, *args): arguments = self._parse_arguments(*...
import os from lib.DockerComposeExecutor import DockerComposeExecutor from lib.Tools import paths class Pull: def __init__(self, manager_factory=None): pass def execute(self, *args): file_path = os.getcwd() + '/environments/compose_files/latest/docker-compose-all.yml' docker_compose ...
Refactor the 'pull' subcommand to use DockerComposeExecutor
Refactor the 'pull' subcommand to use DockerComposeExecutor The pull subcommand was not working because it depended on an unimplemented class DockerManagerFactory.
Python
agpl-3.0
Open365/Open365,Open365/Open365
- from lib.Wrappers.ArgumentParser import ArgumentParser - from lib.DockerManagerFactory import DockerManagerFactory + import os + + from lib.DockerComposeExecutor import DockerComposeExecutor + from lib.Tools import paths class Pull: def __init__(self, manager_factory=None): - self.manager_facto...
Refactor the 'pull' subcommand to use DockerComposeExecutor
## Code Before: from lib.Wrappers.ArgumentParser import ArgumentParser from lib.DockerManagerFactory import DockerManagerFactory class Pull: def __init__(self, manager_factory=None): self.manager_factory = manager_factory or DockerManagerFactory() def execute(self, *args): arguments = self._p...
- from lib.Wrappers.ArgumentParser import ArgumentParser - from lib.DockerManagerFactory import DockerManagerFactory + import os + + from lib.DockerComposeExecutor import DockerComposeExecutor + from lib.Tools import paths class Pull: def __init__(self, manager_factory=None): - self.manager_facto...
b6e532f01d852738f40eb8bedc89f5c056b2f62c
netbox/generate_secret_key.py
netbox/generate_secret_key.py
import random charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' secure_random = random.SystemRandom() print(''.join(secure_random.sample(charset, 50)))
import secrets charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' print(''.join(secrets.choice(charset) for _ in range(50)))
Fix how SECRET_KEY is generated
Fix how SECRET_KEY is generated Use secrets.choice instead of random.sample to generate the secret key.
Python
apache-2.0
digitalocean/netbox,digitalocean/netbox,digitalocean/netbox,digitalocean/netbox
- import random + import secrets charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' + print(''.join(secrets.choice(charset) for _ in range(50))) - secure_random = random.SystemRandom() - print(''.join(secure_random.sample(charset, 50)))
Fix how SECRET_KEY is generated
## Code Before: import random charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' secure_random = random.SystemRandom() print(''.join(secure_random.sample(charset, 50))) ## Instruction: Fix how SECRET_KEY is generated ## Code After: import secrets charset = 'abcdefghijklmnopqrstu...
- import random + import secrets charset = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*(-_=+)' + print(''.join(secrets.choice(charset) for _ in range(50))) - secure_random = random.SystemRandom() - print(''.join(secure_random.sample(charset, 50)))
d97dd4a8f4c0581ce33ed5838dcc0329745041bf
pirate_add_shift_recurrence.py
pirate_add_shift_recurrence.py
import sys import os from tasklib.task import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly created recurrence tasks actually have # modified field cop...
import sys import os from tasklib import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly created recurrence tasks actually have # modified field copied f...
Fix old style import and config overrides
Fix old style import and config overrides
Python
mit
tbabej/task.shift-recurrence
import sys import os - from tasklib.task import TaskWarrior + from tasklib import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly cre...
Fix old style import and config overrides
## Code Before: import sys import os from tasklib.task import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False # Newly created recurrence tasks actually have # mo...
import sys import os - from tasklib.task import TaskWarrior ? ----- + from tasklib import TaskWarrior time_attributes = ('wait', 'scheduled') def is_new_local_recurrence_child_task(task): # Do not affect tasks not spun by recurrence if not task['parent']: return False...
8fadb2bb766bd3a18e7920a5dbf23669796330ff
src/mcedit2/rendering/scenegraph/bind_texture.py
src/mcedit2/rendering/scenegraph/bind_texture.py
from __future__ import absolute_import, division, print_function, unicode_literals import logging from OpenGL import GL from mcedit2.rendering.scenegraph import rendernode from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode from mcedit2.rendering.scenegraph.scenenode import Node from mcedit2.util ...
from __future__ import absolute_import, division, print_function, unicode_literals import logging from OpenGL import GL from mcedit2.rendering.scenegraph import rendernode from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode from mcedit2.rendering.scenegraph.scenenode import Node from mcedit2.util ...
Change BindTextureRenderNode to make fewer GL calls when the texture scale is None.
Change BindTextureRenderNode to make fewer GL calls when the texture scale is None.
Python
bsd-3-clause
vorburger/mcedit2,vorburger/mcedit2
from __future__ import absolute_import, division, print_function, unicode_literals import logging from OpenGL import GL from mcedit2.rendering.scenegraph import rendernode from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode from mcedit2.rendering.scenegraph.scenenode import Node from...
Change BindTextureRenderNode to make fewer GL calls when the texture scale is None.
## Code Before: from __future__ import absolute_import, division, print_function, unicode_literals import logging from OpenGL import GL from mcedit2.rendering.scenegraph import rendernode from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode from mcedit2.rendering.scenegraph.scenenode import Node fr...
from __future__ import absolute_import, division, print_function, unicode_literals import logging from OpenGL import GL from mcedit2.rendering.scenegraph import rendernode from mcedit2.rendering.scenegraph.rendernode import RenderstateRenderNode from mcedit2.rendering.scenegraph.scenenode import Node from...
13c1410de300a7f414b51cb001534f021441a00f
tests/test_authentication.py
tests/test_authentication.py
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() ...
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.test_client() ...
Test that there is a json content type
Test that there is a json content type
Python
mit
jenca-cloud/jenca-authentication
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authenti...
Test that there is a json content type
## Code Before: import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authentication.app.tes...
import unittest import tempfile from authentication import authentication class SignupTests(unittest.TestCase): """ Signup tests. """ def test_signup(self): """ Test that a valid signup request returns an OK status. """ test_app = authenti...
3a428dea9a27709e50bcf84666df6281a0337691
httphandler.py
httphandler.py
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-m...
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does-python-have-a-m...
Add raw request field to request
Add raw request field to request
Python
mit
Zloool/manyfaced-honeypot
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/...
Add raw request field to request
## Code Before: from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/does...
from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO class HTTPRequest(BaseHTTPRequestHandler): """ This class is just an incapsulation of BaseHTTPRequestHandler, so it can be created from string. Code from: http://stackoverflow.com/questions/2115410/...
be1d11bcf53ecab1fbb0e69191c62c83492363d2
cmn_color_helper.py
cmn_color_helper.py
class ColorStr: _HEADER = '\033[95m' _OKBLUE = '\033[94m' _OKGREEN = '\033[92m' _WARNING = '\033[93m' _FAIL = '\033[91m' _ENDC = '\033[0m' _BOLD = '\033[1m' _UNDERLINE = '\033[4m' @staticmethod def color_fun_name(fun): return ColorStr._UNDERLINE + ColorStr._BOLD + Color...
class ColorStr: _HEADER = '\033[95m' _OKBLUE = '\033[94m' _OKGREEN = '\033[92m' _WARNING = '\033[93m' _FAIL = '\033[91m' _ENDC = '\033[0m' _BOLD = '\033[1m' _UNDERLINE = '\033[4m' @staticmethod def color_fun_name(fun): return ColorStr._HEADER + ColorStr._BOLD + fun + Co...
Change function and pkg color style.
Change function and pkg color style.
Python
mit
fanchen1988/sc-common-helper
class ColorStr: _HEADER = '\033[95m' _OKBLUE = '\033[94m' _OKGREEN = '\033[92m' _WARNING = '\033[93m' _FAIL = '\033[91m' _ENDC = '\033[0m' _BOLD = '\033[1m' _UNDERLINE = '\033[4m' @staticmethod def color_fun_name(fun): - return ColorStr._UNDERL...
Change function and pkg color style.
## Code Before: class ColorStr: _HEADER = '\033[95m' _OKBLUE = '\033[94m' _OKGREEN = '\033[92m' _WARNING = '\033[93m' _FAIL = '\033[91m' _ENDC = '\033[0m' _BOLD = '\033[1m' _UNDERLINE = '\033[4m' @staticmethod def color_fun_name(fun): return ColorStr._UNDERLINE + ColorS...
class ColorStr: _HEADER = '\033[95m' _OKBLUE = '\033[94m' _OKGREEN = '\033[92m' _WARNING = '\033[93m' _FAIL = '\033[91m' _ENDC = '\033[0m' _BOLD = '\033[1m' _UNDERLINE = '\033[4m' @staticmethod def color_fun_name(fun): - return ColorStr._UNDERL...
a9354124f4905f4befe9ff2ca8274406fbbb0dad
readux/annotations/migrations/0003_annotation_group_and_permissions.py
readux/annotations/migrations/0003_annotation_group_and_permissions.py
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('annotations', '0002_add_volume_uri'), ] operations = [ migrations.CreateModel( name=...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('annotations', '0002_add_volume_uri'), ] operations = [ migrations.CreateModel( name=...
Fix migration that adds custom annotation permissions
Fix migration that adds custom annotation permissions
Python
apache-2.0
emory-libraries/readux,emory-libraries/readux,emory-libraries/readux
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('annotations', '0002_add_volume_uri'), ] operations = [ migrations.Cr...
Fix migration that adds custom annotation permissions
## Code Before: from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('annotations', '0002_add_volume_uri'), ] operations = [ migrations.CreateModel( ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('annotations', '0002_add_volume_uri'), ] operations = [ migrations.Cr...
13c3379717d1ad10a179f26838950090a2b6e4f4
pyxb/__init__.py
pyxb/__init__.py
class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether super(Myclass,...
class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether super(Myclass,...
Handle unicode and string creation correctly
Handle unicode and string creation correctly
Python
apache-2.0
jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,CantemoInternal/pyxb,jonfoster/pyxb-upstream-mirror,pabigot/pyxb,CantemoInternal/pyxb,jonfoster/pyxb2,balanced/PyXB,jonfoster/pyxb2,pabigot/pyxb,jonfoster/pyxb2,jonfoster/pyxb-upstream-mirror,jonfoster/pyxb1,balanced/PyXB,CantemoInternal/pyxb,balanced/PyXB
class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether ...
Handle unicode and string creation correctly
## Code Before: class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whethe...
class cscRoot (object): """This little bundle of joy exists because in Python 2.6 it became an error to invoke object.__init__ with parameters (unless you also override __new__, in which case it's only a warning. Whatever.). Since I'm bloody not going to check in every class whether ...
c709c58fc128076af5f58d33dcd0983436573d79
tests/test_parsingapi.py
tests/test_parsingapi.py
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYPES) method...
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYPES) method...
Add a test to verify plugin_parsing clears selected parsers after task
Add a test to verify plugin_parsing clears selected parsers after task
Python
mit
tobinjt/Flexget,Flexget/Flexget,jawilson/Flexget,sean797/Flexget,OmgOhnoes/Flexget,poulpito/Flexget,antivirtel/Flexget,ianstalk/Flexget,JorisDeRieck/Flexget,tarzasai/Flexget,Pretagonist/Flexget,malkavi/Flexget,dsemi/Flexget,sean797/Flexget,tobinjt/Flexget,Pretagonist/Flexget,crawln45/Flexget,Danfocus/Flexget,tobinjt/Fl...
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYP...
Add a test to verify plugin_parsing clears selected parsers after task
## Code Before: from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYPES...
from __future__ import unicode_literals, division, absolute_import from flexget.plugin import get_plugin_by_name, get_plugins from flexget.plugins.parsers import plugin_parsing class TestParsingAPI(object): def test_all_types_handled(self): declared_types = set(plugin_parsing.PARSER_TYP...
435e8fc4d9ad8c071a96e37e483fcbc194a94fc6
tests/integration/files/file/base/_modules/runtests_decorators.py
tests/integration/files/file/base/_modules/runtests_decorators.py
from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(True) def booldependsTrue(): ''...
from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(True) def booldependsTrue(): '...
Fix tests: add module function docstring
Fix tests: add module function docstring
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True + @salt.utils.decorators....
Fix tests: add module function docstring
## Code Before: from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True @salt.utils.decorators.depends(True) def booldepen...
from __future__ import absolute_import import time # Import Salt libs import salt.utils.decorators def _fallbackfunc(): return False, 'fallback' def working_function(): ''' CLI Example: .. code-block:: bash ''' return True + @salt.utils.decorators....
1999e66070b02a30460c76d90787c7c20905363a
kboard/board/tests/test_templatetags.py
kboard/board/tests/test_templatetags.py
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_string = url_para...
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is ...
Add test of hide ip template tag
Add test of hide ip template tag
Python
mit
kboard/kboard,cjh5414/kboard,hyesun03/k-board,hyesun03/k-board,hyesun03/k-board,kboard/kboard,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,guswnsxodlf/k-board,cjh5414/kboard,darjeeling/k-board
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter + from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', ...
Add test of hide ip template tag
## Code Before: from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', 'b': 'This is a test' } url_s...
from .base import BoardAppTest from board.templatetags.url_parameter import url_parameter + from board.templatetags.hide_ip import hide_ip class UrlParameterTest(BoardAppTest): def test_contains_correct_string(self): parameter = { 'a': 13, 'query': 'hello', ...
1d355a2143daf438b5a2f5185a7f60268ad7c686
tests/local_test.py
tests/local_test.py
from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run(["echo", "hello"]) assert_equal("hello\n", result.output)
from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run(["echo", "hello"]) assert_equal("hello\n", result.output) @istest def cwd_of_run_can_be_set(): result = shell.run(["pwd"], cwd="/") assert_equal("/\n...
Add test for setting cwd in LocalShell.run
Add test for setting cwd in LocalShell.run
Python
bsd-2-clause
mwilliamson/spur.py
from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run(["echo", "hello"]) assert_equal("hello\n", result.output) + @istest + def cwd_of_run_can_be_set(): + result = shell.run(["pwd"], cw...
Add test for setting cwd in LocalShell.run
## Code Before: from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run(["echo", "hello"]) assert_equal("hello\n", result.output) ## Instruction: Add test for setting cwd in LocalShell.run ## Code After: from nose...
from nose.tools import istest, assert_equal from spur import LocalShell shell = LocalShell() @istest def output_of_run_is_stored(): result = shell.run(["echo", "hello"]) assert_equal("hello\n", result.output) + + @istest + def cwd_of_run_can_be_set(): + result = shell.run(["pwd"], cw...
cd219d5ee0ecbd54705c5add4239cef1513b8c2a
dodocs/__init__.py
dodocs/__init__.py
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) if args.subparser_...
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) try: args....
Use args.func. Deal with failures, default "profile'
Use args.func. Deal with failures, default "profile'
Python
mit
montefra/dodocs
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ arg...
Use args.func. Deal with failures, default "profile'
## Code Before: import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ args = parse(argv=argv) if...
import sys import colorama from dodocs.cmdline import parse __version__ = "0.0.1" colorama.init(autoreset=True) def main(argv=None): """ Main code Parameters ---------- argv : list of strings, optional command line arguments """ arg...
b4f4e870877e4eae8e7dbf2dd9c961e5eec6980d
devtools/ci/push-docs-to-s3.py
devtools/ci/push-docs-to-s3.py
import os import pip import tempfile import subprocess import openpathsampling.version BUCKET_NAME = 'openpathsampling.org' if not openpathsampling.version.release: PREFIX = 'latest' else: PREFIX = openpathsampling.version.short_version if not any(d.project_name == 's3cmd' for d in pip.get_installed_distribu...
import os import pip import tempfile import subprocess import openpathsampling.version BUCKET_NAME = 'openpathsampling.org' if not openpathsampling.version.release: PREFIX = 'latest' else: PREFIX = openpathsampling.version.short_version if not any(d.project_name == 's3cmd' for d in pip.get_installed_distribu...
Add MIME-handling options to s3cmd
Add MIME-handling options to s3cmd
Python
mit
openpathsampling/openpathsampling,choderalab/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,choderalab/openpathsampling,dwhswenson/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openpathsampling,dwhswenson/openpathsampling,openpathsampling/openp...
import os import pip import tempfile import subprocess import openpathsampling.version BUCKET_NAME = 'openpathsampling.org' if not openpathsampling.version.release: PREFIX = 'latest' else: PREFIX = openpathsampling.version.short_version if not any(d.project_name == 's3cmd' for d i...
Add MIME-handling options to s3cmd
## Code Before: import os import pip import tempfile import subprocess import openpathsampling.version BUCKET_NAME = 'openpathsampling.org' if not openpathsampling.version.release: PREFIX = 'latest' else: PREFIX = openpathsampling.version.short_version if not any(d.project_name == 's3cmd' for d in pip.get_in...
import os import pip import tempfile import subprocess import openpathsampling.version BUCKET_NAME = 'openpathsampling.org' if not openpathsampling.version.release: PREFIX = 'latest' else: PREFIX = openpathsampling.version.short_version if not any(d.project_name == 's3cmd' for d i...
4a32838db7cbfa1962f3cd61f46caa308e4ea645
src/rgrep.py
src/rgrep.py
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the '\ 'same as grep\n' def rgrep(pattern='', text='', case='', count=False, version=False): if pattern == '' or text == '': return display_usage() elif not count: if case == 'i': ...
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the '\ 'same as grep\n' class RGrep(object): def __init__(self): self.version = 'RGrep (BSD) 0.0.1' self.count = False self.pattern = '' self.text = '' self.case = '' ...
Add match and case insensitive methods
Add match and case insensitive methods
Python
bsd-2-clause
ambidextrousTx/RGrep-Python
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the '\ 'same as grep\n' - - - def rgrep(pattern='', text='', case='', count=False, version=False): - if pattern == '' or text == '': - return display_usage() - elif not count: - if ca...
Add match and case insensitive methods
## Code Before: def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the '\ 'same as grep\n' def rgrep(pattern='', text='', case='', count=False, version=False): if pattern == '' or text == '': return display_usage() elif not count: if case =...
def display_usage(): return 'Usage: python rgrep [options] pattern files\nThe options are the '\ 'same as grep\n' - - - def rgrep(pattern='', text='', case='', count=False, version=False): - if pattern == '' or text == '': - return display_usage() - elif not count: - if ca...
32d4ea22c1bca4a96a8d826f0225dfee2a4c21d2
django_tenants/tests/__init__.py
django_tenants/tests/__init__.py
from .test_routes import * from .test_tenants import * from .test_cache import *
from .files import * from .staticfiles import * from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
Include static file-related tests in 'test' package.
fix(tests): Include static file-related tests in 'test' package.
Python
mit
tomturner/django-tenants,tomturner/django-tenants,tomturner/django-tenants
+ from .files import * + from .staticfiles import * + from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
Include static file-related tests in 'test' package.
## Code Before: from .test_routes import * from .test_tenants import * from .test_cache import * ## Instruction: Include static file-related tests in 'test' package. ## Code After: from .files import * from .staticfiles import * from .template import * from .test_routes import * from .test_tenants import * from .test_...
+ from .files import * + from .staticfiles import * + from .template import * from .test_routes import * from .test_tenants import * from .test_cache import *
8c3782e676e27bf6b3512ea390ad789698ba331c
memegen/routes/_cache.py
memegen/routes/_cache.py
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs): if kwargs['key'] == 'custom':...
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs): if kwargs['key'] == 'custom' ...
Disable caching of identical images
Disable caching of identical images
Python
mit
DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen,DanLindeman/memegen
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs):...
Disable caching of identical images
## Code Before: import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs): if kwargs['ke...
import logging import yorm from yorm.types import List, Object log = logging.getLogger(__name__) @yorm.attr(items=List.of_type(Object)) @yorm.sync("data/images/cache.yml") class Cache: SIZE = 9 def __init__(self): self.items = [] def add(self, **kwargs):...
33496a58852bcdb2ef9f3cbe1881b06efd48b624
script/sample/submitshell.py
script/sample/submitshell.py
import multyvac multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api') jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done') print("Submitted job [{}].".format(jid)) job = multyvac.get(jid) result = job.get_result() print("Result: [{}]".format(...
from __future__ import print_function import multyvac import sys multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api') jobs = { "stdout result": { "cmd": 'echo "success"', }, "file result": { "cmd": 'echo "success" > /tmp/out', "_resul...
Test different mechanisms for job submission.
Test different mechanisms for job submission.
Python
bsd-3-clause
cloudpipe/cloudpipe,cloudpipe/cloudpipe,cloudpipe/cloudpipe
+ + from __future__ import print_function import multyvac + import sys multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api') - jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done') - print("Submitted job [{}].".format(jid)) + jobs = ...
Test different mechanisms for job submission.
## Code Before: import multyvac multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api') jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done') print("Submitted job [{}].".format(jid)) job = multyvac.get(jid) result = job.get_result() print("Resul...
+ + from __future__ import print_function import multyvac + import sys multyvac.config.set_key(api_key='admin', api_secret_key='12345', api_url='http://docker:8000/api') - jid = multyvac.shell_submit(cmd='for i in {1..10}; do echo $i && sleep 10; done') - print("Submitted job [{}].".format(jid)) + jobs = ...
2a241bd07a4abd66656e3fb505310798f398db7f
respawn/cli.py
respawn/cli.py
from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --help respawn --version Options: ...
from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn import os def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --help respawn --version ...
Remove test print and use better practice to get path of gen.py
Remove test print and use better practice to get path of gen.py
Python
isc
dowjones/respawn,dowjones/respawn
from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn + import os def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn ...
Remove test print and use better practice to get path of gen.py
## Code Before: from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn --help respawn --ver...
from docopt import docopt from schema import Schema, Use, Or from subprocess import check_call, CalledProcessError from pkg_resources import require import respawn + import os def generate(): """Generate CloudFormation Template from YAML Specifications Usage: respawn <yaml> respawn ...
4467ffe669eec09bab16f4e5a3256ed333c5d3d5
rcamp/lib/ldap_utils.py
rcamp/lib/ldap_utils.py
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.in...
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) conn = ldap.in...
Set bytes_mode=False for future compatability with Python3
Set bytes_mode=False for future compatability with Python3
Python
mit
ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP,ResearchComputing/RCAMP
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW...
Set bytes_mode=False for future compatability with Python3
## Code Before: from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW) ...
from django.conf import settings from ldapdb import escape_ldap_filter import ldap def authenticate(dn,pwd,ldap_conf_key): # Setup connection ldap_conf = settings.LDAPCONFS[ldap_conf_key] server = ldap_conf['server'] ldap.set_option(ldap.OPT_X_TLS_REQUIRE_CERT, ldap.OPT_X_TLS_ALLOW...
ef98ba0f2aa660b85a4116d46679bf30321f2a05
scipy/spatial/transform/__init__.py
scipy/spatial/transform/__init__.py
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester
Add RotationSpline into __all__ of spatial.transform
MAINT: Add RotationSpline into __all__ of spatial.transform
Python
bsd-3-clause
grlee77/scipy,pizzathief/scipy,endolith/scipy,Eric89GXL/scipy,gertingold/scipy,aeklant/scipy,anntzer/scipy,tylerjereddy/scipy,ilayn/scipy,scipy/scipy,matthew-brett/scipy,jor-/scipy,endolith/scipy,ilayn/scipy,person142/scipy,Eric89GXL/scipy,nmayorov/scipy,lhilt/scipy,arokem/scipy,endolith/scipy,ilayn/scipy,WarrenWeckess...
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline - __all__ = ['Rotation', 'Slerp'] + __all__ = ['Rotation', 'Slerp', 'RotationSpline'] from scipy._lib._testutils import PytestTester test = PytestTester(...
Add RotationSpline into __all__ of spatial.transform
## Code Before: from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline __all__ = ['Rotation', 'Slerp'] from scipy._lib._testutils import PytestTester test = PytestTester(__name__) del PytestTester ## Instruction: Add Rotati...
from __future__ import division, print_function, absolute_import from .rotation import Rotation, Slerp from ._rotation_spline import RotationSpline - __all__ = ['Rotation', 'Slerp'] + __all__ = ['Rotation', 'Slerp', 'RotationSpline'] ? ++++++++++++++++++ from scipy._lib._...
83c5cc34539f68360cbab585af9465e95f3ec592
tensorbayes/__init__.py
tensorbayes/__init__.py
from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function
import sys from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function if 'ipykernel' in sys.argv[0]: from . import nbutils
Add nbutils import to base import
Add nbutils import to base import
Python
mit
RuiShu/tensorbayes
+ import sys from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function + if 'ipykernel' in sys.argv[0]: + from . import nbutils +
Add nbutils import to base import
## Code Before: from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function ## Instruction: Add nbutils import to base import ## Code After: import sys from . import layers from . import utils from . import...
+ import sys from . import layers from . import utils from . import nputils from . import tbutils from . import distributions from .utils import FileWriter from .tbutils import function + + if 'ipykernel' in sys.argv[0]: + from . import nbutils
8f03f51c89aeea44943f9cb0b39330e676ae0089
utils.py
utils.py
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is not None: ...
Change repeat command to return a list of the results of the repeated commands
Change repeat command to return a list of the results of the repeated commands
Python
mit
philipdexter/vx,philipdexter/vx
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name,...
Change repeat command to return a list of the results of the repeated commands
## Code Before: import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name, None) is no...
import vx from contextlib import contextmanager from functools import partial import sys from io import StringIO def _expose(f=None, name=None): if f is None: return partial(_expose, name=name) if name is None: name = f.__name__.lstrip('_') if getattr(vx, name,...
1bb86e33c8862b5423d292ccc1bd74c560af2e44
vinotes/apps/api/models.py
vinotes/apps/api/models.py
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Winery) def __str__(sel...
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Winery) def __str__(sel...
Update to include vintage in string representation for Wine.
Update to include vintage in string representation for Wine.
Python
unlicense
rcutmore/vinotes-api,rcutmore/vinotes-api
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Wine...
Update to include vintage in string representation for Wine.
## Code Before: from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Winery) ...
from django.db import models class Winery(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title class Wine(models.Model): title = models.CharField(max_length=150) vintage = models.IntegerField() winery = models.ForeignKey(Wine...
eea1ba0273b8e5362f6b27854e29e6053555fb2a
gittip/cli.py
gittip/cli.py
from gittip import wireup def payday(): db = wireup.db() wireup.billing() wireup.nanswers() # Lazily import the billing module. # ================================= # This dodges a problem where db in billing is None if we import it from # gittip before calling wireup.billing. from g...
import os from gittip import wireup def payday(): # Wire things up. # =============== # Manually override max db connections so that we only have one connection. # Our db access is serialized right now anyway, and with only one # connection it's easier to trust changes to statement_timeout. The p...
Configure payday for no db timeout
Configure payday for no db timeout
Python
mit
mccolgst/www.gittip.com,studio666/gratipay.com,studio666/gratipay.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,mccolgst/www.gittip.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,eXcomm/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,studio666/gratipay.com,eXcomm/gratipay.com,eXcomm/...
+ import os from gittip import wireup def payday(): + + # Wire things up. + # =============== + # Manually override max db connections so that we only have one connection. + # Our db access is serialized right now anyway, and with only one + # connection it's easier to trust changes to st...
Configure payday for no db timeout
## Code Before: from gittip import wireup def payday(): db = wireup.db() wireup.billing() wireup.nanswers() # Lazily import the billing module. # ================================= # This dodges a problem where db in billing is None if we import it from # gittip before calling wireup.bill...
+ import os from gittip import wireup def payday(): + + # Wire things up. + # =============== + # Manually override max db connections so that we only have one connection. + # Our db access is serialized right now anyway, and with only one + # connection it's easier to trust changes to st...
61b38528b60203003b9595f7ba2204c287dc6970
string/compress.py
string/compress.py
def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # reset count to 1
def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # reset count to 1 else:...
Add to current count if there is a match
Add to current count if there is a match
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # ...
Add to current count if there is a match
## Code Before: def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # reset co...
def compress_str(str): output = "" curr_char = "" char_count = "" for i in str: if curr_char != str[i]: output = output + curr_char + char_count # add new unique character and its count to our output curr_char = str[i] # move on to the next character in string char_count = 1 # ...
f14329dd4449c352cdf82ff2ffab0bfb9bcff882
parser.py
parser.py
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command...
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cmd is the command...
Fix parsing irc messages with empty list of parameters
Fix parsing irc messages with empty list of parameters
Python
mit
aalien/mib
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - ...
Fix parsing irc messages with empty list of parameters
## Code Before: from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - cm...
from collections import namedtuple IRCMsg = namedtuple('IRCMsg', 'prefix cmd params postfix') def parse(line): """ Parses line and returns a named tuple IRCMsg with fields (prefix, cmd, params, postfix). - prefix is the first part starting with : (colon), without the : - ...
8ecf9d95cf7f085b0245b07422ccda007937a5c6
visu3d/array_dataclass.py
visu3d/array_dataclass.py
"""Dataclass array wrapper.""" from __future__ import annotations import dataclass_array as dca from visu3d.plotly import fig_utils class DataclassArray(dca.DataclassArray, fig_utils.Visualizable): pass
"""Dataclass array wrapper.""" from __future__ import annotations import dataclass_array as dca from visu3d.plotly import fig_utils @dca.dataclass_array(broadcast=True, cast_dtype=True) class DataclassArray(dca.DataclassArray, fig_utils.Visualizable): pass
Add `@dca.dataclass_array` decorator to customize dca params. Change default values
Add `@dca.dataclass_array` decorator to customize dca params. Change default values PiperOrigin-RevId: 475563717
Python
apache-2.0
google-research/visu3d
"""Dataclass array wrapper.""" from __future__ import annotations import dataclass_array as dca from visu3d.plotly import fig_utils + @dca.dataclass_array(broadcast=True, cast_dtype=True) class DataclassArray(dca.DataclassArray, fig_utils.Visualizable): pass
Add `@dca.dataclass_array` decorator to customize dca params. Change default values
## Code Before: """Dataclass array wrapper.""" from __future__ import annotations import dataclass_array as dca from visu3d.plotly import fig_utils class DataclassArray(dca.DataclassArray, fig_utils.Visualizable): pass ## Instruction: Add `@dca.dataclass_array` decorator to customize dca params. Change default ...
"""Dataclass array wrapper.""" from __future__ import annotations import dataclass_array as dca from visu3d.plotly import fig_utils + @dca.dataclass_array(broadcast=True, cast_dtype=True) class DataclassArray(dca.DataclassArray, fig_utils.Visualizable): pass
ed88d9b598b3bd360a6575d83ffd3d4044846a96
traits/tests/test_array.py
traits/tests/test_array.py
from __future__ import absolute_import from traits.testing.unittest_tools import unittest try: import numpy except ImportError: numpy_available = False else: numpy_available = True from ..api import Array, Bool, HasTraits class Foo(HasTraits): a = Array() event_fired = Bool(False) def _a_...
from __future__ import absolute_import from traits.testing.unittest_tools import unittest try: import numpy except ImportError: numpy_available = False else: numpy_available = True from ..api import Array, Bool, HasTraits if numpy_available: # Use of `Array` requires NumPy to be installed. cl...
Make definition of conditional on NumPy being installed; update skip message to match that used elsewhere
Make definition of conditional on NumPy being installed; update skip message to match that used elsewhere
Python
bsd-3-clause
burnpanck/traits,burnpanck/traits
from __future__ import absolute_import from traits.testing.unittest_tools import unittest try: import numpy except ImportError: numpy_available = False else: numpy_available = True from ..api import Array, Bool, HasTraits + if numpy_available: + # Use of `Array` requi...
Make definition of conditional on NumPy being installed; update skip message to match that used elsewhere
## Code Before: from __future__ import absolute_import from traits.testing.unittest_tools import unittest try: import numpy except ImportError: numpy_available = False else: numpy_available = True from ..api import Array, Bool, HasTraits class Foo(HasTraits): a = Array() event_fired = Bool(Fal...
from __future__ import absolute_import from traits.testing.unittest_tools import unittest try: import numpy except ImportError: numpy_available = False else: numpy_available = True from ..api import Array, Bool, HasTraits + if numpy_available: + # Use of `Array` requi...
e8708c28e79a9063469e684b5583114c69ec425f
datadog_checks_dev/datadog_checks/dev/spec.py
datadog_checks_dev/datadog_checks/dev/spec.py
import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'manifest.json'))) relative...
import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'manifest.json'))) assets =...
Fix CI for logs E2E with v2 manifests
Fix CI for logs E2E with v2 manifests
Python
bsd-3-clause
DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core,DataDog/integrations-core
import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'ma...
Fix CI for logs E2E with v2 manifests
## Code Before: import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'manifest.json'...
import json import yaml from .utils import file_exists, path_join, read_file def load_spec(check_root): spec_path = get_spec_path(check_root) return yaml.safe_load(read_file(spec_path)) def get_spec_path(check_root): manifest = json.loads(read_file(path_join(check_root, 'ma...
c33ce5e8d998278d01310205598ceaf15b1573ab
logya/core.py
logya/core.py
from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbose = getattr(options, 've...
from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbose = getattr(options, 've...
Rename build_index to build and add logic to setup template env
Rename build_index to build and add logic to setup template env
Python
mit
elaOnMars/logya,elaOnMars/logya,elaOnMars/logya,yaph/logya,yaph/logya
from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbos...
Rename build_index to build and add logic to setup template env
## Code Before: from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbose = geta...
from logya.content import read_all from logya.template import init_env from logya.util import load_yaml, paths class Logya: """Object to store data such as site index and settings.""" def __init__(self, options): """Set required logya object properties.""" self.verbos...
5a09b88399b34ea8a5185fe1bcdff5f3f7ac7619
invoke_pytest.py
invoke_pytest.py
import sys import py if __name__ == "__main__": sys.exit(py.test.cmdline.main())
import os import sys import py if __name__ == "__main__": os.environ["PYTEST_MD_REPORT_COLOR"] = "text" sys.exit(py.test.cmdline.main())
Add PYTEST_MD_REPORT_COLOR environment variable setting
Add PYTEST_MD_REPORT_COLOR environment variable setting
Python
mit
thombashi/pingparsing,thombashi/pingparsing
+ import os import sys import py if __name__ == "__main__": + os.environ["PYTEST_MD_REPORT_COLOR"] = "text" sys.exit(py.test.cmdline.main())
Add PYTEST_MD_REPORT_COLOR environment variable setting
## Code Before: import sys import py if __name__ == "__main__": sys.exit(py.test.cmdline.main()) ## Instruction: Add PYTEST_MD_REPORT_COLOR environment variable setting ## Code After: import os import sys import py if __name__ == "__main__": os.environ["PYTEST_MD_REPORT_COLOR"] = "text" sys.exit(py...
+ import os import sys import py if __name__ == "__main__": + os.environ["PYTEST_MD_REPORT_COLOR"] = "text" sys.exit(py.test.cmdline.main())
dd35907f9164cd8f75babb1b5b9b6ff9711628fb
djangopeople/djangopeople/management/commands/fix_counts.py
djangopeople/djangopeople/management/commands/fix_counts.py
from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): for qs in...
from django.core.management.base import BaseCommand from ...models import Country, Region class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle(self, **options): for qs in (Country.o...
Remove usage of deprecated NoArgsCommand
Remove usage of deprecated NoArgsCommand
Python
mit
brutasse/djangopeople,django/djangopeople,django/djangopeople,django/djangopeople,brutasse/djangopeople,brutasse/djangopeople,brutasse/djangopeople
- from django.core.management.base import NoArgsCommand + from django.core.management.base import BaseCommand from ...models import Country, Region - class Command(NoArgsCommand): + class Command(BaseCommand): """ Countries and regions keep a denormalized count of people that gets out of sy...
Remove usage of deprecated NoArgsCommand
## Code Before: from django.core.management.base import NoArgsCommand from ...models import Country, Region class Command(NoArgsCommand): """ Countries and regions keep a denormalized count of people that gets out of sync during migrate. This updates it. """ def handle_noargs(self, **options): ...
- from django.core.management.base import NoArgsCommand ? ^^^^^ + from django.core.management.base import BaseCommand ? ^^ + from ...models import Country, Region - class Command(NoArgsCommand): ? ^^^^^ + class C...
35201e71037d544893a59bfda8c4538fcb6fb4b7
api/tests/test_scrape_item.py
api/tests/test_scrape_item.py
from api.scrapers.item import scrape_item_by_id from api import app from flask.json import loads import unittest app.config['TESTING'] = True class ScrapeItem(unittest.TestCase): def test_scrape_item_by_id(self): item = scrape_item_by_id('d19447e548d') self.assertEqual('d19447e548d', item.lode...
from api.scrapers.item import scrape_item_by_id from api import app, db from flask.json import loads import unittest app.config['TESTING'] = True db.create_all() class ScrapeItem(unittest.TestCase): def test_scrape_item_by_id(self): item = scrape_item_by_id('d19447e548d') self.assertEqual('d19...
Create tables in database before running tests
Create tables in database before running tests
Python
mit
Demotivated/loadstone
from api.scrapers.item import scrape_item_by_id - from api import app + from api import app, db from flask.json import loads import unittest app.config['TESTING'] = True + db.create_all() class ScrapeItem(unittest.TestCase): def test_scrape_item_by_id(self): item = scrape_ite...
Create tables in database before running tests
## Code Before: from api.scrapers.item import scrape_item_by_id from api import app from flask.json import loads import unittest app.config['TESTING'] = True class ScrapeItem(unittest.TestCase): def test_scrape_item_by_id(self): item = scrape_item_by_id('d19447e548d') self.assertEqual('d19447e...
from api.scrapers.item import scrape_item_by_id - from api import app + from api import app, db ? ++++ from flask.json import loads import unittest app.config['TESTING'] = True + db.create_all() class ScrapeItem(unittest.TestCase): def test_scrape_item_by_id(self): ...
7a00293d602c1997777fb90331fcbf7cde1b0838
tweet.py
tweet.py
from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html#python-specific-encodings status = urandom(140).decode('utf-8', errors='ignore') tweet = account.update_status(status=status) # Gotta like this tweet, after all, ...
from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html status = urandom(400).decode('utf-8', errors='ignore') status = status[0:140] tweet = account.update_status(status=status) # Gotta like this tweet, after all, we...
Make sure we fill all 140 possible characters.
Make sure we fill all 140 possible characters.
Python
mit
chrisma/dev-urandom,chrisma/dev-urandom
from twython import Twython from credentials import * from os import urandom def random_tweet(account): - # https://docs.python.org/2/library/codecs.html#python-specific-encodings + # https://docs.python.org/2/library/codecs.html - status = urandom(140).decode('utf-8', errors='ignore') + status = uran...
Make sure we fill all 140 possible characters.
## Code Before: from twython import Twython from credentials import * from os import urandom def random_tweet(account): # https://docs.python.org/2/library/codecs.html#python-specific-encodings status = urandom(140).decode('utf-8', errors='ignore') tweet = account.update_status(status=status) # Gotta like this tw...
from twython import Twython from credentials import * from os import urandom def random_tweet(account): - # https://docs.python.org/2/library/codecs.html#python-specific-encodings ? -------------------------- + # https://docs.python.org/2/library/codecs.h...
a7328bd229070126ca5b09bb1c9fe4c5e319bb04
members/urls.py
members/urls.py
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_student_council', ...
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_student_council', ...
Add url for user's profile
Add url for user's profile
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_st...
Add url for user's profile
## Code Before: from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_st...
from django.conf.urls import patterns, url from django.contrib import auth urlpatterns = patterns('members.views', url(r'^login/$', 'login', name='login'), url(r'^logout/$', 'logout', name='logout'), url(r'^search/(?P<name>.*)/$', 'search', name='search'), url(r'^archive/$', 'archive_st...
f1cf2d2e9cbdd4182a5a755b5958e499fc9d9585
gcloud_expenses/views.py
gcloud_expenses/views.py
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_nam...
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_config(route_nam...
Improve status display for reports.
Improve status display for reports.
Python
apache-2.0
GoogleCloudPlatform/google-cloud-python-expenses-demo,GoogleCloudPlatform/google-cloud-python-expenses-demo
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() ...
Improve status display for reports.
## Code Before: from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() @view_...
from pyramid.renderers import get_renderer from pyramid.view import view_config from . import get_report_info from . import list_employees from . import list_reports def get_main_template(request): main_template = get_renderer('templates/main.pt') return main_template.implementation() ...
a10fb75a45bbb647f8071842773d79101c797529
corehq/project_limits/models.py
corehq/project_limits/models.py
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hou...
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=True) per_hou...
Clear caches on DynamicRateDefinition deletion for completeness
Clear caches on DynamicRateDefinition deletion for completeness and to help with tests
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=Tru...
Clear caches on DynamicRateDefinition deletion for completeness
## Code Before: from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=T...
from django.db import models class DynamicRateDefinition(models.Model): key = models.CharField(max_length=512, blank=False, null=False, unique=True, db_index=True) per_week = models.FloatField(default=None, blank=True, null=True) per_day = models.FloatField(default=None, blank=True, null=Tru...
a540a68561db4067b66b4d4d0920b217fea4fda4
var/spack/packages/openssl/package.py
var/spack/packages/openssl/package.py
from spack import * class Openssl(Package): """The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a full-...
from spack import * class Openssl(Package): """The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as a full-...
Make OpenSSL build on Darwin
Make OpenSSL build on Darwin
Python
lgpl-2.1
matthiasdiener/spack,EmreAtes/spack,krafczyk/spack,iulian787/spack,matthiasdiener/spack,tmerrick1/spack,krafczyk/spack,lgarren/spack,TheTimmy/spack,iulian787/spack,EmreAtes/spack,EmreAtes/spack,skosukhin/spack,krafczyk/spack,mfherbst/spack,LLNL/spack,mfherbst/spack,skosukhin/spack,krafczyk/spack,mfherbst/spack,tmerrick...
from spack import * class Openssl(Package): """The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as ...
Make OpenSSL build on Darwin
## Code Before: from spack import * class Openssl(Package): """The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well a...
from spack import * class Openssl(Package): """The OpenSSL Project is a collaborative effort to develop a robust, commercial-grade, full-featured, and Open Source toolkit implementing the Secure Sockets Layer (SSL v2/v3) and Transport Layer Security (TLS v1) protocols as well as ...
27aad0e3ed95cb43b28eb3c02fa96b3a9b74de5b
tests/test_container.py
tests/test_container.py
from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w')
import os import sys import unittest from .common import * # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. # Starting with Python 3.6 the situation is saner thanks to PEP 529: # # https://www.python.org/dev/peps/pep-0529/ broken_unicode = ( os.name == 'nt' and sys.version_info >= (3, ...
Disable unicode filename test on Windows with Python 3.0 - 3.5
Disable unicode filename test on Windows with Python 3.0 - 3.5 Before PEP 529 landed in Python 3.6, unicode filename handling on Windows is hit-and-miss, so don't break CI.
Python
bsd-3-clause
PyAV-Org/PyAV,mikeboers/PyAV,PyAV-Org/PyAV,mikeboers/PyAV
+ + import os + import sys + import unittest from .common import * + + # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. + # Starting with Python 3.6 the situation is saner thanks to PEP 529: + # + # https://www.python.org/dev/peps/pep-0529/ + + broken_unicode = ( + os.name == 'nt' and ...
Disable unicode filename test on Windows with Python 3.0 - 3.5
## Code Before: from .common import * class TestContainers(TestCase): def test_unicode_filename(self): container = av.open(self.sandboxed(u'¢∞§¶•ªº.mov'), 'w') ## Instruction: Disable unicode filename test on Windows with Python 3.0 - 3.5 ## Code After: import os import sys import unittest from .com...
+ + import os + import sys + import unittest from .common import * + + # On Windows, Python 3.0 - 3.5 have issues handling unicode filenames. + # Starting with Python 3.6 the situation is saner thanks to PEP 529: + # + # https://www.python.org/dev/peps/pep-0529/ + + broken_unicode = ( + os.name == 'nt' and ...
cf0850e23b07c656bd2bc56c88f9119dc4142931
mooch/banktransfer.py
mooch/banktransfer.py
from django import http from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from mooch.base import BaseMoocher, require_POST_m from mooch.signals imp...
from django import http from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from mooch.base import BaseMoocher, require_POST_m from mooch.signals imp...
Allow disabling the autocharging behavior of the bank transfer moocher
Allow disabling the autocharging behavior of the bank transfer moocher
Python
mit
matthiask/django-mooch,matthiask/django-mooch,matthiask/django-mooch
from django import http from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from mooch.base import BaseMoocher, require_POST_m from...
Allow disabling the autocharging behavior of the bank transfer moocher
## Code Before: from django import http from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from mooch.base import BaseMoocher, require_POST_m from m...
from django import http from django.conf.urls import url from django.shortcuts import get_object_or_404 from django.template.loader import render_to_string from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from mooch.base import BaseMoocher, require_POST_m from...
4486fba6dd75dab67c25221653f2384455eda9be
tests/test_sorting_and_searching/test_binary_search.py
tests/test_sorting_and_searching/test_binary_search.py
import unittest from sorting_and_searching import binary_search_recursive class BinarySearchTestCase(unittest.TestCase): ''' Unit tests for binary search ''' def setUp(self): self.example_1 = [2, 3, 4, 10, 40] def test_binary_search_recursive(self): result = binary_search_recurs...
import unittest from aids.sorting_and_searching.binary_search import binary_search_recursive, binary_search_iterative class BinarySearchTestCase(unittest.TestCase): ''' Unit tests for binary search ''' def setUp(self): self.example_1 = [2, 3, 4, 10, 40] def test_binary_search_recursive(...
Add unit tests for binary search recursive and iterative
Add unit tests for binary search recursive and iterative
Python
mit
ueg1990/aids
import unittest - from sorting_and_searching import binary_search_recursive + from aids.sorting_and_searching.binary_search import binary_search_recursive, binary_search_iterative class BinarySearchTestCase(unittest.TestCase): ''' Unit tests for binary search ''' def setUp(self):...
Add unit tests for binary search recursive and iterative
## Code Before: import unittest from sorting_and_searching import binary_search_recursive class BinarySearchTestCase(unittest.TestCase): ''' Unit tests for binary search ''' def setUp(self): self.example_1 = [2, 3, 4, 10, 40] def test_binary_search_recursive(self): result = bina...
import unittest - from sorting_and_searching import binary_search_recursive + from aids.sorting_and_searching.binary_search import binary_search_recursive, binary_search_iterative class BinarySearchTestCase(unittest.TestCase): ''' Unit tests for binary search ''' def setUp(self):...
6b2ac1d6be094eddc6a940eb1dafa32e483a6b7e
ereuse_devicehub/resources/device/peripheral/settings.py
ereuse_devicehub/resources/device/peripheral/settings.py
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', 'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Terminal', 'HUB', 'S...
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', 'allowed': { 'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Termina...
Add new types of peripherals
Add new types of peripherals
Python
agpl-3.0
eReuse/DeviceHub,eReuse/DeviceHub
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', + 'allowed': { - 'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'M...
Add new types of peripherals
## Code Before: import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', 'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'MultifunctionPrinter', 'Term...
import copy from ereuse_devicehub.resources.device.schema import Device from ereuse_devicehub.resources.device.settings import DeviceSubSettings class Peripheral(Device): type = { 'type': 'string', + 'allowed': { - 'allowed': {'Router', 'Switch', 'Printer', 'Scanner', 'M...
91c6c7b8e8077a185e8a62af0c3bcb74d4026e7c
tests/search.py
tests/search.py
import pycomicvine import unittest api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestSearch(unittest.TestCase): def test_search_resource_type(self): search = pycomicvine.Search( resources="volume", query="Angel" ) self.assertIsInstance(sear...
import pycomicvine import unittest api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestSearch(unittest.TestCase): def test_search_resource_type(self): search = pycomicvine.Search( resources="volume", query="Angel" ) for v in search: ...
Check every result in Search test
Check every result in Search test
Python
mit
authmillenon/pycomicvine
import pycomicvine import unittest api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestSearch(unittest.TestCase): def test_search_resource_type(self): search = pycomicvine.Search( resources="volume", query="Angel" ) + fo...
Check every result in Search test
## Code Before: import pycomicvine import unittest api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestSearch(unittest.TestCase): def test_search_resource_type(self): search = pycomicvine.Search( resources="volume", query="Angel" ) self.asser...
import pycomicvine import unittest api_key = "476302e62d7e8f8f140182e36aebff2fe935514b" class TestSearch(unittest.TestCase): def test_search_resource_type(self): search = pycomicvine.Search( resources="volume", query="Angel" ) + fo...
f9ffd5021f8af96df503c8a2743e97c8f1a17be0
infupy/backends/common.py
infupy/backends/common.py
def printerr(msg, e=''): print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Syringe(): _ev...
def printerr(msg, e=''): msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(sel...
Add marker to indicate backend error
Add marker to indicate backend error
Python
isc
jaj42/infupy
def printerr(msg, e=''): + msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command...
Add marker to indicate backend error
## Code Before: def printerr(msg, e=''): print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command error: {}".format(self.args) class Sy...
def printerr(msg, e=''): + msg = "Backend: " + str(msg) print(msg.format(e), file=sys.stderr) class CommunicationError(Exception): def __str__(self): return "Communication error: {}".format(self.args) class CommandError(Exception): def __str__(self): return "Command...
eacc66e5a9ab3310c75924dcb340e4944e9424d4
tests/specifications/external_spec_test.py
tests/specifications/external_spec_test.py
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(checkid, font=None, **iterargs): if checkid in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/036", # ots-sanitize "com.google.fonts/check/037", # Font Validator ...
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(checkid, font=None, **iterargs): if checkid in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/036", # ots-sanitize "com.google.fonts/check/037", # Font Validator ...
Test for expected and unexpected checks
Test for expected and unexpected checks
Python
apache-2.0
googlefonts/fontbakery,graphicore/fontbakery,graphicore/fontbakery,googlefonts/fontbakery,googlefonts/fontbakery,moyogo/fontbakery,moyogo/fontbakery,moyogo/fontbakery,graphicore/fontbakery
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(checkid, font=None, **iterargs): if checkid in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/036", # ots-sanitize "com.google.fonts/check/037", #...
Test for expected and unexpected checks
## Code Before: from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(checkid, font=None, **iterargs): if checkid in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/036", # ots-sanitize "com.google.fonts/check/037", # F...
from fontbakery.checkrunner import Section from fontbakery.fonts_spec import spec_factory def check_filter(checkid, font=None, **iterargs): if checkid in ( "com.google.fonts/check/035", # ftxvalidator "com.google.fonts/check/036", # ots-sanitize "com.google.fonts/check/037", #...
ed46ee16ed1b8efcee3697d3da909f72b0755a13
webcomix/tests/test_docker.py
webcomix/tests/test_docker.py
import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = DockerManager(True)...
import docker import pytest from webcomix.docker import DockerManager, CONTAINER_NAME @pytest.fixture def cleanup_container(test): yield None client = docker.from_env() for container in client.containers().list(): if container.attrs["Config"]["Image"] == CONTAINER_NAME: container.kill(...
Add test fixture for docker tests
Add test fixture for docker tests
Python
mit
J-CPelletier/webcomix,J-CPelletier/webcomix
import docker + import pytest - from webcomix.docker import DockerManager + from webcomix.docker import DockerManager, CONTAINER_NAME + @pytest.fixture + def cleanup_container(test): + yield None + client = docker.from_env() + for container in client.containers().list(): + if container.attrs...
Add test fixture for docker tests
## Code Before: import docker from webcomix.docker import DockerManager def test_no_javascript_spawns_no_container(): manager = DockerManager(False) manager.__enter__() manager.client = docker.from_env() assert manager._get_container() is None def test_javascript_spawns_container(): manager = Doc...
import docker + import pytest - from webcomix.docker import DockerManager + from webcomix.docker import DockerManager, CONTAINER_NAME ? ++++++++++++++++ + @pytest.fixture + def cleanup_container(test): + yield None + client = docker.from_env() + for containe...
8dcf6c373316d21399fa1edd276cea357fea75fb
groundstation/sockets/stream_socket.py
groundstation/sockets/stream_socket.py
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # XXX Implement the...
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # XXX Implement the...
Support being given protobuf Messages
Support being given protobuf Messages
Python
mit
richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation,richo/groundstation
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
Support being given protobuf Messages
## Code Before: import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # X...
import socket import groundstation.logger log = groundstation.logger.getLogger(__name__) from groundstation.peer_socket import PeerSocket class StreamSocket(object): """Wraps a TCP socket""" def __init__(self): self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
8d5b0682c3262fa210c3ed5e50c91259f1f2550c
myhome/blog/models.py
myhome/blog/models.py
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() live = model...
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) class Meta: ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) ...
Set default ordering for blog post tags
Set default ordering for blog post tags
Python
mit
plumdog/myhome,plumdog/myhome,plumdog/myhome,plumdog/myhome
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) + + class Meta: + ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models....
Set default ordering for blog post tags
## Code Before: from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models.CharField(max_length=255) content = models.TextField() ...
from django.db import models class BlogPostTag(models.Model): name = models.CharField(max_length=255) + + class Meta: + ordering = ['name'] def __str__(self): return self.name class BlogPost(models.Model): datetime = models.DateTimeField() title = models....
72655f0b0c7edfd3f51fe0ea847d45f9acd5ba42
hoomd/triggers.py
hoomd/triggers.py
from hoomd import _hoomd class Trigger(_hoomd.Trigger): pass class PeriodicTrigger(_hoomd.PeriodicTrigger): def __init__(self, period, phase=0): _hoomd.PeriodicTrigger.__init__(self, period, phase)
from hoomd import _hoomd class Trigger(_hoomd.Trigger): pass class PeriodicTrigger(_hoomd.PeriodicTrigger, Trigger): def __init__(self, period, phase=0): _hoomd.PeriodicTrigger.__init__(self, period, phase)
Make ``PeriodicTrigger`` inherent from ``Trigger``
Make ``PeriodicTrigger`` inherent from ``Trigger`` Fixes bug in checking state and preprocessing ``Triggers`` for duck typing.
Python
bsd-3-clause
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
from hoomd import _hoomd + class Trigger(_hoomd.Trigger): pass + - class PeriodicTrigger(_hoomd.PeriodicTrigger): + class PeriodicTrigger(_hoomd.PeriodicTrigger, Trigger): def __init__(self, period, phase=0): _hoomd.PeriodicTrigger.__init__(self, period, phase)
Make ``PeriodicTrigger`` inherent from ``Trigger``
## Code Before: from hoomd import _hoomd class Trigger(_hoomd.Trigger): pass class PeriodicTrigger(_hoomd.PeriodicTrigger): def __init__(self, period, phase=0): _hoomd.PeriodicTrigger.__init__(self, period, phase) ## Instruction: Make ``PeriodicTrigger`` inherent from ``Trigger`` ## Code After: fro...
from hoomd import _hoomd + class Trigger(_hoomd.Trigger): pass + - class PeriodicTrigger(_hoomd.PeriodicTrigger): + class PeriodicTrigger(_hoomd.PeriodicTrigger, Trigger): ? +++++++++ def __init__(self, period, phase=0): _hoomd.PeriodicTr...