Datasets:

commit
stringlengths
40
40
old_file
stringlengths
4
118
new_file
stringlengths
4
118
old_contents
stringlengths
10
2.94k
new_contents
stringlengths
21
3.18k
subject
stringlengths
16
444
message
stringlengths
17
2.63k
lang
stringclasses
1 value
license
stringclasses
13 values
repos
stringlengths
5
43k
ndiff
stringlengths
51
3.32k
instruction
stringlengths
16
444
content
stringlengths
133
4.32k
91709b78c27ed0e05f3c67fcc13ffa8085dac15a
heavy-ion-luminosity.py
heavy-ion-luminosity.py
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) print(arr.dtype) # The TTree name is al...
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) for element in arr.dtype.names: pri...
Print out dtypes in .root file individually
Print out dtypes in .root file individually
Python
mit
jacobbieker/ATLAS-Luminosity
__author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) - print(arr.d...
Print out dtypes in .root file individually
## Code Before: __author__ = 'jacob' import ROOT import numpy as np import os from root_numpy import root2array, root2rec, tree2rec # Look at r284484 data filename = os.path.join("data", "r284484.root") # Convert a TTree in a ROOT file into a NumPy structured array arr = root2array(filename) print(arr.dtype) # The ...
bfec6f3e2db99e20baf9b87fcd85da9ff050b030
UM/OutputDevice/OutputDeviceError.py
UM/OutputDevice/OutputDeviceError.py
class ErrorCodes: UserCanceledError = 1 DeviceBusyError = 2 class WriteRequestFailedError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code self.message = message
class WriteRequestFailedError(Exception): pass class UserCancelledError(WriteRequestFailedError): pass class PermissionDeniedError(WriteRequestFailedError): pass class DeviceBusyError(WriteRequestFailedError): pass
Replace error codes with error subclasses
Replace error codes with error subclasses This provides the same information but is a cleaner solution for python
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
- - class ErrorCodes: - UserCanceledError = 1 - DeviceBusyError = 2 class WriteRequestFailedError(Exception): + pass - def __init__(self, code, message): - super().__init__(message) - self.code = code - self.message = message + class UserCancelledError(WriteRequestFailed...
Replace error codes with error subclasses
## Code Before: class ErrorCodes: UserCanceledError = 1 DeviceBusyError = 2 class WriteRequestFailedError(Exception): def __init__(self, code, message): super().__init__(message) self.code = code self.message = message ## Instruction: Replace error codes with error subclasses ## C...
094132685688d0e9e599da6e8c0e0554945d56a5
html5lib/trie/datrie.py
html5lib/trie/datrie.py
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(key, str): ...
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not is...
Fix DATrie support under Python 2.
Fix DATrie support under Python 2. This is a simple issue of using `str` to refer to what should be `six.text_type`.
Python
mit
mindw/html5lib-python,html5lib/html5lib-python,alex/html5lib-python,gsnedders/html5lib-python,ordbogen/html5lib-python,dstufft/html5lib-python,alex/html5lib-python,mgilson/html5lib-python,alex/html5lib-python,mindw/html5lib-python,dstufft/html5lib-python,dstufft/html5lib-python,ordbogen/html5lib-python,html5lib/html5li...
from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie + from six import text_type from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.key...
Fix DATrie support under Python 2.
## Code Before: from __future__ import absolute_import, division, unicode_literals from itertools import chain from datrie import Trie as DATrie from ._base import Trie as ABCTrie class Trie(ABCTrie): def __init__(self, data): chars = set() for key in data.keys(): if not isinstance(k...
e20dc134911ad7b99014fdbf77dacd498cecce19
eventkit/plugins/fluentevent/migrations/0002_fluentevent_layout.py
eventkit/plugins/fluentevent/migrations/0002_fluentevent_layout.py
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_name='fluentevent...
Update related name for `layout` field.
Update related name for `layout` field.
Python
mit
ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events,ic-labs/icekit-events,ic-labs/django-icekit,ic-labs/django-icekit,ic-labs/icekit-events
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( ...
Update related name for `layout` field.
## Code Before: from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('icekit', '0002_layout'), ('eventkit_fluentevent', '0001_initial'), ] operations = [ migrations.AddField( model_n...
73f76034b0d00c48774cafe3584bb672b8ba55bd
apps/announcements/models.py
apps/announcements/models.py
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): author = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('author', 'objec...
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_t...
Rename of the author field to content_type in the model, in order to avoid confusion
Rename of the author field to content_type in the model, in order to avoid confusion
Python
agpl-3.0
LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr,LinuxTeam-teilar/cronos.teilar.gr
from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): - author = models.ForeignKey(ContentType) + content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerFie...
Rename of the author field to content_type in the model, in order to avoid confusion
## Code Before: from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic class Authors(models.Model): author = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey(...
d6b7cccb14cd1f82bb3a6b070999204fafacf07e
hyper/common/util.py
hyper/common/util.py
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: ...
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element else: ...
Fix to_host_port_tuple to resolve test case issues
Fix to_host_port_tuple to resolve test case issues
Python
mit
Lukasa/hyper,lawnmowerlatte/hyper,irvind/hyper,Lukasa/hyper,lawnmowerlatte/hyper,fredthomsen/hyper,irvind/hyper,plucury/hyper,fredthomsen/hyper,plucury/hyper
from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return eleme...
Fix to_host_port_tuple to resolve test case issues
## Code Before: from hyper.compat import unicode, bytes, imap def to_bytestring(element): """ Converts a single string to a bytestring, encoding via UTF-8 if needed. """ if isinstance(element, unicode): return element.encode('utf-8') elif isinstance(element, bytes): return element ...
67a50f33177e0fa6aec15fc7d26836c38b374c31
plugins/lastfm.py
plugins/lastfm.py
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=...
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", api_key=...
Fix last.fm bug for users not listening to something.
Fix last.fm bug for users not listening to something. The last.fm plugin previously worked only for users not listening to anything, and then it was 'fixed' for users listening to something, but broke for users not listening to something. See lastfm.py comments for changes.
Python
unlicense
parkrrr/skybot,Jeebeevee/DouweBot_JJ15,craisins/wh2kbot,callumhogsden/ausbot,df-5/skybot,ddwo/nhl-bot,Jeebeevee/DouweBot,rmmh/skybot,TeamPeggle/ppp-helpdesk,crisisking/skybot,Teino1978-Corp/Teino1978-Corp-skybot,isislab/botbot,cmarguel/skybot,jmgao/skybot,craisins/nascarbot,olslash/skybot,andyeff/skybot,SophosBlitz/gla...
from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", ...
Fix last.fm bug for users not listening to something.
## Code Before: from util import hook, http api_key = "" api_url = "http://ws.audioscrobbler.com/2.0/?format=json" @hook.command def lastfm(inp, nick='', say=None): if inp: user = inp else: user = nick response = http.get_json(api_url, method="user.getrecenttracks", ...
c487dfc63e71abb0e11534c42591c216def5c433
ITDB/ITDB_Main/views.py
ITDB/ITDB_Main/views.py
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at the ITDB_Main in...
from django.http import Http404 from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're ...
Update theater view to use get_object_or_404 shortcut
Update theater view to use get_object_or_404 shortcut
Python
apache-2.0
Plaudenslager/ITDB,Plaudenslager/ITDB,Plaudenslager/ITDB
from django.http import Http404 from django.http import HttpResponse - from django.shortcuts import render + from django.shortcuts import get_object_or_404, render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(re...
Update theater view to use get_object_or_404 shortcut
## Code Before: from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render from django.template import RequestContext, loader from .models import Theater # Default first page. Should be the search page. def index(request): return HttpResponse("Hello, world. You're at ...
18ed712bad3beb8c128f56638878e66f34bcf722
Lib/test/test_binhex.py
Lib/test/test_binhex.py
import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my hero' f.writ...
import binhex import os import tempfile import test_support import unittest class BinHexTestCase(unittest.TestCase): def setUp(self): self.fname1 = tempfile.mktemp() self.fname2 = tempfile.mktemp() def tearDown(self): try: os.unlink(self.fname1) except OSError: pass ...
Convert binhex regression test to PyUnit. We could use a better test for this.
Convert binhex regression test to PyUnit. We could use a better test for this.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
import binhex + import os import tempfile - from test_support import verbose, TestSkipped + import test_support + import unittest - def test(): + class BinHexTestCase(unittest.TestCase): - try: - fname1 = tempfile.mktemp() - fname2 = tempfile.mktemp() - f = open(fname1, 'w') - ...
Convert binhex regression test to PyUnit. We could use a better test for this.
## Code Before: import binhex import tempfile from test_support import verbose, TestSkipped def test(): try: fname1 = tempfile.mktemp() fname2 = tempfile.mktemp() f = open(fname1, 'w') except: raise TestSkipped, "Cannot test binhex without a temp file" start = 'Jack is my ...
9fece51bc6b3496381871c0fc7db486f8fbfebd7
chef/tests/test_role.py
chef/tests/test_role.py
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) ...
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r.run_list, []) ...
Add tests for role attributes.
Add tests for role attributes.
Python
apache-2.0
cread/pychef,jarosser06/pychef,jarosser06/pychef,coderanger/pychef,Scalr/pychef,dipakvwarade/pychef,cread/pychef,dipakvwarade/pychef,coderanger/pychef,Scalr/pychef
from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqu...
Add tests for role attributes.
## Code Before: from chef import Role from chef.exceptions import ChefError from chef.tests import ChefTestCase class RoleTestCase(ChefTestCase): def test_get(self): r = Role('test_1') self.assertTrue(r.exists) self.assertEqual(r.description, 'Static test role 1') self.assertEqual(r...
9f925f0da6d3a06d085ee71b8bee0fcdecaed5a0
marrow/schema/transform/primitive.py
marrow/schema/transform/primitive.py
raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set...
from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null Tuple List Set Mapping Sequence Tuple Integer Flo...
Fix for insanely silly pip.
Fix for insanely silly pip.
Python
mit
marrow/schema,marrow/schema
- - raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Comp...
Fix for insanely silly pip.
## Code Before: raise ImportError("For future use.") from __future__ import unicode_literals from ..compat import unicode from .base import Concern, Transform, Attribute class Primitive(Transform): pass """ Primitive VInteger (min/max) VFloat (min/max) Decimal (min/max) Complex String Binary Unicode Null...
57ef9c9166d5bc573589cb58313056a2ef515ad8
tests/test_misc.py
tests/test_misc.py
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _....
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]) _ = _....
Add test for nesting streamer data-structures.
Add test for nesting streamer data-structures.
Python
mit
caffeine-potent/Streamer-Datastructure
import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stre...
Add test for nesting streamer data-structures.
## Code Before: import mr_streams as ms import unittest from operator import add # :::: auxilary functions :::: def add_one(x): return x + 1 def repeat_n_times(x, n = 1): return [x] * n def double(x): return [x,x] class TestMisc(unittest.TestCase): def test_001(self): _ = ms.stream([1,2,3,4,5]...
30f1156140a4a246a2090aa3e8d5183ceea0beed
tests/test_mmap.py
tests/test_mmap.py
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') ...
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_init_alt_name') ...
Add some more mmap related tests
Add some more mmap related tests
Python
bsd-3-clause
schmichael/mmstats,schmichael/mmstats,schmichael/mmstats,schmichael/mmstats
from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'm...
Add some more mmap related tests
## Code Before: from . import base import os import mmstats class TestMmap(base.MmstatsTestCase): def test_pagesize(self): """PAGESIZE > 0""" self.assertTrue(mmstats.PAGESIZE > 0, mmstats.PAGESIZE) def test_init_alt_name(self): expected_fn = os.path.join(self.path, 'mmstats-test_in...
89a8d6021d8ca8a714af018f3168298109013c6f
radio/__init__.py
radio/__init__.py
from django.utils.version import get_version from subprocess import check_output, CalledProcessError VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProcessError): __g...
import logging from django.utils.version import get_version from subprocess import check_output, CalledProcessError logger = logging.getLogger(__name__) VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() ...
Move version print to logger
Move version print to logger
Python
mit
ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player,ScanOC/trunk-player
+ import logging + from django.utils.version import get_version from subprocess import check_output, CalledProcessError + + logger = logging.getLogger(__name__) + VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short'...
Move version print to logger
## Code Before: from django.utils.version import get_version from subprocess import check_output, CalledProcessError VERSION = (0, 0, 3, 'beta', 1) __version__ = get_version(VERSION) try: __git_hash__ = check_output(['git', 'rev-parse', '--short', 'HEAD']).strip().decode() except (FileNotFoundError, CalledProces...
009113edec59e788bb495b80ddaf763aabd8c82f
GreyMatter/notes.py
GreyMatter/notes.py
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.commit() conn.close() def not...
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.close() def note_something(speech...
Remove unused line of code
Remove unused line of code
Python
mit
Melissa-AI/Melissa-Core,Melissa-AI/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,Melissa-AI/Melissa-Core,anurag-ks/Melissa-Core,anurag-ks/Melissa-Core,anurag-ks/Melissa-Core
import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) - conn.comm...
Remove unused line of code
## Code Before: import sqlite3 from datetime import datetime from SenseCells.tts import tts def show_all_notes(): conn = sqlite3.connect('memory.db') tts('Your notes are as follows:') cursor = conn.execute("SELECT notes FROM notes") for row in cursor: tts(row[0]) conn.commit() conn....
7f42966277eff0d16fd15d5192cffcf7a91aae2e
expyfun/__init__.py
expyfun/__init__.py
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_contr...
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from ._eyelink_contr...
Add `analyze` to `expyfun` init
FIX: Add `analyze` to `expyfun` init
Python
bsd-3-clause
LABSN/expyfun,rkmaddox/expyfun,Eric89GXL/expyfun,lkishline/expyfun,drammock/expyfun
__version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs fr...
Add `analyze` to `expyfun` init
## Code Before: __version__ = '1.1.0.git' # have to import verbose first since it's needed by many things from ._utils import set_log_level, set_config, \ get_config, get_config_path from ._utils import verbose_dec as verbose from ._experiment_controller import ExperimentController, wait_secs from...
9d4dca76abb3f6fb0f107c93874942496f4f8e7b
src/healthcheck/__init__.py
src/healthcheck/__init__.py
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is no...
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message if response is no...
Debug print each health check
Debug print each health check
Python
mit
Vilsepi/nysseituu,Vilsepi/nysseituu
import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = m...
Debug print each health check
## Code Before: import requests class Healthcheck: def __init__(self): pass def _result(self, site, health, response=None, message=None): result = { "name": site["name"], "health": health } if message: result["message"] = message i...
59544c531a4cd52e363bf0714ff51bac779c2018
fleece/httperror.py
fleece/httperror.py
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPRequestHandler.respons...
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler # import lzstring # lz = lzstring.LZString() # lz.decompressFromBase64(SECRET) SECRET = ('FAAj4yrAKVogfQeAlCV9qIDQ0agHTLQxxKK76U0GEKZg' '4Dkl9YA9NADoQfeJQHFiC4gAPgCJJ4np07BZS8OMqy...
Add extra status codes to HTTPError
Add extra status codes to HTTPError
Python
apache-2.0
racker/fleece,racker/fleece
try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler + + # import lzstring + # lz = lzstring.LZString() + # lz.decompressFromBase64(SECRET) + SECRET = ('FAAj4yrAKVogfQeAlCV9qIDQ0agHTLQxxKK76U0GEKZg' + '4Dkl9YA9NADoQfeJQHFiC4...
Add extra status codes to HTTPError
## Code Before: try: from BaseHTTPServer import BaseHTTPRequestHandler except ImportError: from http.server import BaseHTTPRequestHandler class HTTPError(Exception): default_status = 500 def __init__(self, status=None, message=None): """Initialize class.""" responses = BaseHTTPReques...
2c572024bf4e5070c999a3653fbc3f5de679e126
common/responses.py
common/responses.py
from django.http import HttpResponse from django.utils import simplejson def JSONResponse(data): return HttpResponse(simplejson.dumps(data), mimetype='application/json')
from django.http import HttpResponse import json def JSONResponse(data): return HttpResponse(json.dumps(data), content_type='application/json')
Fix JSONResponse to work without complaints on django 1.6
Fix JSONResponse to work without complaints on django 1.6
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
from django.http import HttpResponse - from django.utils import simplejson + import json def JSONResponse(data): - return HttpResponse(simplejson.dumps(data), mimetype='application/json') + return HttpResponse(json.dumps(data), content_type='application/json')
Fix JSONResponse to work without complaints on django 1.6
## Code Before: from django.http import HttpResponse from django.utils import simplejson def JSONResponse(data): return HttpResponse(simplejson.dumps(data), mimetype='application/json') ## Instruction: Fix JSONResponse to work without complaints on django 1.6 ## Code After: from django.http import HttpResponse...
ac0a166f96509c37ade42e9ae4c35f43137bbbbb
mygpoauth/login/urls.py
mygpoauth/login/urls.py
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.login, { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }, name...
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.LoginView.as_view(), { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, }...
Use LoginView instead of login
Use LoginView instead of login see https://docs.djangoproject.com/en/dev/releases/1.11/#django-contrib-auth
Python
agpl-3.0
gpodder/mygpo-auth,gpodder/mygpo-auth
from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ - path('', auth_views.login, { + path('', auth_views.LoginView.as_view(), { 'template_name': 'login/login.html', ...
Use LoginView instead of login
## Code Before: from django.urls import path from django.contrib.auth import views as auth_views from . import views from . import forms app_name = 'login' urlpatterns = [ path('', auth_views.login, { 'template_name': 'login/login.html', 'authentication_form': forms.MyAuthenticationForm, ...
1fdb305233916d766a82a3d92818f2d2fd593752
get_sample_names.py
get_sample_names.py
import sys from statusdb.db import connections as statusdb if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] pcon = statusdb.ProjectSummaryConnection() prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in sorted(prj_samples...
import sys import os from taca.utils.statusdb import ProjectSummaryConnection from taca.utils.config import load_config if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] statusdb_config = os.getenv('STATUS_DB_CONFIG') conf = load_config(statusdb_config) conf = conf.get('statusdb'...
Use tacas statusdb module instead
Use tacas statusdb module instead
Python
mit
SciLifeLab/standalone_scripts,SciLifeLab/standalone_scripts
import sys - from statusdb.db import connections as statusdb + import os + from taca.utils.statusdb import ProjectSummaryConnection + from taca.utils.config import load_config if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] + statusdb_config = os.getenv('STATUS_DB...
Use tacas statusdb module instead
## Code Before: import sys from statusdb.db import connections as statusdb if len(sys.argv) == 1: sys.exit('Please provide a project name') prj = sys.argv[1] pcon = statusdb.ProjectSummaryConnection() prj_obj = pcon.get_entry(prj) prj_samples = prj_obj.get('samples',{}) print("NGI_id\tUser_id") for sample in so...
f551d23531ec4aab041494ac8af921eb77d6b2a0
nb_conda/__init__.py
nb_conda/__init__.py
from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'nbextension/static', 'dest': 'nb_conda', 'require': 'nb_conda/main' }] def _jupyter_server_extension_paths(): return [{ 'require': 'nb_conda.nb...
from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [dict(section="notebook", src="nbextension/static", dest="nb_conda", require="nb_conda/main")] def _jupyter_server_extension_paths(): return [dict(module='nb_conda.nbex...
Update to the latest way to offer metadata
Update to the latest way to offer metadata
Python
bsd-3-clause
Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda,Anaconda-Server/nb_conda
from ._version import version_info, __version__ + def _jupyter_nbextension_paths(): + return [dict(section="notebook", - return [{ - 'section': 'notebook', - 'src': 'nbextension/static', + src="nbextension/static", - 'dest': 'nb_conda', - 'require': 'nb_c...
Update to the latest way to offer metadata
## Code Before: from ._version import version_info, __version__ def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'nbextension/static', 'dest': 'nb_conda', 'require': 'nb_conda/main' }] def _jupyter_server_extension_paths(): return [{ 'requir...
4546054e84f5c352bb7b5e1fc4f9530e8ebfab78
app.py
app.py
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, defau...
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use", type=str, defau...
Use the same format everywhere
[Logging] Use the same format everywhere
Python
mit
HubbeKing/Hubbot_Twisted
import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to u...
Use the same format everywhere
## Code Before: import argparse import logging import os import sys from hubbot.bothandler import BotHandler from newDB import createDB if __name__ == "__main__": parser = argparse.ArgumentParser(description="A derpy Twisted IRC bot.") parser.add_argument("-c", "--config", help="The configuration file to use",...
ad69cbc6814e0458ab27412cfad9519fe30545e0
conanfile.py
conanfile.py
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author...
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage = url author...
Support package in editable mode
Conan: Support package in editable mode Add a method to the recipe that maps the include path to "src" when the package is put into "editable mode". See: https://docs.conan.io/en/latest/developing_packages/editable_packages.html
Python
mit
skypjack/entt,skypjack/entt,skypjack/entt,skypjack/entt
from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepag...
Support package in editable mode
## Code Before: from conans import ConanFile class EnttConan(ConanFile): name = "entt" description = "Gaming meets modern C++ - a fast and reliable entity-component system (ECS) and much more " topics = ("conan," "entt", "gaming", "entity", "ecs") url = "https://github.com/skypjack/entt" homepage ...
0d2816e4ea0bf5a04794456651e79f7db9b2571f
src/jupyter_notebook_gist/config.py
src/jupyter_notebook_gist/config.py
from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', help='The ...
import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', ...
Use six for correct Python2/3 compatibility
Use six for correct Python2/3 compatibility
Python
mpl-2.0
mreid-moz/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mreid-moz/jupyter-notebook-gist
+ import six from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Un...
Use six for correct Python2/3 compatibility
## Code Before: from traitlets.config import LoggingConfigurable from traitlets.traitlets import Unicode class NotebookGist(LoggingConfigurable): oauth_client_id = Unicode( '', help='The GitHub application OAUTH client ID', ).tag(config=True) oauth_client_secret = Unicode( '', ...
54a3cf2994b2620fc3b0e62af8c91b034290e98a
tuskar_ui/infrastructure/dashboard.py
tuskar_ui/infrastructure/dashboard.py
from django.utils.translation import ugettext_lazy as _ import horizon class BasePanels(horizon.PanelGroup): slug = "infrastructure" name = _("Infrastructure") panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history', ...
from django.utils.translation import ugettext_lazy as _ import horizon class Infrastructure(horizon.Dashboard): name = _("Infrastructure") slug = "infrastructure" panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', 'history',...
Remove the Infrastructure panel group
Remove the Infrastructure panel group Remove the Infrastructure panel group, and place the panels directly under the Infrastructure dashboard. Change-Id: I321f9a84dd885732438ad58b6c62c480c9c10e37
Python
apache-2.0
rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui,rdo-management/tuskar-ui
from django.utils.translation import ugettext_lazy as _ import horizon - class BasePanels(horizon.PanelGroup): + class Infrastructure(horizon.Dashboard): + name = _("Infrastructure") slug = "infrastructure" - name = _("Infrastructure") panels = ( 'overview', 'paramet...
Remove the Infrastructure panel group
## Code Before: from django.utils.translation import ugettext_lazy as _ import horizon class BasePanels(horizon.PanelGroup): slug = "infrastructure" name = _("Infrastructure") panels = ( 'overview', 'parameters', 'roles', 'nodes', 'flavors', 'images', ...
de9a6f647d0a6082e2a473895ec61ba23b41753e
controllers/oldauth.py
controllers/oldauth.py
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = db.Query(OldAuth)...
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): u = User().current() user = users.get_current_user() site = self.request.get('site')...
Create users when they log in
Create users when they log in
Python
mit
argoroots/Entu,argoroots/Entu,argoroots/Entu
import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): + + u = User().current() + user = users.get_current_user() ...
Create users when they log in
## Code Before: import hashlib import base64 from datetime import date from bo import * from database.oldauth import * class Login(webapp.RequestHandler): def get(self): if self.request.get('site'): user = users.get_current_user() site = self.request.get('site') oa = d...
cfabcbe0e729eeb3281c4f4b7d6182a29d35f37e
ixprofile_client/fetchers.py
ixprofile_client/fetchers.py
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import inspect import sys import urllib.request from openid.fetchers import Urllib2Fetcher clas...
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import import inspect import sys PY3 = sys.version_info >= (3, 0) # Important: python3-open uses urllib.request, whereas (python2) openid uses # urllib2. You cannot use the c...
Use the correct urllib for the openid we're using
Use the correct urllib for the openid we're using
Python
mit
infoxchange/ixprofile-client,infoxchange/ixprofile-client
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import - from future import standard_library - standard_library.install_aliases() import inspect import sys - import urllib.request + + PY3 = sys.version_info ...
Use the correct urllib for the openid we're using
## Code Before: from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() import inspect import sys import urllib.request from openid.fetchers import Urlli...
72d119ef80c4c84ae3be65c93795832a7250fc51
run.py
run.py
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Gener...
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load(path)) # Gener...
Use linear models by default
Use linear models by default
Python
mit
ogrisel/brain2vec
import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(n...
Use linear models by default
## Code Before: import data import model import numpy as np from keras import optimizers # Localize data through file system relative indexing method path = 'hcp_olivier/102816/MNINonLinear/Results/rfMRI_REST1_LR/rfMRI_REST1_LR.npy' # Use data loading library to load data a, b, y = data.generate_learning_set(np.load...
0fb5a8b5caa99b82845712703bf53f2348227f78
examples/string_expansion.py
examples/string_expansion.py
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) ...
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str, entries))) ...
Fix ordering in string expansion example
Fix ordering in string expansion example
Python
mit
MisanthropicBit/bibpy,MisanthropicBit/bibpy
"""Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.j...
Fix ordering in string expansion example
## Code Before: """Example of expanding and unexpanding string variables in entry fields.""" from __future__ import print_function import bibpy import os def get_path_for(path): return os.path.join(os.path.dirname(os.path.abspath(__file__)), path) def print_entries(entries): print(os.linesep.join(map(str,...
844aff45eb1804b461460368f97af4f73a6b62f0
data_structures/union_find/weighted_quick_union.py
data_structures/union_find/weighted_quick_union.py
class WeightedQuickUnion(object): def __init__(self): self.id = [] self.weight = [] def find(self, val): p = val while self.id[p] != p: p = self.id[p] return self.id[p] def union(self, p, q): p_root = self.find(p) q_root = self.find(q...
class WeightedQuickUnion(object): def __init__(self, data=None): self.id = data self.weight = [1] * len(data) self.count = len(data) def count(self): return self.count def find(self, val): p = val while self.id[p] != p: p = self.id[p] ...
Fix quick union functions issue
Fix quick union functions issue Missing counter Find function should return position of element Decrement counter in union
Python
mit
hongta/practice-python,hongta/practice-python
class WeightedQuickUnion(object): - def __init__(self): + def __init__(self, data=None): - self.id = [] + self.id = data - self.weight = [] + self.weight = [1] * len(data) + self.count = len(data) + + def count(self): + return self.count d...
Fix quick union functions issue
## Code Before: class WeightedQuickUnion(object): def __init__(self): self.id = [] self.weight = [] def find(self, val): p = val while self.id[p] != p: p = self.id[p] return self.id[p] def union(self, p, q): p_root = self.find(p) q_ro...
bddab649c6684f09870983dca97c39eb30b62c06
djangobotcfg/status.py
djangobotcfg/status.py
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # cancelPendingB...
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth def get_status(): return [ html.WebStatus( http_port = '8010', # authz = authz, order_console_by_time = True, revlink = 'http://...
Remove the IRC bot for now, and also the commented-out code.
Remove the IRC bot for now, and also the commented-out code.
Python
bsd-3-clause
hochanh/django-buildmaster,jacobian-archive/django-buildmaster
from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth - - # authz = Authz( - # forceBuild=True, - # forceAllBuilds=True, - # pingBuilder=True, - # gracefulShutdown=True, - # stopBuild=True, - # stopAllBuilds=True...
Remove the IRC bot for now, and also the commented-out code.
## Code Before: from buildbot.status import html, words from buildbot.status.web.authz import Authz from buildbot.status.web.auth import BasicAuth # authz = Authz( # forceBuild=True, # forceAllBuilds=True, # pingBuilder=True, # gracefulShutdown=True, # stopBuild=True, # stopAllBuilds=True, # ...
6bb63c6133db2155c1985d6bb2827f65d5ae3555
ntm/__init__.py
ntm/__init__.py
from . import controllers from . import heads from . import init from . import memory from . import nonlinearities from . import ntm from . import similarities from . import updates
from . import controllers from . import heads from . import init from . import layers from . import memory from . import nonlinearities from . import similarities from . import updates
Fix import name from ntm to layers
Fix import name from ntm to layers
Python
mit
snipsco/ntm-lasagne
from . import controllers from . import heads from . import init + from . import layers from . import memory from . import nonlinearities - from . import ntm from . import similarities from . import updates
Fix import name from ntm to layers
## Code Before: from . import controllers from . import heads from . import init from . import memory from . import nonlinearities from . import ntm from . import similarities from . import updates ## Instruction: Fix import name from ntm to layers ## Code After: from . import controllers from . import heads from . imp...
d7d6819e728edff997c07c6191f882a61d30f219
setup.py
setup.py
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos...
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo-tag your photos...
Make sure to install gpx.xsd in data directory
Make sure to install gpx.xsd in data directory
Python
apache-2.0
tinuzz/taggert
from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program ...
Make sure to install gpx.xsd in data directory
## Code Before: from distutils.core import setup setup(name="taggert", version="1.0", author="Martijn Grendelman", author_email="m@rtijn.net", maintainer="Martijn Grendelman", maintainer_email="m@rtijn.net", description="GTK+ 3 geotagging application", long_description="Taggert is an easy-to-use program to geo...
cf30c07be85cf6408c636ffa34f984ed652cd212
setup.py
setup.py
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'tracer', 'harvester', 'simuvex' ], )
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'rex', 'tracer', 'harvester', 'simuvex' ], )
Add rex as a dependency
Add rex as a dependency
Python
bsd-2-clause
mechaphish/colorguard
from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ + 'rex', 'tracer', 'harvester', 'simuvex' ], )
Add rex as a dependency
## Code Before: from distutils.core import setup import subprocess setup( name='colorguard', version='0.01', packages=['colorguard'], install_requires=[ 'tracer', 'harvester', 'simuvex' ], ) ## Instruction: Add rex as a dependency ## Code After: from d...
c25297735f38d1e2a6ddb6878f919d192f9faedd
GcodeParser.py
GcodeParser.py
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented d...
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise NotImplemented d...
ADD function to return box gcode
ADD function to return box gcode
Python
mit
RootAccessHackerspace/k40-laser-scripts,RootAccessHackerspace/k40-laser-scripts
"""Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" ...
ADD function to return box gcode
## Code Before: """Module containing Gcode parsing functions""" __author__ = "Dylan Armitage" __email__ = "d.armitage89@gmail.com" ####---- Imports ----#### from pygcode import Line, GCodeLinearMove def bounding_box(gcode_file): """Take in file of gcode, return dict of max and min bounding values""" raise N...
b3362c05032b66592b8592ccb94a3ec3f10f815f
project/urls.py
project/urls.py
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$', lambda r: Http...
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth...
Add media server to dev server
Add media server to dev server
Python
bsd-2-clause
dbinetti/barberscore-django,barberscore/barberscore-api,dbinetti/barberscore,dbinetti/barberscore,dbinetti/barberscore-django,barberscore/barberscore-api,barberscore/barberscore-api,barberscore/barberscore-api
from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse + from django.conf import settings + from django.conf.urls.static import static urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls...
Add media server to dev server
## Code Before: from django.conf.urls import ( include, url, ) from django.contrib import admin from django.http import HttpResponse urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('apps.api.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^robots.txt$'...
d730eb0c0df2fb6784f7adcce479c4c9588764b9
spacy/ja/__init__.py
spacy/ja/__init__.py
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): from janome.tokenizer import Tokenizer ...
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): try: from janome.tokenizer import T...
Raise custom ImportError if importing janome fails
Raise custom ImportError if importing janome fails
Python
mit
raphael0202/spaCy,recognai/spaCy,explosion/spaCy,Gregory-Howard/spaCy,recognai/spaCy,spacy-io/spaCy,recognai/spaCy,aikramer2/spaCy,Gregory-Howard/spaCy,honnibal/spaCy,recognai/spaCy,raphael0202/spaCy,explosion/spaCy,Gregory-Howard/spaCy,raphael0202/spaCy,aikramer2/spaCy,spacy-io/spaCy,Gregory-Howard/spaCy,raphael0202/s...
from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): + try: - ...
Raise custom ImportError if importing janome fails
## Code Before: from __future__ import unicode_literals, print_function from os import path from ..language import Language from ..attrs import LANG from ..tokens import Doc from .language_data import * class Japanese(Language): lang = 'ja' def make_doc(self, text): from janome.tokenizer import To...
223872a6f894b429b3784365fe50e139e649d233
chempy/electrochemistry/nernst.py
chempy/electrochemistry/nernst.py
from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_conc_out: float ...
from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None, backend=math): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ...
Add keyword arg for backend for log
Add keyword arg for backend for log Can be used to switch out math module with other modules, ex. sympy for symbolic answers
Python
bsd-2-clause
bjodah/aqchem,bjodah/aqchem,bjodah/chempy,bjodah/chempy,bjodah/aqchem
from __future__ import (absolute_import, division, print_function) import math - def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): + def nernst_potential(ion_conc_out, ion_conc_in, charge, T, + constants=None, units=None, backend=math): """ ...
Add keyword arg for backend for log
## Code Before: from __future__ import (absolute_import, division, print_function) import math def nernst_potential(ion_conc_out, ion_conc_in, charge, T, constants=None, units=None): """ Calculates the Nernst potential using the Nernst equation for a particular ion. Parameters ---------- ion_...
5ea19da9fdd797963a7b7f1f2fd8f7163200b4bc
easy_maps/conf.py
easy_maps/conf.py
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more i...
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOptions for more i...
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
Python
mit
kmike/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps
import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutori...
Check is EASY_MAPS_GOOGLE_MAPS_API_KEY is not None before raising warning.
## Code Before: import warnings from django.conf import settings # pylint: disable=W0611 from appconf import AppConf class EasyMapsSettings(AppConf): CENTER = (-41.3, 32) GEOCODE = 'easy_maps.geocode.google_v3' ZOOM = 16 # See https://developers.google.com/maps/documentation/javascript/tutorial#MapOp...
2d74b55a0c110a836190af819b55673bce2300a0
gaphor/ui/macosshim.py
gaphor/ui/macosshim.py
try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: return Fal...
try: import gi from gi.repository import Gtk if Gtk.get_major_version() == 3: gi.require_version("GtkosxApplication", "1.0") else: raise ValueError() except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Applica...
Fix macos shim for gtk 4
Fix macos shim for gtk 4
Python
lgpl-2.1
amolenaar/gaphor,amolenaar/gaphor
try: import gi + from gi.repository import Gtk + if Gtk.get_major_version() == 3: - gi.require_version("GtkosxApplication", "1.0") + gi.require_version("GtkosxApplication", "1.0") + else: + raise ValueError() except ValueError: macos_init = None else: from gi.r...
Fix macos shim for gtk 4
## Code Before: try: import gi gi.require_version("GtkosxApplication", "1.0") except ValueError: macos_init = None else: from gi.repository import GtkosxApplication macos_app = GtkosxApplication.Application.get() def open_file(macos_app, path, application): if path == __file__: ...
4a84fe0c774638b7a00d37864b6d634200512f99
tests.py
tests.py
import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py")) self....
import inspect import unittest from stacklogger import srcfile currentframe = inspect.currentframe class FakeFrames(object): def fake_method(self): return currentframe() @property def fake_property(self): return currentframe() @classmethod def fake_classmethod(cls): ...
Build fake frames for later testing.
Build fake frames for later testing.
Python
isc
whilp/stacklogger
+ import inspect import unittest from stacklogger import srcfile + + currentframe = inspect.currentframe + + class FakeFrames(object): + + def fake_method(self): + return currentframe() + + @property + def fake_property(self): + return currentframe() + + @classmethod ...
Build fake frames for later testing.
## Code Before: import unittest from stacklogger import srcfile class TestUtils(unittest.TestCase): def test_srcfile(self): self.assertTrue(srcfile("foo.py").endswith("foo.py")) self.assertTrue(srcfile("foo.pyc").endswith("foo.py")) self.assertTrue(srcfile("foo.pyo").endswith("foo.py"...
eba6e117c0a13b49219bb60e773f896b274b6601
tests/_support/configs/collection.py
tests/_support/configs/collection.py
from spec import eq_ from invoke import ctask, Collection @ctask def collection(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(collection) ns.configure({'run': {'echo': True}})
from spec import eq_ from invoke import ctask, Collection @ctask def go(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(go) ns.configure({'run': {'echo': True}})
Fix test fixture to match earlier test change
Fix test fixture to match earlier test change
Python
bsd-2-clause
singingwolfboy/invoke,kejbaly2/invoke,tyewang/invoke,frol/invoke,mattrobenolt/invoke,mkusz/invoke,pfmoore/invoke,mkusz/invoke,pyinvoke/invoke,kejbaly2/invoke,pfmoore/invoke,sophacles/invoke,frol/invoke,pyinvoke/invoke,mattrobenolt/invoke
from spec import eq_ from invoke import ctask, Collection @ctask - def collection(c): + def go(c): c.run('false') # Ensures a kaboom if mocking fails - ns = Collection(collection) + ns = Collection(go) ns.configure({'run': {'echo': True}})
Fix test fixture to match earlier test change
## Code Before: from spec import eq_ from invoke import ctask, Collection @ctask def collection(c): c.run('false') # Ensures a kaboom if mocking fails ns = Collection(collection) ns.configure({'run': {'echo': True}}) ## Instruction: Fix test fixture to match earlier test change ## Code After: from spec import...
c31c54624d7a46dfd9df96e32d2e07246868aecc
tomviz/python/DefaultITKTransform.py
tomviz/python/DefaultITKTransform.py
def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables itk_image_typ...
import tomviz.operators class DefaultITKTransform(tomviz.operators.CancelableOperator): def transform_scalars(self, dataset): """Define this method for Python operators that transform the input array. This example uses an ITK filter to add 10 to each voxel value.""" # Try imports to make...
Change the ITK example to use a simpler ITK filter
Change the ITK example to use a simpler ITK filter
Python
bsd-3-clause
cjh1/tomviz,cryos/tomviz,mathturtle/tomviz,OpenChemistry/tomviz,cjh1/tomviz,thewtex/tomviz,thewtex/tomviz,cryos/tomviz,mathturtle/tomviz,thewtex/tomviz,cjh1/tomviz,cryos/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,OpenChemistry/tomviz,mathturtle/tomviz
+ import tomviz.operators - def transform_scalars(dataset): - """Define this method for Python operators that - transform the input array.""" - from tomviz import utils - import numpy as np - import itk - # Get the current volume as a numpy array. - array = utils.get_array(dataset) + c...
Change the ITK example to use a simpler ITK filter
## Code Before: def transform_scalars(dataset): """Define this method for Python operators that transform the input array.""" from tomviz import utils import numpy as np import itk # Get the current volume as a numpy array. array = utils.get_array(dataset) # Set up some ITK variables ...
8d8b122ecbb306bb53de4ee350104e7627e8b362
app/app/__init__.py
app/app/__init__.py
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_con...
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine = engine_from_con...
Add route for preview request
Add route for preview request
Python
mit
recombinators/snapsat,recombinators/snapsat,recombinators/snapsat
import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') en...
Add route for preview request
## Code Before: import os from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import DBSession, Base def main(global_config, **settings): '''This function returns a Pyramid WSGI application.''' settings['sqlalchemy.url'] = os.environ.get('DATABASE_URL') engine =...
0654d962918327e5143fb9250ad344de26e284eb
electrumx_server.py
electrumx_server.py
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %(message)-100s '...
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-7s %(message)-100s '...
Remove logger name from logs
Remove logger name from logs
Python
mit
thelazier/electrumx,shsmith/electrumx,shsmith/electrumx,erasmospunk/electrumx,erasmospunk/electrumx,thelazier/electrumx
'''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, - format='%(asctime)s %(lev...
Remove logger name from logs
## Code Before: '''Script to kick off the server.''' import logging import traceback from server.env import Env from server.controller import Controller def main(): '''Set up logging and run the server.''' logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)-9s %...
a910cd19890ef02a08aeb05c8ba450b2c59f0352
monitoring/nagios/plugin/__init__.py
monitoring/nagios/plugin/__init__.py
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI from monitoring.nagi...
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
Python
mit
bigbrozer/monitoring.nagios,bigbrozer/monitoring.nagios
from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI + from mon...
Make NagiosPluginHTTP available from monitoring.nagios.plugin package.
## Code Before: from monitoring.nagios.plugin.base import NagiosPlugin from monitoring.nagios.plugin.snmp import NagiosPluginSNMP from monitoring.nagios.plugin.secureshell import NagiosPluginSSH from monitoring.nagios.plugin.database import NagiosPluginMSSQL from monitoring.nagios.plugin.wmi import NagiosPluginWMI ## I...
f794c6ed1f6be231d79ac35759ad76270c3e14e0
brains/mapping/admin.py
brains/mapping/admin.py
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] ...
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x', 'y', 'suburb'] ...
Set everything on the report read only.
Set everything on the report read only.
Python
bsd-3-clause
crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains,crisisking/udbraaains
from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['n...
Set everything on the report read only.
## Code Before: from django.contrib import admin from mapping.models import Location, Report class LocationAdmin(admin.ModelAdmin): fieldsets = ((None, {'fields': ( ('name', 'suburb'), ('x', 'y'), 'building_type' )} ),) list_display = ['name', 'x',...
e76bd7de6a0eb7f46e9e5ce3cdaec44943b848d2
pagseguro/configs.py
pagseguro/configs.py
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX NOTIF...
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = ...
Fix charset default to UTF-8
Fix charset default to UTF-8
Python
mit
vintasoftware/python-pagseguro,rochacbruno/python-pagseguro,rgcarrasqueira/python-pagseguro
class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" + CHARSET = "UTF-8" # ISO-8859-1 NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" ...
Fix charset default to UTF-8
## Code Before: class Config(object): BASE_URL = "https://ws.pagseguro.uol.com.br" VERSION = "/v2/" CHECKOUT_SUFFIX = VERSION + "checkout" NOTIFICATION_SUFFIX = VERSION + "transactions/notifications/%s" TRANSACTION_SUFFIX = VERSION + "transactions/" CHECKOUT_URL = BASE_URL + CHECKOUT_SUFFIX ...
08461a2f61b5a5981a6da9f6ef91a362eed92bfd
pycroft/__init__.py
pycroft/__init__.py
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_data(self._packa...
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = None try: data = pkgutil.get_data(self._package, self._resource) exc...
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
Python
apache-2.0
lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): + data = None + try: - data = (pkgutil.get_data(self._package, self...
Fix config loader (bug in commit:5bdf6e47 / commit:eefe7561)
## Code Before: import json, collections, pkgutil class Config(object): def __init__(self): self._config_data = None self._package = "pycroft" self._resource = "config.json" def load(self): data = (pkgutil.get_data(self._package, self._resource) or pkgutil.get_...
92595871f908aa22d353a2490f851da23f3d1f64
gitcd/Config/FilePersonal.py
gitcd/Config/FilePersonal.py
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filen...
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str): self.filen...
Add .gitcd-personal to .gitignore automaticly
Add .gitcd-personal to .gitignore automaticly
Python
apache-2.0
claudio-walser/gitcd,claudio-walser/gitcd
import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, confi...
Add .gitcd-personal to .gitignore automaticly
## Code Before: import os import yaml from gitcd.Config.Parser import Parser from gitcd.Config.DefaultsPersonal import DefaultsPersonal class FilePersonal: loaded = False filename = ".gitcd-personal" parser = Parser() defaults = DefaultsPersonal() config = False def setFilename(self, configFilename: str...
36da7bdc8402494b5ef3588289739e1696ad6002
docs/_ext/djangodummy/settings.py
docs/_ext/djangodummy/settings.py
STATIC_URL = '/static/'
STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
Fix autodoc support with Django 1.5
Fix autodoc support with Django 1.5
Python
apache-2.0
django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,django-fluent/django-fluent-contents,ixc/django-fluent-contents,pombredanne/django-fluent-contents,jpotterm/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,jpotterm/django-fluent-conte...
STATIC_URL = '/static/' + # Avoid error for missing the secret key + SECRET_KEY = 'docs' +
Fix autodoc support with Django 1.5
## Code Before: STATIC_URL = '/static/' ## Instruction: Fix autodoc support with Django 1.5 ## Code After: STATIC_URL = '/static/' # Avoid error for missing the secret key SECRET_KEY = 'docs'
00b5599e574740680e6c08884510ad605294fad2
tests/conftest.py
tests/conftest.py
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Nee...
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: pytest.skip('Nee...
Use `delete_all` instead of running cypher query
Use `delete_all` instead of running cypher query
Python
mit
wcooley/python-gryaml
"""Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os...
Use `delete_all` instead of running cypher query
## Code Before: """Shared fixtures for :mod:`pytest`.""" from __future__ import print_function, absolute_import import os import pytest # noqa import gryaml from py2neo_compat import py2neo_ver @pytest.fixture def graphdb(): """Fixture connecting to graphdb.""" if 'NEO4J_URI' not in os.environ: ...
e4fde66624f74c4b0bbfae7c7c11a50884a0a73c
pyfr/readers/base.py
pyfr/readers/base.py
from abc import ABCMeta, abstractmethod import uuid class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata mesh['m...
from abc import ABCMeta, abstractmethod import uuid import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add meta...
Fix the HDF5 type of mesh_uuid for imported meshes.
Fix the HDF5 type of mesh_uuid for imported meshes.
Python
bsd-3-clause
BrianVermeire/PyFR,Aerojspark/PyFR
from abc import ABCMeta, abstractmethod import uuid + + import numpy as np class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self...
Fix the HDF5 type of mesh_uuid for imported meshes.
## Code Before: from abc import ABCMeta, abstractmethod import uuid class BaseReader(object, metaclass=ABCMeta): @abstractmethod def __init__(self): pass @abstractmethod def _to_raw_pyfrm(self): pass def to_pyfrm(self): mesh = self._to_raw_pyfrm() # Add metadata...
0af3f7ddd1912d18d502ca1795c596397d9cd495
python/triple-sum.py
python/triple-sum.py
def get_num_special_triplets(list_a, list_b, list_c): num_special_triplets = 0 for b in list_b: len_a_candidates = len([a for a in list_a if a <= b]) len_c_candidates = len([c for c in list_c if c <= b]) num_special_triplets += 1 * len_a_candidates * len_c_candidates return num_spe...
def get_num_special_triplets(list_a, list_b, list_c): # remove duplicates and sort lists list_a = sorted(set(list_a)) list_b = sorted(set(list_b)) list_c = sorted(set(list_c)) num_special_triplets = 0 for b in list_b: len_a_candidates = num_elements_less_than(b, list_a) len_c_c...
Sort lists prior to computing len of candidates
Sort lists prior to computing len of candidates
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
def get_num_special_triplets(list_a, list_b, list_c): + # remove duplicates and sort lists + list_a = sorted(set(list_a)) + list_b = sorted(set(list_b)) + list_c = sorted(set(list_c)) + num_special_triplets = 0 for b in list_b: - len_a_candidates = len([a for a in list_a if a <...
Sort lists prior to computing len of candidates
## Code Before: def get_num_special_triplets(list_a, list_b, list_c): num_special_triplets = 0 for b in list_b: len_a_candidates = len([a for a in list_a if a <= b]) len_c_candidates = len([c for c in list_c if c <= b]) num_special_triplets += 1 * len_a_candidates * len_c_candidates ...
2daee974533d1510a17280cddb5a4dfc147338fa
tests/level/test_map.py
tests/level/test_map.py
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)]...
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2), (3, 3), (4, 4)], level_map.a_star_path(0, 0...
Add test for force_pathable_endpoint pathfind param
Add test for force_pathable_endpoint pathfind param This parameter is intended to allow pathing to adjacent squares of an unpassable square. This is necessary because if you want to pathfind to a monster which blocks a square, you don't want to actually go *onto* the square, you just want to go next to it, presumably ...
Python
mit
MoyTW/RL_Arena_Experiment
import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): - level_map = LevelMap() - level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) + level_map = LevelMap([[LevelTi...
Add test for force_pathable_endpoint pathfind param
## Code Before: import unittest from hunting.level.map import LevelTile, LevelMap class TestPathfinding(unittest.TestCase): def test_basic_diagonal(self): level_map = LevelMap() level_map.set_map([[LevelTile() for _ in range(0, 5)] for _ in range(0, 5)]) self.assertEqual([(1, 1), (2, 2),...
822cc689ce44b1c43ac118b2a13c6d0024d2e194
tests/raw_text_tests.py
tests/raw_text_tests.py
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def raw_text_of_text_element_is_value(): assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) @istest def raw_text_of_paragraph_is_terminated_wit...
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def text_element_is_converted_to_text_content(): element = documents.Text("Hello.") result = extract_raw_text_from_element(element) assert_equal("Hello.", result)...
Make raw text tests consistent with mammoth.js
Make raw text tests consistent with mammoth.js
Python
bsd-2-clause
mwilliamson/python-mammoth
from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest - def raw_text_of_text_element_is_value(): - assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) + def text_element_is_converted_to_...
Make raw text tests consistent with mammoth.js
## Code Before: from nose.tools import istest, assert_equal from mammoth.raw_text import extract_raw_text_from_element from mammoth import documents @istest def raw_text_of_text_element_is_value(): assert_equal("Hello", extract_raw_text_from_element(documents.Text("Hello"))) @istest def raw_text_of_paragraph_i...
fd5387f1bb8ac99ed421c61fdff777316a4d3191
tests/test_publisher.py
tests/test_publisher.py
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state_exchange'] ...
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.chann...
Mark test as xfail so that releases can be cut
Mark test as xfail so that releases can be cut
Python
mit
yougov/mettle,yougov/mettle,yougov/mettle,yougov/mettle
import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event + @pytest.mark.xfail(reason="Need RabbitMQ fixture") def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url))...
Mark test as xfail so that releases can be cut
## Code Before: import pytest import pika from mettle.settings import get_settings from mettle.publisher import publish_event def test_long_routing_key(): settings = get_settings() conn = pika.BlockingConnection(pika.URLParameters(settings.rabbit_url)) chan = conn.channel() exchange = settings['state...
53636a17cd50d704b7b4563d0b23a474677051f4
hub/prototype/config.py
hub/prototype/config.py
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hubs we echo to; no...
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), "some.other.game.tld": (543, "...
Make sure we give an example for two servers.
Make sure we give an example for two servers.
Python
agpl-3.0
madprof/alpha-hub
HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), + "some.ot...
Make sure we give an example for two servers.
## Code Before: HOST = "the.hub.machine.tld" # the servers we listen to; for now each server can just # have one port and secret key on the hub even if it runs # multiple game servers; not sure if we need to allow more # than that yet :-/ SERVERS = { "some.game.server.tld": (42, "somesecret"), } # the other hub...
d185407ac4caf5648ef4c12eab83fec81c307407
tests/test_trackable.py
tests/test_trackable.py
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datastore.find_user(e...
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): ...
Add mock X-Forwarded-For header in trackable tests
Add mock X-Forwarded-For header in trackable tests
Python
mit
pawl/flask-security,reustle/flask-security,jonafato/flask-security,asmodehn/flask-security,quokkaproject/flask-security,LeonhardPrintz/flask-security-fork,dommert/flask-security,LeonhardPrintz/flask-security-fork,fuhrysteve/flask-security,CodeSolid/flask-security,simright/flask-security,inveniosoftware/flask-security-f...
import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) - authenticate(client, email=e) + authenticate(client, email=e, headers={'X-Forw...
Add mock X-Forwarded-For header in trackable tests
## Code Before: import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datas...
3bd9214465547ff6cd0f7ed94edf8dacf10135b5
registration/backends/simple/urls.py
registration/backends/simple/urls.py
from django.conf.urls import include, url from django.views.generic.base import TemplateView from registration.backends.simple.views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', Temp...
from django.conf.urls import include, url from django.views.generic.base import TemplateView from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/$', TemplateView.as_view( ...
Clean up an import in simple backend URLs.
Clean up an import in simple backend URLs.
Python
bsd-3-clause
dirtycoder/django-registration,ubernostrum/django-registration,myimages/django-registration,tdruez/django-registration,awakeup/django-registration
from django.conf.urls import include, url from django.views.generic.base import TemplateView - from registration.backends.simple.views import RegistrationView + from .views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='regist...
Clean up an import in simple backend URLs.
## Code Before: from django.conf.urls import include, url from django.views.generic.base import TemplateView from registration.backends.simple.views import RegistrationView urlpatterns = [ url(r'^register/$', RegistrationView.as_view(), name='registration_register'), url(r'^register/closed/...
4dfbe6ea079b32644c9086351f911ce1a2b2b0e1
easy_maps/geocode.py
easy_maps/geocode.py
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google ...
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tuple using Google...
Resolve the 500 error when google send a no results info
Resolve the 500 error when google send a no results info
Python
mit
duixteam/django-easy-maps,kmike/django-easy-maps,Gonzasestopal/django-easy-maps,kmike/django-easy-maps,bashu/django-easy-maps,bashu/django-easy-maps,Gonzasestopal/django-easy-maps
from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError + class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude)...
Resolve the 500 error when google send a no results info
## Code Before: from __future__ import absolute_import from django.utils.encoding import smart_str from geopy import geocoders from geopy.exc import GeocoderServiceError class Error(Exception): pass def google_v3(address): """ Given an address, return ``(computed_address, (latitude, longitude))`` tup...
25993238cb18212a2b83b2d6b0aa98939d38f192
scripts/lwtnn-split-keras-network.py
scripts/lwtnn-split-keras-network.py
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', ...
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architecture-file-name', ...
Remove Keras from network splitter
Remove Keras from network splitter Keras isn't as stable as h5py and json. This commit removes the keras dependency from the network splitting function.
Python
mit
lwtnn/lwtnn,lwtnn/lwtnn,lwtnn/lwtnn
import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--archite...
Remove Keras from network splitter
## Code Before: import argparse def get_args(): d = '(default: %(default)s)' parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('model') parser.add_argument('-w','--weight-file-name', default='weights.h5', help=d) parser.add_argument('-a', '--architect...
3916efe4a017fe9e0fb1c5fe09b99f374d7a4060
instana/__init__.py
instana/__init__.py
__author__ = 'Instana Inc.' __copyright__ = 'Copyright 2016 Instana Inc.' __credits__ = ['Pavlo Baron'] __license__ = 'MIT' __version__ = '0.0.1' __maintainer__ = 'Pavlo Baron' __email__ = 'pavlo.baron@instana.com' __all__ = ['sensor', 'tracer']
__author__ = 'Instana Inc.' __copyright__ = 'Copyright 2017 Instana Inc.' __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' __version__ = '0.6.6' __maintainer__ = 'Peter Giacomo Lombardo' __email__ = 'peter.lombardo@instana.com' __all__ = ['sensor', 'tracer']
Update module init file; begin version stamping here.
Update module init file; begin version stamping here.
Python
mit
instana/python-sensor,instana/python-sensor
__author__ = 'Instana Inc.' - __copyright__ = 'Copyright 2016 Instana Inc.' + __copyright__ = 'Copyright 2017 Instana Inc.' - __credits__ = ['Pavlo Baron'] + __credits__ = ['Pavlo Baron', 'Peter Giacomo Lombardo'] __license__ = 'MIT' - __version__ = '0.0.1' + __version__ = '0.6.6' - __maintainer__ = 'Pavlo Baron...
Update module init file; begin version stamping here.
## Code Before: __author__ = 'Instana Inc.' __copyright__ = 'Copyright 2016 Instana Inc.' __credits__ = ['Pavlo Baron'] __license__ = 'MIT' __version__ = '0.0.1' __maintainer__ = 'Pavlo Baron' __email__ = 'pavlo.baron@instana.com' __all__ = ['sensor', 'tracer'] ## Instruction: Update module init file; begin version ...
67fd73f8f035ac0e13a64971d9d54662df46a77f
karm/test/__karmutil.py
karm/test/__karmutil.py
import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise "Only one instan...
import sys import os class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: r...
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that. svn path=/trunk/kdepim/; revision=367066
Python
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
import sys import os + + class KarmTestError( Exception ): pass def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None - try: - ( stdin, stdout ) = os.popen2( "dcop" ) + ( stdin, stdout ) = os.popen2( "dcop" ) + l = stdout.readline() + ...
Add KarmTestError we can distinguish and print full tracebacks for unexpected errors. Delete exception trapping--let the test scripts do that.
## Code Before: import sys import os def dcopid(): '''Get dcop id of karm. Fail if more than one instance running.''' id = stdin = stdout = None try: ( stdin, stdout ) = os.popen2( "dcop" ) l = stdout.readline() while l: if l.startswith( "karm" ): if not id: id = l else: raise ...
d237c121955b7249e0e2ab5580d2abc2d19b0f25
noveltorpedo/models.py
noveltorpedo/models.py
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=255) contents = models.TextFie...
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): authors = models.ManyToManyField(Author) title = models.CharField(max_length=255) contents = models.TextField(default='') ...
Allow a story to have many authors
Allow a story to have many authors
Python
mit
NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo,NovelTorpedo/noveltorpedo
from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): - author = models.ForeignKey(Author, on_delete=models.CASCADE) + authors = models.ManyToManyField(Author) ...
Allow a story to have many authors
## Code Before: from django.db import models class Author(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Story(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) title = models.CharField(max_length=255) contents ...
43905a102092bdd50de1f8997cd19cb617b348b3
tests/cart_tests.py
tests/cart_tests.py
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() c...
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502.CPU() c...
Use the reset adder from the banks properly
Use the reset adder from the banks properly
Python
bsd-2-clause
pusscat/refNes
import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): ...
Use the reset adder from the banks properly
## Code Before: import importlib import os import sys import unittest import code import struct code_path = os.path.dirname(__file__) code_path = os.path.join(code_path, os.pardir) sys.path.append(code_path) import MOS6502 class TestCartHeaderParsing(unittest.TestCase): def testMagic(self): cpu = MOS6502...
f0e8999ad139a8da8d3762ee1d318f23928edd9c
tests/modelstest.py
tests/modelstest.py
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), ...
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1", size=1), ...
Fix test after metadata changes
Fix test after metadata changes
Python
apache-2.0
sassoftware/rpath-repeater
import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title=...
Fix test after metadata changes
## Code Before: import testsuite testsuite.setup() from testrunner import testcase from rpath_repeater import models class TestBase(testcase.TestCaseWithWorkDir): pass class ModelsTest(TestBase): def testModelToXml(self): files = models.ImageFiles([ models.ImageFile(title="i1", sha1="s1...
3a5fb18a385ffd0533da94632d917e3c0bcfb051
tests/test_nulls.py
tests/test_nulls.py
from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can deserialize None...
from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None ...
Add a test for saving an empty recurrence object
Add a test for saving an empty recurrence object I wasn't sure whether this would fail on models which don't accept null values. Turns out it's allowed, so we should make sure it stays allowed.
Python
bsd-3-clause
linux2400/django-recurrence,linux2400/django-recurrence,django-recurrence/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,Nikola-K/django-recurrence,FrankSalad/django-recurrence,django-recurrence/django-recurrence
+ from recurrence import Recurrence from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert eve...
Add a test for saving an empty recurrence object
## Code Before: from tests.models import EventWithNulls, EventWithNoNulls import pytest @pytest.mark.django_db def test_recurs_can_be_explicitly_none_if_none_is_allowed(): # Check we can save None correctly event = EventWithNulls.objects.create(recurs=None) assert event.recurs is None # Check we can ...
d8c1c7da47e2568cecc1fd6dff0fec7661b39125
turbosms/routers.py
turbosms/routers.py
class SMSRouter(object): app_label = 'sms' db_name = 'sms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self.app_label: ...
class TurboSMSRouter(object): app_label = 'turbosms' db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == self...
Fix bug in sms router.
Fix bug in sms router.
Python
isc
pmaigutyak/mp-turbosms
- class SMSRouter(object): + class TurboSMSRouter(object): - app_label = 'sms' + app_label = 'turbosms' - db_name = 'sms' + db_name = 'turbosms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name r...
Fix bug in sms router.
## Code Before: class SMSRouter(object): app_label = 'sms' db_name = 'sms' def db_for_read(self, model, **hints): if model._meta.app_label == self.app_label: return self.db_name return None def db_for_write(self, model, **hints): if model._meta.app_label == sel...
5fade4bc26c2637a479a69051cee37a1a859c71a
load_hilma.py
load_hilma.py
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getr...
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse(inputfile).getr...
Use the notice ID as priary key
Use the notice ID as priary key Gentlemen, drop your DBs!
Python
agpl-3.0
jampekka/openhilma
import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): r...
Use the notice ID as priary key
## Code Before: import xml.etree.ElementTree as ET import sys import pymongo from pathlib import Path import argh from xml2json import etree_to_dict from hilma_conversion import get_handler hilma_to_dict = lambda notice: etree_to_dict(notice, get_handler) def load_hilma_xml(inputfile, collection): root = ET.parse...
8bc2b19e9aef410832555fb9962c243f0d4aef96
brink/decorators.py
brink/decorators.py
def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be passed to the han...
import asyncio def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be ...
Add decorator for using websocket subhandlers
Add decorator for using websocket subhandlers
Python
bsd-3-clause
brinkframework/brink
+ import asyncio + + def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. ...
Add decorator for using websocket subhandlers
## Code Before: def require_request_model(cls, *args, validate=True, **kwargs): """ Makes a handler require that a request body that map towards the given model is provided. Unless the ``validate`` option is set to ``False`` the data will be validated against the model's fields. The model will be p...
2501bb03e836ac29cc1defa8591446ff217771b2
tests/test_model.py
tests/test_model.py
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender =...
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicode() gender =...
Fix of tests with unicode strings
Fix of tests with unicode strings
Python
bsd-3-clause
ets-labs/domain_models,ets-labs/python-domain-models,rmk135/domain_models
"""Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name =...
Fix of tests with unicode strings
## Code Before: """Sample unittests.""" import unittest2 as unittest from domain_models import model from domain_models import fields class User(model.DomainModel): """Example user domain model.""" id = fields.Int() email = fields.String() first_name = fields.Unicode() last_name = fields.Unicod...
cb798ae8f7f6e810a87137a56cd04be76596a2dd
photutils/tests/test_psfs.py
photutils/tests/test_psfs.py
from __future__ import division import numpy as np from astropy.tests.helper import pytest from photutils.psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.para...
from __future__ import division import numpy as np from astropy.tests.helper import pytest from ..psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @pytest.mark.parametrize(('w...
Use relative imports for consistency; pep8
Use relative imports for consistency; pep8
Python
bsd-3-clause
larrybradley/photutils,astropy/photutils
from __future__ import division - import numpy as np - from astropy.tests.helper import pytest - from photutils.psf import GaussianPSF + from ..psf import GaussianPSF - try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0...
Use relative imports for consistency; pep8
## Code Before: from __future__ import division import numpy as np from astropy.tests.helper import pytest from photutils.psf import GaussianPSF try: from scipy import optimize HAS_SCIPY = True except ImportError: HAS_SCIPY = False widths = [0.001, 0.01, 0.1, 1] @pytest.mark.skipif('not HAS_SCIPY') @...
65fd070a88e06bb040e8c96babc6b4c86ca29730
validatish/error.py
validatish/error.py
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ ...
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message __unicode__ ...
Hide Python 2.6 Exception.message deprecation warnings
Hide Python 2.6 Exception.message deprecation warnings
Python
bsd-3-clause
ish/validatish,ish/validatish
class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self....
Hide Python 2.6 Exception.message deprecation warnings
## Code Before: class Invalid(Exception): def __init__(self, message, exceptions=None, validator=None): Exception.__init__(self, message, exceptions) self.message = message self.exceptions = exceptions self.validator = validator def __str__(self): return self.message ...
356dd5294280db3334f86354202f0d68881254b9
joerd/check.py
joerd/check.py
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.test...
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result = zip_file.test...
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
Python
mit
mapzen/joerd,tilezen/joerd
import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') ...
Return verifier function, not None. Also reset the temporary file to the beginning before verifying it.
## Code Before: import zipfile import tarfile import shutil import tempfile from osgeo import gdal def is_zip(tmp): """ Returns True if the NamedTemporaryFile given as the argument appears to be a well-formed Zip file. """ try: zip_file = zipfile.ZipFile(tmp.name, 'r') test_result...
d84e6aa022ef5e256807738c35e5069a0a1380d7
app/main/forms/frameworks.py
app/main/forms/frameworks.py
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide t...
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="You must provide t...
Add form for accepting contract variation
Add form for accepting contract variation
Python
mit
alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend,alphagov/digitalmarketplace-supplier-frontend
from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="...
Add form for accepting contract variation
## Code Before: from flask.ext.wtf import Form from wtforms import BooleanField from wtforms.validators import DataRequired, Length from dmutils.forms import StripWhitespaceStringField class SignerDetailsForm(Form): signerName = StripWhitespaceStringField('Full name', validators=[ DataRequired(message="Yo...
75171ed80079630d22463685768072ad7323e653
boundary/action_installed.py
boundary/action_installed.py
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions associated with the Boundary account"
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions configured within a Boundary account"
Change code to be PEP-8 compliant
Change code to be PEP-8 compliant
Python
apache-2.0
boundary/boundary-api-cli,boundary/boundary-api-cli,jdgwartney/boundary-api-cli,jdgwartney/pulse-api-cli,wcainboundary/boundary-api-cli,wcainboundary/boundary-api-cli,jdgwartney/pulse-api-cli,boundary/pulse-api-cli,jdgwartney/boundary-api-cli,boundary/pulse-api-cli
from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): - return "Returns the actions associated with the Bou...
Change code to be PEP-8 compliant
## Code Before: from api_cli import ApiCli class ActionInstalled (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/actions/installed" def getDescription(self): return "Returns the actions associated with the Boundary ...
57bc8b3c40bbafda6f69b23c230ad73750e881ab
hashable/helpers.py
hashable/helpers.py
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equality_comparable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equality_comparabl...
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equalable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = equalable(cls, attributes, m...
Rename decorator equality_comparable to equalable
Rename decorator equality_comparable to equalable
Python
mit
minmax/hashable
from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', - 'equality_comparable', + 'equalable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def d...
Rename decorator equality_comparable to equalable
## Code Before: from .equals_builder import EqualsBuilder from .hash_code_builder import HashCodeBuilder __all__ = [ 'hashable', 'equality_comparable', ] def hashable(cls=None, attributes=None, methods=None): _validate_attributes_and_methods(attributes, methods) def decorator(cls): cls = eq...
4f6e27a6bbc2bbdb19c165f21d47d1491bffd70e
scripts/mc_check_lib_file.py
scripts/mc_check_lib_file.py
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] for pathname in args.f...
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] with db.sessionmaker()...
Move sessionmaker outside of loop
Move sessionmaker outside of loop
Python
bsd-2-clause
HERA-Team/hera_mc,HERA-Team/hera_mc
import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_fil...
Move sessionmaker outside of loop
## Code Before: import os from hera_mc import mc ap = mc.get_mc_argument_parser() ap.description = """Check that listed files are safely in librarian.""" ap.add_argument("files", type=str, default=None, nargs="*", help="list of files") args = ap.parse_args() db = mc.connect_to_mc_db(args) found_files = [] for pa...
a3213788d0d8591b235359d4b17886ce3f50ab37
tests/test_plugin.py
tests/test_plugin.py
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open('./datajoint.pub', "r") as f: as...
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources from os import path def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open(path.join(path.abspa...
Make pubkey test more portable.
Make pubkey test more portable.
Python
lgpl-2.1
datajoint/datajoint-python,dimitri-yatsenko/datajoint-python
import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources + from os import path def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) - with o...
Make pubkey test more portable.
## Code Before: import datajoint.errors as djerr import datajoint.plugin as p import pkg_resources def test_check_pubkey(): base_name = 'datajoint' base_meta = pkg_resources.get_distribution(base_name) pubkey_meta = base_meta.get_metadata('{}.pub'.format(base_name)) with open('./datajoint.pub', "r") ...
bc5475bcc3608de75c42d24c5c74e416b41b873f
pages/base.py
pages/base.py
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() ...
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator).click() ...
Make username and password required arguments
Make username and password required arguments
Python
mpl-2.0
mozilla/mozwebqa-examples,davehunt/mozwebqa-examples,mozilla/mozwebqa-examples,davehunt/mozwebqa-examples
from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._lo...
Make username and password required arguments
## Code Before: from selenium.webdriver.common.by import By from page import Page class Base(Page): _login_locator = (By.ID, 'login') _logout_locator = (By.ID, 'logout') _notification_locator = (By.CLASS_NAME, 'flash') def click_login(self): self.selenium.find_element(*self._login_locator)...
54bce2a224843ec9c1c8b7eb35cdc6bf19d5726b
expensonator/api.py
expensonator/api.py
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() ...
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tags_as_string() ...
Fix key error when no tags are specified
Fix key error when no tags are specified
Python
mit
matt-haigh/expensonator
from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle...
Fix key error when no tags are specified
## Code Before: from tastypie.authorization import Authorization from tastypie.fields import CharField from tastypie.resources import ModelResource from expensonator.models import Expense class ExpenseResource(ModelResource): tags = CharField() def dehydrate_tags(self, bundle): return bundle.obj.tag...
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...
caf9795cf0f775442bd0c3e06cd550a6e8d0206b
virtool/labels/db.py
virtool/labels/db.py
async def count_samples(db, label_id): return await db.samples.count_documents({"labels": {"$in": [label_id]}})
async def attach_sample_count(db, document, label_id): document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
Rewrite function for sample count
Rewrite function for sample count
Python
mit
virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool
- async def count_samples(db, label_id): + async def attach_sample_count(db, document, label_id): - return await db.samples.count_documents({"labels": {"$in": [label_id]}}) + document.update({"count": await db.samples.count_documents({"labels": {"$in": [label_id]}})})
Rewrite function for sample count
## Code Before: async def count_samples(db, label_id): return await db.samples.count_documents({"labels": {"$in": [label_id]}}) ## Instruction: Rewrite function for sample count ## Code After: async def attach_sample_count(db, document, label_id): document.update({"count": await db.samples.count_documents({"la...
51e7cd3bc5a9a56fb53a5b0a8328d0b9d58848dd
modder/utils/desktop_notification.py
modder/utils/desktop_notification.py
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title='Modder', soun...
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, title=None, sound=Fa...
Fix title for desktop notification
Fix title for desktop notification
Python
mit
JokerQyou/Modder2
import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') - def desktop_notify(text, ...
Fix title for desktop notification
## Code Before: import platform if platform.system() == 'Darwin': from Foundation import NSUserNotificationDefaultSoundName import objc NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') def desktop_notify(text, titl...
8a7837a8ce7b35c3141374c6a5c99361261fa70a
Cura/avr_isp/chipDB.py
Cura/avr_isp/chipDB.py
avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False
avrChipDB = { 'ATMega1280': { 'signature': [0x1E, 0x97, 0x03], 'pageSize': 128, 'pageCount': 512, }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: ret...
Add ATMega1280 chip to programmer chips.
Add ATMega1280 chip to programmer chips.
Python
agpl-3.0
MolarAmbiguity/OctoPrint,EZ3-India/EZ-Remote,JackGavin13/octoprint-test-not-finished,spapadim/OctoPrint,dragondgold/OctoPrint,hudbrog/OctoPrint,CapnBry/OctoPrint,Javierma/OctoPrint-TFG,chriskoz/OctoPrint,javivi001/OctoPrint,shohei/Octoprint,eddieparker/OctoPrint,MolarAmbiguity/OctoPrint,mayoff/OctoPrint,uuv/OctoPrint,C...
avrChipDB = { + 'ATMega1280': { + 'signature': [0x1E, 0x97, 0x03], + 'pageSize': 128, + 'pageCount': 512, + }, 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if...
Add ATMega1280 chip to programmer chips.
## Code Before: avrChipDB = { 'ATMega2560': { 'signature': [0x1E, 0x98, 0x01], 'pageSize': 128, 'pageCount': 1024, }, } def getChipFromDB(sig): for chip in avrChipDB.values(): if chip['signature'] == sig: return chip return False ## Instruction: Add ATMega1280 chip to programmer chips. ## Code After:...
ef96000b01c50a77b3500fc4071f83f96d7b2458
mrbelvedereci/api/views/cumulusci.py
mrbelvedereci/api/views/cumulusci.py
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelved...
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter from mrbelved...
Remove ServiceFilter from view since it's not needed. Service only has name and json
Remove ServiceFilter from view since it's not needed. Service only has name and json
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci
from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilter f...
Remove ServiceFilter from view since it's not needed. Service only has name and json
## Code Before: from django.shortcuts import render from mrbelvedereci.api.serializers.cumulusci import OrgSerializer from mrbelvedereci.api.serializers.cumulusci import ScratchOrgInstanceSerializer from mrbelvedereci.api.serializers.cumulusci import ServiceSerializer from mrbelvedereci.cumulusci.filters import OrgFilt...
24f0402e27ce7e51f370e82aa74c783438875d02
oslo_db/tests/sqlalchemy/__init__.py
oslo_db/tests/sqlalchemy/__init__.py
from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__)
from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
Remove deprecation warning when loading tests/sqlalchemy /home/sam/Work/ironic/.tox/py27/local/lib/python2.7/site-packages/oslo_db/tests/sqlalchemy/__init__.py:20: DeprecationWarning: Function 'oslo_db.sqlalchemy.test_base.optimize_db_test_loader()' has moved to 'oslo_db.sqlalchemy.test_fixtures.optimize_package_test_...
Python
apache-2.0
openstack/oslo.db,openstack/oslo.db
- from oslo_db.sqlalchemy import test_base + from oslo_db.sqlalchemy import test_fixtures - load_tests = test_base.optimize_db_test_loader(__file__) + load_tests = test_fixtures.optimize_package_test_loader(__file__)
Remove deprecation warning when loading tests/sqlalchemy
## Code Before: from oslo_db.sqlalchemy import test_base load_tests = test_base.optimize_db_test_loader(__file__) ## Instruction: Remove deprecation warning when loading tests/sqlalchemy ## Code After: from oslo_db.sqlalchemy import test_fixtures load_tests = test_fixtures.optimize_package_test_loader(__file__)
db6cb95d5d4261780482b4051f556fcbb2d9f237
rest_api/forms.py
rest_api/forms.py
from django.forms import ModelForm from rest_api.models import Url class UrlForm(ModelForm): class Meta: model = Url
from django.forms import ModelForm from gateway_backend.models import Url class UrlForm(ModelForm): class Meta: model = Url
Remove Url model from admin
Remove Url model from admin
Python
bsd-2-clause
victorpoluceno/shortener_frontend,victorpoluceno/shortener_frontend
from django.forms import ModelForm + - from rest_api.models import Url + from gateway_backend.models import Url class UrlForm(ModelForm): class Meta: model = Url
Remove Url model from admin
## Code Before: from django.forms import ModelForm from rest_api.models import Url class UrlForm(ModelForm): class Meta: model = Url ## Instruction: Remove Url model from admin ## Code After: from django.forms import ModelForm from gateway_backend.models import Url class UrlForm(ModelForm): class Me...
3410fba1c8a39156def029eac9c7ff9f779832e6
dev/ci.py
dev/ci.py
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) if sys.v...
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(deps_dir) # In ...
Fix CI to ignore system install of asn1crypto
Fix CI to ignore system install of asn1crypto
Python
mit
wbond/oscrypto
from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.adds...
Fix CI to ignore system install of asn1crypto
## Code Before: from __future__ import unicode_literals, division, absolute_import, print_function import os import site import sys from . import build_root, requires_oscrypto from ._import import _preload deps_dir = os.path.join(build_root, 'modularcrypto-deps') if os.path.exists(deps_dir): site.addsitedir(dep...
502d99042428175b478e796c067e41995a0ae5bf
picoCTF-web/api/apps/v1/__init__.py
picoCTF-web/api/apps/v1/__init__.py
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from...
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as exceptions_ns from...
Fix PicoException response code bug
Fix PicoException response code bug
Python
mit
royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF,picoCTF/picoCTF,picoCTF/picoCTF,royragsdale/picoCTF
"""picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns...
Fix PicoException response code bug
## Code Before: """picoCTF API v1 app.""" from flask import Blueprint, jsonify from flask_restplus import Api from api.common import PicoException from .achievements import ns as achievements_ns from .problems import ns as problems_ns from .shell_servers import ns as shell_servers_ns from .exceptions import ns as ex...
5d71215645683a059a51407a3768054c9ea77406
pisite/logs/forms.py
pisite/logs/forms.py
from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow)
from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.defaultLinesToShow)
Add to the label that 0 lines will result in the entire file being downloaded
Add to the label that 0 lines will result in the entire file being downloaded
Python
mit
sizlo/RPiFun,sizlo/RPiFun
from django import forms from logs.models import Log class LineCountForm(forms.Form): - linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) + linesToFetch = forms.IntegerField(label="Number of lines to show (0 for all)", min_value=0, initial=Log.d...
Add to the label that 0 lines will result in the entire file being downloaded
## Code Before: from django import forms from logs.models import Log class LineCountForm(forms.Form): linesToFetch = forms.IntegerField(label="Number of lines to show", min_value=0, initial=Log.defaultLinesToShow) ## Instruction: Add to the label that 0 lines will result in the entire file being downloaded ## Code A...
a389f20c7f2c8811a5c2f50c43a9ce5c7f3c8387
jobs_backend/vacancies/serializers.py
jobs_backend/vacancies/serializers.py
from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.HyperlinkedModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_o...
from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.ModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_on', 'modified_on' ...
Fix for correct resolve URL
jobs-010: Fix for correct resolve URL
Python
mit
pyshopml/jobs-backend,pyshopml/jobs-backend
from rest_framework import serializers from .models import Vacancy - class VacancySerializer(serializers.HyperlinkedModelSerializer): + class VacancySerializer(serializers.ModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy field...
Fix for correct resolve URL
## Code Before: from rest_framework import serializers from .models import Vacancy class VacancySerializer(serializers.HyperlinkedModelSerializer): """ Common vacancy model serializer """ class Meta: model = Vacancy fields = ( 'id', 'url', 'title', 'description', 'created_...
441a1b85f6ab954ab89f32977e4f00293270aac6
sphinxcontrib/multilatex/__init__.py
sphinxcontrib/multilatex/__init__.py
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=================...
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #=================...
Set LaTeX builder to skip latex_document nodes
Set LaTeX builder to skip latex_document nodes This stops Sphinx' built-in LaTeX builder from complaining about unknown latex_document node type.
Python
apache-2.0
t4ngo/sphinxcontrib-multilatex,t4ngo/sphinxcontrib-multilatex
import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passth...
Set LaTeX builder to skip latex_document nodes
## Code Before: import directive import builder #=========================================================================== # Node visitor functions def visit_passthrough(self, node): pass def depart_passthrough(self, node): pass passthrough = (visit_passthrough, depart_passthrough) #==================...
5c11a65af1d51794133895ebe2de92861b0894cf
flask_limiter/errors.py
flask_limiter/errors.py
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions werkzeug_exception = None werkzeug_version = get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersion("0.9"): # pra...
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions class RateLimitExceeded(exceptions.TooManyRequests): """exception raised when a rate limit is hit. The exception results in ``abort(429...
Remove backward compatibility hack for exception subclass
Remove backward compatibility hack for exception subclass
Python
mit
alisaifee/flask-limiter,alisaifee/flask-limiter
"""errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions - werkzeug_exception = None - werkzeug_version = get_distribution("werkzeug").version - if LooseVersion(werkzeug_version) < LooseVe...
Remove backward compatibility hack for exception subclass
## Code Before: """errors and exceptions.""" from distutils.version import LooseVersion from pkg_resources import get_distribution from six import text_type from werkzeug import exceptions werkzeug_exception = None werkzeug_version = get_distribution("werkzeug").version if LooseVersion(werkzeug_version) < LooseVersio...
b3979a46a7bcd71aa9b40892167910fdeed5ad97
frigg/projects/admin.py
frigg/projects/admin.py
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): ...
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, obj=None): ...
Return empty tuple in get_readonly_fields
fix: Return empty tuple in get_readonly_fields
Python
mit
frigg/frigg-hq,frigg/frigg-hq,frigg/frigg-hq
from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(r...
Return empty tuple in get_readonly_fields
## Code Before: from django.contrib import admin from django.template.defaultfilters import pluralize from .forms import EnvironmentVariableForm from .models import EnvironmentVariable, Project class EnvironmentVariableMixin: form = EnvironmentVariableForm @staticmethod def get_readonly_fields(request, ...
0d7c0b045c4a2e930fe0d7aa68b96d5a99916a34
scripts/document_path_handlers.py
scripts/document_path_handlers.py
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the ...
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the description for all the ...
Make path handlers list horizontal
Make path handlers list horizontal Signed-off-by: Chris Warrick <de6f931166e131a07f31c96c765aee08f061d1a5@gmail.com>
Python
mit
s2hc-johan/nikola,wcmckee/nikola,gwax/nikola,x1101/nikola,okin/nikola,masayuko/nikola,xuhdev/nikola,wcmckee/nikola,gwax/nikola,knowsuchagency/nikola,atiro/nikola,andredias/nikola,gwax/nikola,xuhdev/nikola,atiro/nikola,x1101/nikola,okin/nikola,knowsuchagency/nikola,wcmckee/nikola,okin/nikola,getnikola/nikola,masayuko/ni...
from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the ...
Make path handlers list horizontal
## Code Before: from __future__ import print_function, unicode_literals from nikola import nikola n = nikola.Nikola() n.init_plugins() print(""".. title: Path Handlers for Nikola .. slug: path-handlers .. author: The Nikola Team Nikola supports special links with the syntax ``link://kind/name``. Here is the descript...
c6d50c3feed444f8f450c5c140e8470c6897f2bf
societies/models.py
societies/models.py
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the soci...
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) #: the soci...
Make the Guitar Society __str__ Method a bit more Logical
Make the Guitar Society __str__ Method a bit more Logical
Python
bsd-3-clause
chrisguitarguy/GuitarSocieties.org,chrisguitarguy/GuitarSocieties.org
from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max...
Make the Guitar Society __str__ Method a bit more Logical
## Code Before: from django.db import models from django_countries.fields import CountryField class GuitarSociety(models.Model): """ Represents a single guitar society. .. versionadded:: 0.1 """ #: the name of the society #: ..versionadded:: 0.1 name = models.CharField(max_length=1024) ...
c7a209d2c4455325f1d215ca1c12074b394ae00e
gitdir/host/__init__.py
gitdir/host/__init__.py
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not s...
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Host {} does not s...
Add status messages to `gitdir update`
Add status messages to `gitdir update`
Python
mit
fenhl/gitdir
import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImpl...
Add status messages to `gitdir update`
## Code Before: import abc import subprocess import gitdir class Host(abc.ABC): @abc.abstractmethod def __iter__(self): raise NotImplementedError() @abc.abstractmethod def __str__(self): raise NotImplementedError() def clone(self, repo_spec): raise NotImplementedError('Ho...